(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 this.limit) {
this.buffer.shift();
}
}
/**
* gets the array-index for the given pointer
* @param {number} pointer
* @return {number|null} arrayIndex which can be used to itterate from there. If null, pointer is out of lower bound
*/
}, {
key: "getArrayIndexByPointer",
value: function getArrayIndexByPointer(pointer) {
var oldestEvent = this.buffer[0];
var oldestCounter = this.eventCounterMap.get(oldestEvent);
if (pointer < oldestCounter) return null; // out of bounds
var rest = pointer - oldestCounter;
return rest;
}
/**
* get all changeEvents which came in later than the pointer-event
* @param {number} pointer
* @return {RxChangeEvent[]|null} array with change-events. Iif null, pointer out of bounds
*/
}, {
key: "getFrom",
value: function getFrom(pointer) {
var ret = [];
var currentIndex = this.getArrayIndexByPointer(pointer);
if (currentIndex === null) // out of bounds
return null;
while (true) {
var nextEvent = this.buffer[currentIndex];
currentIndex++;
if (!nextEvent) return ret;else ret.push(nextEvent);
}
}
}, {
key: "runFrom",
value: function runFrom(pointer, fn) {
this.getFrom(pointer).forEach(function (cE) {
return fn(cE);
});
}
/**
* no matter how many operations are done on one document,
* only the last operation has to be checked to calculate the new state
* this function reduces the events to the last ChangeEvent of each doc
* @param {ChangeEvent[]} changeEvents
* @return {ChangeEvents[]}
*/
}, {
key: "reduceByLastOfDoc",
value: function reduceByLastOfDoc(changeEvents) {
var docEventMap = {};
changeEvents.forEach(function (changeEvent) {
docEventMap[changeEvent.data.doc] = changeEvent;
});
return Object.values(docEventMap);
}
}, {
key: "destroy",
value: function destroy() {
this.subs.forEach(function (sub) {
return sub.unsubscribe();
});
}
}]);
return ChangeEventBuffer;
}();
function create(collection) {
return new ChangeEventBuffer(collection);
}
exports["default"] = {
create: create
};
},{"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51}],3:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isRxSchema = exports.isRxQuery = exports.isRxDocument = exports.isRxCollection = exports.isRxDatabase = exports.plugin = exports.checkAdapter = exports.removeDatabase = exports.create = undefined;
var _rxDatabase = require('./rx-database');
var _rxDatabase2 = _interopRequireDefault(_rxDatabase);
var _rxSchema = require('./rx-schema');
var _rxSchema2 = _interopRequireDefault(_rxSchema);
var _rxDocument = require('./rx-document');
var _rxDocument2 = _interopRequireDefault(_rxDocument);
var _rxQuery = require('./rx-query');
var _rxQuery2 = _interopRequireDefault(_rxQuery);
var _rxCollection = require('./rx-collection');
var _rxCollection2 = _interopRequireDefault(_rxCollection);
var _queryChangeDetector = require('./query-change-detector');
var _queryChangeDetector2 = _interopRequireDefault(_queryChangeDetector);
var _plugin = require('./plugin');
var _plugin2 = _interopRequireDefault(_plugin);
var _pouchDb = require('./pouch-db');
var _pouchDb2 = _interopRequireDefault(_pouchDb);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* this is the main entry-point for custom builds
* it can be used as standalone but is also used in the batteries-included main-export
*/
var create = exports.create = _rxDatabase2['default'].create;
var removeDatabase = exports.removeDatabase = _rxDatabase2['default'].removeDatabase;
var checkAdapter = exports.checkAdapter = _rxDatabase2['default'].checkAdapter;
var plugin = exports.plugin = _plugin2['default'].addPlugin;
var isRxDatabase = exports.isRxDatabase = _rxDatabase2['default'].isInstanceOf;
var isRxCollection = exports.isRxCollection = _rxCollection2['default'].isInstanceOf;
var isRxDocument = exports.isRxDocument = _rxDocument2['default'].isInstanceOf;
var isRxQuery = exports.isRxQuery = _rxQuery2['default'].isInstanceOf;
var isRxSchema = exports.isRxSchema = _rxSchema2['default'].isInstanceOf;
exports['default'] = {
create: create,
removeDatabase: removeDatabase,
checkAdapter: checkAdapter,
plugin: plugin,
isRxDatabase: isRxDatabase,
isRxCollection: isRxCollection,
isRxDocument: isRxDocument,
isRxQuery: isRxQuery,
isRxSchema: isRxSchema,
RxSchema: _rxSchema2['default'],
PouchDB: _pouchDb2['default'],
QueryChangeDetector: _queryChangeDetector2['default'],
RxDatabase: _rxDatabase2['default']
};
},{"./plugin":12,"./pouch-db":25,"./query-change-detector":27,"./rx-collection":30,"./rx-database":31,"./rx-document":32,"./rx-query":34,"./rx-schema":35}],4:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Crypter = undefined;
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 _objectPath = require('object-path');
var _objectPath2 = _interopRequireDefault(_objectPath);
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var Crypter = exports.Crypter = function () {
function Crypter(password, schema) {
(0, _classCallCheck3['default'])(this, Crypter);
this._password = password;
this._schema = schema;
}
/**
* encrypt and stringify data
* @overwritten by plugin (optional)
* @param {any} value
* @return {string}
*/
(0, _createClass3['default'])(Crypter, [{
key: '_encryptValue',
value: function _encryptValue() {
throw _rxError2['default'].pluginMissing('encryption');
}
/**
* decrypt and json-parse an encrypted value
* @overwritten by plugin (optional)
* @param {string} encValue
* @return {any}
*/
}, {
key: '_decryptValue',
value: function _decryptValue() {
throw _rxError2['default'].pluginMissing('encryption');
}
}, {
key: 'encrypt',
value: function encrypt(obj) {
var _this = this;
obj = (0, _clone2['default'])(obj);
if (!this._password) return obj;
Object.keys(this._schema.encryptedPaths).map(function (path) {
var value = _objectPath2['default'].get(obj, path);
var encrypted = _this._encryptValue(value);
_objectPath2['default'].set(obj, path, encrypted);
});
return obj;
}
}, {
key: 'decrypt',
value: function decrypt(obj) {
var _this2 = this;
obj = (0, _clone2['default'])(obj);
if (!this._password) return obj;
Object.keys(this._schema.encryptedPaths).map(function (path) {
var value = _objectPath2['default'].get(obj, path);
var decrypted = _this2._decryptValue(value);
_objectPath2['default'].set(obj, path, decrypted);
});
return obj;
}
}]);
return Crypter;
}(); /**
* handle the en/decryption of documents-data
*/
function create(password, schema) {
return new Crypter(password, schema);
}
exports['default'] = {
create: create,
Crypter: Crypter
};
},{"./rx-error":33,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"clone":63,"object-path":567}],5:[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 _pouchDb = require('./pouch-db');
var _pouchDb2 = _interopRequireDefault(_pouchDb);
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _rxSchema = require('./rx-schema');
var _rxSchema2 = _interopRequireDefault(_rxSchema);
var _crypter = require('./crypter');
var _crypter2 = _interopRequireDefault(_crypter);
var _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
var _overwritable = require('./overwritable');
var _overwritable2 = _interopRequireDefault(_overwritable);
var _hooks = require('./hooks');
var _hooks2 = _interopRequireDefault(_hooks);
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 }; }
/**
* The DataMigrator handles the documents from collections with older schemas
* and transforms/saves them into the newest collection
*/
var DataMigrator = function () {
function DataMigrator(newestCollection, migrationStrategies) {
(0, _classCallCheck3['default'])(this, DataMigrator);
this.newestCollection = newestCollection;
this.migrationStrategies = migrationStrategies;
this.currentSchema = newestCollection.schema;
this.database = newestCollection.database;
this.name = newestCollection.name;
}
/**
* get an array with OldCollection-instances from all existing old pouchdb-instance
* @return {Promise}
*/
(0, _createClass3['default'])(DataMigrator, [{
key: '_getOldCollections',
value: function _getOldCollections() {
var _this = this;
return Promise.all(this.currentSchema.previousVersions.map(function (v) {
return _this.database._collectionsPouch.get(_this.name + '-' + v);
}).map(function (fun) {
return fun['catch'](function () {
return null;
});
}) // auto-catch so Promise.all continues
).then(function (oldColDocs) {
return oldColDocs.filter(function (colDoc) {
return colDoc !== null;
}).map(function (colDoc) {
return new OldCollection(colDoc.schema.version, colDoc.schema, _this);
});
});
}
/**
* @param {number} [batchSize=10] amount of documents handled in parallel
* @return {Observable} emits the migration-state
*/
}, {
key: 'migrate',
value: function migrate() {
var _this2 = this;
var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
if (this._migrated) throw new Error('Migration has already run');
this._migrated = true;
var state = {
done: false, // true if finished
total: null, // will be the doc-count
handled: 0, // amount of handled docs
success: 0, // handled docs which successed
deleted: 0, // handled docs which got deleted
percent: 0 // percentage
};
var migrationState$ = new util.Rx.Observable(function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee(observer) {
var oldCols, countAll, totalCount, currentCol, _loop;
return _regenerator2['default'].wrap(function _callee$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return _this2._getOldCollections();
case 2:
oldCols = _context2.sent;
_context2.next = 5;
return Promise.all(oldCols.map(function (oldCol) {
return oldCol.countAllUndeleted();
}));
case 5:
countAll = _context2.sent;
totalCount = countAll.reduce(function (cur, prev) {
return prev = cur + prev;
}, 0);
state.total = totalCount;
observer.next((0, _clone2['default'])(state));
currentCol = null;
_loop = /*#__PURE__*/_regenerator2['default'].mark(function _loop() {
var migrationState$;
return _regenerator2['default'].wrap(function _loop$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
migrationState$ = currentCol.migrate(batchSize);
_context.next = 3;
return new Promise(function (res) {
var sub = migrationState$.subscribe(function (subState) {
state.handled++;
state[subState.type] = state[subState.type] + 1;
state.percent = Math.round(state.handled / state.total * 100);
observer.next((0, _clone2['default'])(state));
}, function (e) {
sub.unsubscribe();
observer.error(e);
}, function () {
sub.unsubscribe();
res();
});
});
case 3:
case 'end':
return _context.stop();
}
}
}, _loop, _this2);
});
case 11:
if (!(currentCol = oldCols.shift())) {
_context2.next = 15;
break;
}
return _context2.delegateYield(_loop(), 't0', 13);
case 13:
_context2.next = 11;
break;
case 15:
state.done = true;
state.percent = 100;
observer.next((0, _clone2['default'])(state));
observer.complete();
case 19:
case 'end':
return _context2.stop();
}
}
}, _callee, _this2);
}));
return function (_x2) {
return _ref.apply(this, arguments);
};
}());
return migrationState$;
}
}, {
key: 'migratePromise',
value: function migratePromise(batchSize) {
var _this3 = this;
if (!this._migratePromise) {
this._migratePromise = new Promise(function (res, rej) {
var state$ = _this3.migrate(batchSize);
state$.subscribe(null, rej, res);
});
}
return this._migratePromise;
}
}]);
return DataMigrator;
}();
var OldCollection = function () {
function OldCollection(version, schemaObj, dataMigrator) {
(0, _classCallCheck3['default'])(this, OldCollection);
this.version = version;
this.dataMigrator = dataMigrator;
this.schemaObj = schemaObj;
this.newestCollection = dataMigrator.newestCollection;
this.database = dataMigrator.newestCollection.database;
}
(0, _createClass3['default'])(OldCollection, [{
key: 'countAllUndeleted',
value: function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
return _regenerator2['default'].wrap(function _callee2$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt('return', _pouchDb2['default'].countAllUndeleted(this.pouchdb));
case 1:
case 'end':
return _context3.stop();
}
}
}, _callee2, this);
}));
function countAllUndeleted() {
return _ref2.apply(this, arguments);
}
return countAllUndeleted;
}()
}, {
key: 'getBatch',
value: function getBatch(batchSize) {
var _this4 = this;
return _pouchDb2['default'].getBatch(this.pouchdb, batchSize).then(function (docs) {
return docs.map(function (doc) {
return _this4._handleFromPouch(doc);
});
});
}
/**
* handles a document from the pouchdb-instance
*/
}, {
key: '_handleFromPouch',
value: function _handleFromPouch(docData) {
var data = (0, _clone2['default'])(docData);
data = this.schema.swapIdToPrimary(docData);
if (this.schema.doKeyCompression()) data = this.keyCompressor.decompress(data);
data = this.crypter.decrypt(data);
return data;
}
/**
* wrappers for Pouch.put/get to handle keycompression etc
*/
}, {
key: '_handleToPouch',
value: function _handleToPouch(docData) {
var data = (0, _clone2['default'])(docData);
data = this.crypter.encrypt(data);
data = this.schema.swapPrimaryToId(data);
if (this.schema.doKeyCompression()) data = this.keyCompressor.compress(data);
return data;
}
/**
* runs the doc-data through all following migrationStrategies
* so it will match the newest schema.
* @throws Error if final doc does not match final schema or migrationStrategy crashes
* @return {Object|null} final object or null if migrationStrategy deleted it
*/
}, {
key: 'migrateDocumentData',
value: function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3(doc) {
var nextVersion;
return _regenerator2['default'].wrap(function _callee3$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
doc = (0, _clone2['default'])(doc);
nextVersion = this.version + 1;
// run throught migrationStrategies
case 2:
if (!(nextVersion <= this.newestCollection.schema.version)) {
_context4.next = 11;
break;
}
_context4.next = 5;
return this.dataMigrator.migrationStrategies[nextVersion + ''](doc);
case 5:
doc = _context4.sent;
nextVersion++;
if (!(doc === null)) {
_context4.next = 9;
break;
}
return _context4.abrupt('return', null);
case 9:
_context4.next = 2;
break;
case 11:
_context4.prev = 11;
this.newestCollection.schema.validate(doc);
_context4.next = 18;
break;
case 15:
_context4.prev = 15;
_context4.t0 = _context4['catch'](11);
throw _rxError2['default'].newRxError('migration of document from v' + this.version + ' to v' + this.newestCollection.schema.version + ' failed\n final document does not match final schema', {
finalDoc: doc
});
case 18:
return _context4.abrupt('return', doc);
case 19:
case 'end':
return _context4.stop();
}
}
}, _callee3, this, [[11, 15]]);
}));
function migrateDocumentData(_x3) {
return _ref3.apply(this, arguments);
}
return migrateDocumentData;
}()
/**
* transform docdata and save to new collection
* @return {{type: string, doc: {}}} status-action with status and migrated document
*/
}, {
key: '_migrateDocument',
value: function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4(doc) {
var migrated, action, res;
return _regenerator2['default'].wrap(function _callee4$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return this.migrateDocumentData(doc);
case 2:
migrated = _context5.sent;
action = {
doc: doc,
migrated: migrated,
oldCollection: this,
newestCollection: this.newestCollection
};
if (!migrated) {
_context5.next = 16;
break;
}
_hooks2['default'].runPluginHooks('preMigrateDocument', action);
// save to newest collection
delete migrated._rev;
_context5.next = 9;
return this.newestCollection._pouchPut(migrated, true);
case 9:
res = _context5.sent;
action.res = res;
action.type = 'success';
_context5.next = 14;
return _hooks2['default'].runAsyncPluginHooks('postMigrateDocument', action);
case 14:
_context5.next = 17;
break;
case 16:
action.type = 'deleted';
case 17:
_context5.prev = 17;
_context5.next = 20;
return this.pouchdb.remove(this._handleToPouch(doc));
case 20:
_context5.next = 24;
break;
case 22:
_context5.prev = 22;
_context5.t0 = _context5['catch'](17);
case 24:
return _context5.abrupt('return', action);
case 25:
case 'end':
return _context5.stop();
}
}
}, _callee4, this, [[17, 22]]);
}));
function _migrateDocument(_x4) {
return _ref4.apply(this, arguments);
}
return _migrateDocument;
}()
/**
* deletes this.pouchdb and removes it from the database.collectionsCollection
* @return {Promise}
*/
}, {
key: 'delete',
value: function _delete() {
var _this5 = this;
return this.pouchdb.destroy().then(function () {
return _this5.database.removeCollectionDoc(_this5.dataMigrator.name, _this5.schema);
});
}
/**
* runs the migration on all documents and deletes the pouchdb afterwards
*/
}, {
key: 'migrate',
value: function migrate() {
var _this6 = this;
var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
if (this._migrate) throw new Error('migration already running');
this._migrate = true;
var stateStream$ = new util.Rx.Observable(function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5(observer) {
var batch, error;
return _regenerator2['default'].wrap(function _callee5$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return _this6.getBatch(batchSize);
case 2:
batch = _context6.sent;
error = void 0;
case 4:
_context6.next = 6;
return Promise.all(batch.map(function (doc) {
return _this6._migrateDocument(doc).then(function (action) {
return observer.next(action);
});
}))['catch'](function (e) {
return error = e;
});
case 6:
if (!error) {
_context6.next = 9;
break;
}
observer.error(error);
return _context6.abrupt('return');
case 9:
_context6.next = 11;
return _this6.getBatch(batchSize);
case 11:
batch = _context6.sent;
case 12:
if (!error && batch.length > 0) {
_context6.next = 4;
break;
}
case 13:
_context6.next = 15;
return _this6['delete']();
case 15:
observer.complete();
case 16:
case 'end':
return _context6.stop();
}
}
}, _callee5, _this6);
}));
return function (_x6) {
return _ref5.apply(this, arguments);
};
}());
return stateStream$;
}
}, {
key: 'migratePromise',
value: function migratePromise(batchSize) {
var _this7 = this;
if (!this._migratePromise) {
this._migratePromise = new Promise(function (res, rej) {
var state$ = _this7.migrate(batchSize);
state$.subscribe(null, rej, res);
});
}
return this._migratePromise;
}
}, {
key: 'schema',
get: function get() {
if (!this._schema) {
// delete this.schemaObj._id;
this._schema = _rxSchema2['default'].create(this.schemaObj, false);
}
return this._schema;
}
}, {
key: 'keyCompressor',
get: function get() {
if (!this._keyCompressor) this._keyCompressor = _overwritable2['default'].createKeyCompressor(this.schema);
return this._keyCompressor;
}
}, {
key: 'crypter',
get: function get() {
if (!this._crypter) this._crypter = _crypter2['default'].create(this.database.password, this.schema);
return this._crypter;
}
}, {
key: 'pouchdb',
get: function get() {
if (!this._pouchdb) {
this._pouchdb = this.database._spawnPouchDB(this.newestCollection.name, this.version, this.newestCollection.pouchSettings);
}
return this._pouchdb;
}
}]);
return OldCollection;
}();
function create(newestCollection, migrationStrategies) {
return new DataMigrator(newestCollection, migrationStrategies);
}
exports['default'] = {
create: create
};
},{"./crypter":4,"./hooks":7,"./overwritable":11,"./pouch-db":25,"./rx-error":33,"./rx-schema":35,"./util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/regenerator":57,"clone":63}],6:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// TODO add a function to run a cache-clear
var DocCache = function () {
function DocCache() {
(0, _classCallCheck3["default"])(this, DocCache);
this._map = {};
}
(0, _createClass3["default"])(DocCache, [{
key: "get",
value: function get(id) {
return this._map[id];
}
}, {
key: "set",
value: function set(id, obj) {
return this._map[id] = obj;
}
}, {
key: "delete",
value: function _delete(id) {
delete this._map[id];
}
}]);
return DocCache;
}();
;
function create() {
return new DocCache();
}
exports["default"] = {
create: create
};
},{"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51}],7:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.runAsyncPluginHooks = exports.HOOKS = undefined;
var _regenerator = require("babel-runtime/regenerator");
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require("babel-runtime/helpers/asyncToGenerator");
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var runAsyncPluginHooks = exports.runAsyncPluginHooks = function () {
var _ref = (0, _asyncToGenerator3["default"])( /*#__PURE__*/_regenerator2["default"].mark(function _callee(hookKey, obj) {
return _regenerator2["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", Promise.all(HOOKS[hookKey].map(function (fun) {
return fun(obj);
})));
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
return function runAsyncPluginHooks(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
exports.runPluginHooks = runPluginHooks;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* stores the hooks that where added by the plugins
*/
/**
* hook-functions that can be extended by the plugin
*/
var HOOKS = exports.HOOKS = {
createRxDatabase: [],
createRxCollection: [],
/**
* functions that get the json-schema as input
* to do additionally checks/manipulation
*/
preCreateRxSchema: [],
/**
* functions that run after the RxSchema is created
* gets RxSchema as attribute
*/
createRxSchema: [],
createRxQuery: [],
createRxDocument: [],
/**
* runs before a pouchdb-instance is created
* gets pouchParameters as attribute so you can manipulate them
* {
* location: string,
* adapter: any,
* settings: object
* }
* @type {Array}
*/
preCreatePouchDb: [],
/**
* runs on the document-data before the document is migrated
* {
* doc: Object, // originam doc-data
* migrated: // migrated doc-data after run throught migration-strategies
* }
* @type {Array}
*/
preMigrateDocument: [],
/**
* runs after the migration of a document has been done
* @type {Array}
*/
postMigrateDocument: []
};
function runPluginHooks(hookKey, obj) {
HOOKS[hookKey].forEach(function (fun) {
return fun(obj);
});
}
;
exports["default"] = {
runPluginHooks: runPluginHooks,
runAsyncPluginHooks: runAsyncPluginHooks,
HOOKS: HOOKS
};
},{"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/regenerator":57}],8:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.checkAdapter = exports.RxDatabase = exports.QueryChangeDetector = exports.PouchDB = exports.RxSchema = exports.isRxSchema = exports.isRxQuery = exports.isRxDocument = exports.isRxCollection = exports.isRxDatabase = exports.plugin = exports.removeDatabase = exports.create = undefined;
var _core = require('./core');
var _core2 = _interopRequireDefault(_core);
var _schemaCheck = require('./plugins/schema-check');
var _schemaCheck2 = _interopRequireDefault(_schemaCheck);
var _validate = require('./plugins/validate');
var _validate2 = _interopRequireDefault(_validate);
var _keyCompression = require('./plugins/key-compression');
var _keyCompression2 = _interopRequireDefault(_keyCompression);
var _leaderElection = require('./plugins/leader-election');
var _leaderElection2 = _interopRequireDefault(_leaderElection);
var _encryption = require('./plugins/encryption');
var _encryption2 = _interopRequireDefault(_encryption);
var _update = require('./plugins/update');
var _update2 = _interopRequireDefault(_update);
var _replication = require('./plugins/replication');
var _replication2 = _interopRequireDefault(_replication);
var _adapterCheck = require('./plugins/adapter-check');
var _adapterCheck2 = _interopRequireDefault(_adapterCheck);
var _jsonDump = require('./plugins/json-dump');
var _jsonDump2 = _interopRequireDefault(_jsonDump);
var _inMemory = require('./plugins/in-memory');
var _inMemory2 = _interopRequireDefault(_inMemory);
var _attachments = require('./plugins/attachments');
var _attachments2 = _interopRequireDefault(_attachments);
var _localDocuments = require('./plugins/local-documents');
var _localDocuments2 = _interopRequireDefault(_localDocuments);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* this is the default rxdb-export
* It has a batteries-included guarantee.
* It basically just rxdb-core with some default plugins
*/
_core2['default'].plugin(_schemaCheck2['default']);
// default plugins
_core2['default'].plugin(_validate2['default']);
_core2['default'].plugin(_keyCompression2['default']);
_core2['default'].plugin(_leaderElection2['default']);
_core2['default'].plugin(_encryption2['default']);
_core2['default'].plugin(_update2['default']);
_core2['default'].plugin(_replication2['default']);
_core2['default'].plugin(_adapterCheck2['default']);
_core2['default'].plugin(_jsonDump2['default']);
_core2['default'].plugin(_inMemory2['default']);
_core2['default'].plugin(_attachments2['default']);
_core2['default'].plugin(_localDocuments2['default']);
/**
* 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 = _core2['default'].create;
/**
* removes the database and all its known data
* @param {string} databaseName
* @param {Object} adapter
* @return {Promise}
*/
var removeDatabase = exports.removeDatabase = _core2['default'].removeDatabase;
/**
* add a plugin for rxdb or pouchdb
*/
var plugin = exports.plugin = _core2['default'].plugin;
var isRxDatabase = exports.isRxDatabase = _core2['default'].isRxDatabase;
var isRxCollection = exports.isRxCollection = _core2['default'].isRxCollection;
var isRxDocument = exports.isRxDocument = _core2['default'].isRxDocument;
var isRxQuery = exports.isRxQuery = _core2['default'].isRxQuery;
var isRxSchema = exports.isRxSchema = _core2['default'].isRxSchema;
var RxSchema = exports.RxSchema = _core2['default'].RxSchema;
var PouchDB = exports.PouchDB = _core2['default'].PouchDB;
var QueryChangeDetector = exports.QueryChangeDetector = _core2['default'].QueryChangeDetector;
var RxDatabase = exports.RxDatabase = _core2['default'].RxDatabase;
var checkAdapter = exports.checkAdapter = _core2['default'].checkAdapter;
exports['default'] = {
create: create,
checkAdapter: checkAdapter,
removeDatabase: removeDatabase,
plugin: plugin,
isRxDatabase: isRxDatabase,
isRxCollection: isRxCollection,
isRxDocument: isRxDocument,
isRxQuery: isRxQuery,
isRxSchema: isRxSchema,
RxSchema: RxSchema,
PouchDB: PouchDB,
QueryChangeDetector: QueryChangeDetector,
RxDatabase: RxDatabase
};
},{"./core":3,"./plugins/adapter-check":13,"./plugins/attachments":14,"./plugins/encryption":15,"./plugins/in-memory":16,"./plugins/json-dump":17,"./plugins/key-compression":18,"./plugins/leader-election":19,"./plugins/local-documents":20,"./plugins/replication":21,"./plugins/schema-check":22,"./plugins/update":23,"./plugins/validate":24}],9:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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);
var _mquery_utils = require('./mquery_utils');
var utils = _interopRequireWildcard(_mquery_utils);
var _clone2 = require('clone');
var _clone3 = _interopRequireDefault(_clone2);
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 is based on
* @link https://github.com/aheckmann/mquery/blob/master/lib/mquery.js
*/
var MQuery = function () {
/**
* MQuery constructor used for building queries.
*
* ####Example:
* var query = new MQuery({ name: 'mquery' });
* query.where('age').gte(21).exec(callback);
*
* @param {Object} [criteria]
*/
function MQuery(criteria) {
(0, _classCallCheck3['default'])(this, MQuery);
var proto = this.constructor.prototype;
this.options = {};
this._conditions = proto._conditions ? (0, _clone3['default'])(proto._conditions) : {};
this._fields = proto._fields ? (0, _clone3['default'])(proto._fields) : undefined;
this._path = proto._path || undefined;
if (criteria) this.find(criteria);
}
/**
* returns a cloned version of the query
* @return {MQuery}
*/
(0, _createClass3['default'])(MQuery, [{
key: 'clone',
value: function clone() {
var same = new MQuery();
Object.entries(this).forEach(function (entry) {
same[entry[0]] = (0, _clone3['default'])(entry[1]);
});
return same;
}
/**
* Specifies a `path` for use with chaining.
* @param {String} [path]
* @param {Object} [val]
* @return {MQuery} this
*/
}, {
key: 'where',
value: function where() {
if (!arguments.length) return this;
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);
* @param {Object} val
* @return {MQuery} this
*/
}, {
key: 'equals',
value: 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`
* @param {Object} val
* @return {MQuery} this
*/
}, {
key: 'eq',
value: 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 {MQuery} this
*/
}, {
key: 'or',
value: function or(array) {
var or = this._conditions.$or || (this._conditions.$or = []);
if (!Array.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 {MQuery} this
*/
}, {
key: 'nor',
value: function nor(array) {
var nor = this._conditions.$nor || (this._conditions.$nor = []);
if (!Array.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 {MQuery} this
*/
}, {
key: 'and',
value: 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 `$mod` condition
*
* @param {String} [path]
* @param {Number} val
* @return {MQuery} this
* @api public
*/
}, {
key: 'mod',
value: function mod() {
var val = void 0;
var path = void 0;
if (1 === arguments.length) {
this._ensurePath('mod');
val = arguments[0];
path = this._path;
} else if (2 === arguments.length && !Array.isArray(arguments[1])) {
this._ensurePath('mod');
val = arguments.slice();
path = this._path;
} else if (3 === arguments.length) {
val = arguments.slice(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')
* @param {String} [path]
* @param {Number} val
* @return {MQuery} this
* @api public
*/
}, {
key: 'exists',
value: function exists() {
var path = void 0;
var val = void 0;
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 {MQuery} this
*/
}, {
key: 'elemMatch',
value: function elemMatch() {
if (null === arguments[0]) throw new TypeError('Invalid argument');
var fn = void 0;
var path = void 0;
var criteria = void 0;
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 MQuery();
fn(criteria);
criteria = criteria._conditions;
}
var conds = this._conditions[path] || (this._conditions[path] = {});
conds.$elemMatch = criteria;
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
* query.sort({ field: 'asc', test: -1 });
* query.sort('field -test');
* query.sort([['field', 1], ['test', -1]]);
* @param {Object|String|Array} arg
* @return {MQuery} this
*/
}, {
key: 'sort',
value: function sort(arg) {
var _this = this;
if (!arg) return this;
var len = void 0;
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 = Object.keys(arg);
keys.forEach(function (field) {
return push(_this.options, field, arg[field]);
});
return this;
}
throw new TypeError('Invalid sort() argument. Must be a string, object, or array.');
}
/**
* Merges another MQuery or conditions object into this one.
*
* When a MQuery is passed, conditions, field selection and options are merged.
*
* @param {MQuery|Object} source
* @return {MQuery} this
*/
}, {
key: 'merge',
value: function merge(source) {
if (!source) return this;
if (!MQuery.canMerge(source)) throw new TypeError('Invalid argument. Expected instanceof mquery or plain object');
if (source instanceof MQuery) {
// 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.
* ####Example
* query.find()
* query.find({ name: 'Burning Lights' })
* @param {Object} [criteria] mongodb selector
* @return {MQuery} this
*/
}, {
key: 'find',
value: function find(criteria) {
if (MQuery.canMerge(criteria)) this.merge(criteria);
return this;
}
/**
* Returns default options.
* @return {Object}
*/
}, {
key: '_optionsForExec',
value: function _optionsForExec() {
var options = (0, _clone3['default'])(this.options);
return options;
}
/**
* Make sure _path is set.
*
* @parmam {String} method
*/
}, {
key: '_ensurePath',
value: function _ensurePath(method) {
if (!this._path) {
throw new Error('\n ' + method + '() must be used after where()\n when called with these arguments\n ');
}
}
}]);
return MQuery;
}();
/**
* 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'].forEach(function ($conditional) {
MQuery.prototype[$conditional] = function () {
var path = void 0;
var val = void 0;
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;
};
});
/*!
* @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 (Array.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('\n Can\'t mix sort syntaxes. Use either array or object:\n \n- .sort([[\'field\', 1], [\'test\', -1]])\n \n- .sort({ field: 1, test: -1 })');
}
/* const valueStr = value.toString()
.replace('asc', '1')
.replace('ascending', '1')
.replace('desc', '-1')
.replace('descending', '-1');*/
opts.sort.push([field, value]);
};
/**
* Determines if `conds` can be merged using `mquery().merge()`
*
* @param {Object} conds
* @return {Boolean}
*/
MQuery.canMerge = function (conds) {
return conds instanceof MQuery || utils.isObject(conds);
};
/**
* limit, skip, maxScan, batchSize, comment
*
* Sets these associated options.
*
* query.comment('feed query');
*/
['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function (method) {
MQuery.prototype[method] = function (v) {
this.options[method] = v;
return this;
};
});
MQuery.utils = utils;
exports['default'] = MQuery;
},{"./mquery_utils":10,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/typeof":56,"clone":63}],10:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.merge = merge;
exports.mergeClone = mergeClone;
exports.isObject = isObject;
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Merges `from` into `to` without overwriting existing properties.
*
* @param {object} to
* @param {object} from
*/
function merge(to, from) {
var keys = Object.keys(from);
var i = keys.length;
var key = void 0;
while (i--) {
key = keys[i];
if ('undefined' === typeof to[key]) to[key] = from[key];else {
if (isObject(from[key])) merge(to[key], from[key]);else to[key] = from[key];
}
}
} /**
* this is copied from
* @link https://github.com/aheckmann/mquery/blob/master/lib/utils.js
*/
;
/**
* Same as merge but clones the assigned values.
*
* @param {object} to
* @param {object} from
*/
function mergeClone(to, from) {
var keys = Object.keys(from);
var i = keys.length;
var key = void 0;
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] = (0, _clone2['default'])(from[key], {
retainKeyOrder: 1
});
} else {
if (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] = (0, _clone2['default'])(from[key], {
retainKeyOrder: 1
});
}
}
}
};
/**
* Determines if `arg` is an object.
*
* @param {Object|Array|String|Function|RegExp|any} arg
* @return {Boolean}
*/
function isObject(arg) {
return '[object Object]' === arg.toString();
};
},{"clone":63}],11:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var funs = {
/**
* validates if a password can be used
* @overwritten by plugin (optional)
* @param {any} password
* @throws if password not valid
* @return {void}
*/
validatePassword: function validatePassword() {
throw _rxError2['default'].pluginMissing('encryption');
},
/**
* creates a key-compressor for the given schema
* @param {RxSchema} schema
* @return {KeyCompressor}
*/
createKeyCompressor: function createKeyCompressor() {
throw _rxError2['default'].pluginMissing('keycompression');
},
/**
* creates a leader-elector for the given database
* @param {RxDatabase} database
* @return {LeaderElector}
*/
createLeaderElector: function createLeaderElector() {
throw _rxError2['default'].pluginMissing('leaderelection');
},
/**
* checks if the given adapter can be used
* @return {any} adapter
*/
checkAdapter: function checkAdapter() {
throw _rxError2['default'].pluginMissing('adapter-check');
}
}; /**
* functions that can or should be overwritten by plugins
*/
exports['default'] = funs;
},{"./rx-error":33}],12:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
exports.addPlugin = addPlugin;
var _rxSchema = require('./rx-schema');
var _rxSchema2 = _interopRequireDefault(_rxSchema);
var _crypter = require('./crypter');
var _crypter2 = _interopRequireDefault(_crypter);
var _rxDocument = require('./rx-document');
var _rxDocument2 = _interopRequireDefault(_rxDocument);
var _rxQuery = require('./rx-query');
var _rxQuery2 = _interopRequireDefault(_rxQuery);
var _rxCollection = require('./rx-collection');
var _rxCollection2 = _interopRequireDefault(_rxCollection);
var _rxDatabase = require('./rx-database');
var _rxDatabase2 = _interopRequireDefault(_rxDatabase);
var _pouchDb = require('./pouch-db');
var _pouchDb2 = _interopRequireDefault(_pouchDb);
var _overwritable = require('./overwritable');
var _overwritable2 = _interopRequireDefault(_overwritable);
var _hooks = require('./hooks');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* prototypes that can be manipulated with a plugin
* @type {Object}
*/
var PROTOTYPES = {
RxSchema: _rxSchema2['default'].RxSchema.prototype,
Crypter: _crypter2['default'].Crypter.prototype,
RxDocument: _rxDocument2['default'].RxDocument.prototype,
RxQuery: _rxQuery2['default'].RxQuery.prototype,
RxCollection: _rxCollection2['default'].RxCollection.prototype,
RxDatabase: _rxDatabase2['default'].RxDatabase.prototype
}; /**
* this handles how plugins are added to rxdb
* basically it changes the internal prototypes
* by passing them to the plugins-functions
*/
function addPlugin(plugin) {
if (!plugin.rxdb) {
// pouchdb-plugin
if ((typeof plugin === 'undefined' ? 'undefined' : (0, _typeof3['default'])(plugin)) === 'object' && plugin['default']) plugin = plugin['default'];
_pouchDb2['default'].plugin(plugin);
}
// prototype-overwrites
if (plugin.prototypes) {
Object.entries(plugin.prototypes).forEach(function (entry) {
var name = entry[0];
var fun = entry[1];
fun(PROTOTYPES[name]);
});
}
// overwritable-overwrites
if (plugin.overwritable) {
Object.entries(plugin.overwritable).forEach(function (entry) {
var name = entry[0];
var fun = entry[1];
_overwritable2['default'][name] = fun;
});
}
// extend-hooks
if (plugin.hooks) {
Object.entries(plugin.hooks).forEach(function (entry) {
var name = entry[0];
var fun = entry[1];
_hooks.HOOKS[name].push(fun);
});
}
}
exports['default'] = {
addPlugin: addPlugin,
overwritable: _overwritable2['default']
};
},{"./crypter":4,"./hooks":7,"./overwritable":11,"./pouch-db":25,"./rx-collection":30,"./rx-database":31,"./rx-document":32,"./rx-query":34,"./rx-schema":35,"babel-runtime/helpers/typeof":56}],13:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwritable = exports.prototypes = exports.rxdb = exports.checkAdapter = undefined;
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
/**
* this plugin adds the checkAdapter-function to rxdb
* you can use it to check if the given adapter is working in the current environmet
*/
var checkAdapter = exports.checkAdapter = function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee(adapter) {
var id, recoveredDoc, pouch;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
id = 'rxdb-test-adapter-' + util.generateId();
recoveredDoc = null;
pouch = void 0;
_context.prev = 3;
pouch = new _pouchDb2['default'](id, util.adapterObject(adapter), {
auto_compaction: false, // no compaction because this only stores local documents
revs_limit: 1
});
_context.next = 7;
return pouch.info();
case 7:
_context.next = 9;
return pouch.put({
_id: id,
value: true
});
case 9:
_context.next = 11;
return pouch.get(id);
case 11:
recoveredDoc = _context.sent;
_context.next = 17;
break;
case 14:
_context.prev = 14;
_context.t0 = _context['catch'](3);
return _context.abrupt('return', false);
case 17:
_context.prev = 17;
_context.next = 20;
return pouch.destroy();
case 20:
_context.next = 24;
break;
case 22:
_context.prev = 22;
_context.t1 = _context['catch'](17);
case 24:
if (!(recoveredDoc && recoveredDoc.value)) {
_context.next = 28;
break;
}
return _context.abrupt('return', true);
case 28:
return _context.abrupt('return', false);
case 29:
case 'end':
return _context.stop();
}
}
}, _callee, this, [[3, 14], [17, 22]]);
}));
return function checkAdapter(_x) {
return _ref.apply(this, arguments);
};
}();
var _pouchDb = require('../pouch-db');
var _pouchDb2 = _interopRequireDefault(_pouchDb);
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 rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {};
var overwritable = exports.overwritable = {
checkAdapter: checkAdapter
};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable
};
},{"../pouch-db":25,"../util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/regenerator":57}],14:[function(require,module,exports){
(function (Buffer){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hooks = exports.overwritable = exports.prototypes = exports.rxdb = exports.postMigrateDocument = exports.preMigrateDocument = exports.putAttachment = exports.RxAttachment = exports.blobBufferUtil = undefined;
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var resyncRxDocument = function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee(doc) {
var docData, data, changeEvent;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return doc.collection.pouch.get(doc.primary);
case 2:
docData = _context.sent;
data = doc.collection._handleFromPouch(docData);
changeEvent = _rxChangeEvent2['default'].create('UPDATE', doc.collection.database, doc.collection, doc, data);
doc.$emit(changeEvent);
case 6:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function resyncRxDocument(_x) {
return _ref.apply(this, arguments);
};
}();
var putAttachment = exports.putAttachment = function () {
var _ref7 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee6(_ref6) {
var _this = this;
var id = _ref6.id,
data = _ref6.data,
_ref6$type = _ref6.type,
type = _ref6$type === undefined ? 'text/plain' : _ref6$type;
var queue, blobBuffer, ret;
return _regenerator2['default'].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
ensureSchemaSupportsAttachments(this);
queue = getAtomicQueueOfDocument(this);
if (shouldEncrypt(this)) data = this.collection._crypter._encryptValue(data);
blobBuffer = blobBufferUtil.createBlobBuffer(data, type);
_context6.next = 6;
return queue.requestIdlePromise();
case 6:
_context6.next = 8;
return queue.wrapCall((0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5() {
var docData, attachmentData, attachment;
return _regenerator2['default'].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return _this.collection.pouch.putAttachment(_this.primary, id, _this._data._rev, blobBuffer, type);
case 2:
_context5.next = 4;
return _this.collection.pouch.get(_this.primary);
case 4:
docData = _context5.sent;
attachmentData = docData._attachments[id];
attachment = RxAttachment.fromPouchDocument(id, attachmentData, _this);
_this._data._rev = docData._rev;
_this._data._attachments = docData._attachments;
_context5.next = 11;
return resyncRxDocument(_this);
case 11:
return _context5.abrupt('return', attachment);
case 12:
case 'end':
return _context5.stop();
}
}
}, _callee5, _this);
})));
case 8:
ret = _context6.sent;
return _context6.abrupt('return', ret);
case 10:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
return function putAttachment(_x2) {
return _ref7.apply(this, arguments);
};
}();
var preMigrateDocument = exports.preMigrateDocument = function () {
var _ref9 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee7(action) {
return _regenerator2['default'].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
delete action.migrated._attachments;
return _context7.abrupt('return', action);
case 2:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
return function preMigrateDocument(_x3) {
return _ref9.apply(this, arguments);
};
}();
var postMigrateDocument = exports.postMigrateDocument = function () {
var _ref10 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee8(action) {
var primaryPath, attachments, id, stubData, primary, data, res;
return _regenerator2['default'].wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
primaryPath = action.oldCollection.schema.primaryPath;
attachments = action.doc._attachments;
if (attachments) {
_context8.next = 4;
break;
}
return _context8.abrupt('return', action);
case 4:
_context8.t0 = _regenerator2['default'].keys(attachments);
case 5:
if ((_context8.t1 = _context8.t0()).done) {
_context8.next = 21;
break;
}
id = _context8.t1.value;
stubData = attachments[id];
primary = action.doc[primaryPath];
_context8.next = 11;
return action.oldCollection.pouchdb.getAttachment(primary, id);
case 11:
data = _context8.sent;
_context8.next = 14;
return blobBufferUtil.toString(data);
case 14:
data = _context8.sent;
_context8.next = 17;
return action.newestCollection.pouch.putAttachment(primary, id, action.res.rev, blobBufferUtil.createBlobBuffer(data, stubData.content_type), stubData.content_type);
case 17:
res = _context8.sent;
action.res = res;
_context8.next = 5;
break;
case 21:
case 'end':
return _context8.stop();
}
}
}, _callee8, this);
}));
return function postMigrateDocument(_x4) {
return _ref10.apply(this, arguments);
};
}();
exports.getAtomicQueueOfDocument = getAtomicQueueOfDocument;
exports.getAttachment = getAttachment;
exports.allAttachments = allAttachments;
var _customIdleQueue = require('custom-idle-queue');
var _customIdleQueue2 = _interopRequireDefault(_customIdleQueue);
var _rxChangeEvent = require('./../rx-change-event');
var _rxChangeEvent2 = _interopRequireDefault(_rxChangeEvent);
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 }; }
/**
* to not have update-conflicts,
* we use atomic inserts (per document) on putAttachment()
* @type {WeakMap}
*/
var ATTACHMENT_ATOMIC_QUEUES = new WeakMap();
function ensureSchemaSupportsAttachments(doc) {
var schemaJson = doc.collection.schema.jsonID;
if (!schemaJson.attachments) throw new Error('to use attachments, please define this in your schema');
}
var blobBufferUtil = exports.blobBufferUtil = {
/**
* depending if we are on node or browser,
* we have to use Buffer(node) or Blob(browser)
* @param {string} data
* @param {string} type
* @return {Blob|Buffer}
*/
createBlobBuffer: function createBlobBuffer(data, type) {
var blobBuffer = void 0;
try {
// for browsers
blobBuffer = new Blob([data], {
type: type
});
} catch (e) {
// for node
blobBuffer = new Buffer(data, {
type: type
});
}
return blobBuffer;
},
toString: function toString(blobBuffer) {
if (blobBuffer instanceof Buffer) {
// node
return util.nextTick().then(function () {
return blobBuffer.toString();
});
}
return new Promise(function (res) {
// browsers
var reader = new FileReader();
reader.addEventListener('loadend', function (e) {
var text = e.target.result;
res(text);
});
reader.readAsText(blobBuffer);
});
}
};
var _assignMethodsToAttachment = function _assignMethodsToAttachment(attachment) {
Object.entries(attachment.doc.collection._attachments).forEach(function (entry) {
var funName = entry[0];
var fun = entry[1];
attachment.__defineGetter__(funName, function () {
return fun.bind(attachment);
});
});
};
/**
* an RxAttachment is basically just the attachment-stub
* wrapped so that you can access the attachment-data
*/
var RxAttachment = exports.RxAttachment = function () {
function RxAttachment(_ref2) {
var doc = _ref2.doc,
id = _ref2.id,
type = _ref2.type,
length = _ref2.length,
digest = _ref2.digest,
rev = _ref2.rev;
(0, _classCallCheck3['default'])(this, RxAttachment);
this.doc = doc;
this.id = id;
this.type = type;
this.length = length;
this.digest = digest;
this.rev = rev;
_assignMethodsToAttachment(this);
}
(0, _createClass3['default'])(RxAttachment, [{
key: 'remove',
value: function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.doc.collection.pouch.removeAttachment(this.doc.primary, this.id, this.doc._data._rev);
case 2:
_context2.next = 4;
return resyncRxDocument(this.doc);
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function remove() {
return _ref3.apply(this, arguments);
}
return remove;
}()
/**
* returns the data for the attachment
* @return {Promise}
*/
}, {
key: 'getData',
value: function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3() {
var data, dataString;
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.doc.collection.pouch.getAttachment(this.doc.primary, this.id);
case 2:
data = _context3.sent;
if (!shouldEncrypt(this.doc)) {
_context3.next = 8;
break;
}
_context3.next = 6;
return blobBufferUtil.toString(data);
case 6:
dataString = _context3.sent;
data = blobBufferUtil.createBlobBuffer(this.doc.collection._crypter._decryptValue(dataString), this.type);
case 8:
return _context3.abrupt('return', data);
case 9:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function getData() {
return _ref4.apply(this, arguments);
}
return getData;
}()
}, {
key: 'getStringData',
value: function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4() {
var bufferBlob;
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.getData();
case 2:
bufferBlob = _context4.sent;
_context4.next = 5;
return blobBufferUtil.toString(bufferBlob);
case 5:
return _context4.abrupt('return', _context4.sent);
case 6:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function getStringData() {
return _ref5.apply(this, arguments);
}
return getStringData;
}()
}]);
return RxAttachment;
}();
RxAttachment.fromPouchDocument = function (id, pouchDocAttachment, rxDocument) {
return new RxAttachment({
doc: rxDocument,
id: id,
type: pouchDocAttachment.content_type,
length: pouchDocAttachment.length,
digest: pouchDocAttachment.digest,
rev: pouchDocAttachment.revpos
});
};
function getAtomicQueueOfDocument(doc) {
if (!ATTACHMENT_ATOMIC_QUEUES.has(doc)) ATTACHMENT_ATOMIC_QUEUES.set(doc, new _customIdleQueue2['default']());
return ATTACHMENT_ATOMIC_QUEUES.get(doc);
};
function shouldEncrypt(doc) {
return !!doc.collection.schema.jsonID.attachments.encrypted;
}
;
/**
* get an attachment of the document by its id
* @param {string} id
* @return {RxAttachment}
*/
function getAttachment(id) {
ensureSchemaSupportsAttachments(this);
var docData = this._dataSync$.getValue();
if (!docData._attachments || !docData._attachments[id]) return null;
var attachmentData = docData._attachments[id];
var attachment = RxAttachment.fromPouchDocument(id, attachmentData, this);
return attachment;
};
/**
* returns all attachments of the document
* @return {RxAttachment[]}
*/
function allAttachments() {
var _this2 = this;
ensureSchemaSupportsAttachments(this);
var docData = this._dataSync$.getValue();
return Object.keys(docData._attachments).map(function (id) {
return RxAttachment.fromPouchDocument(id, docData._attachments[id], _this2);
});
};
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {
RxDocument: function RxDocument(proto) {
proto.putAttachment = putAttachment;
proto.getAttachment = getAttachment;
proto.allAttachments = allAttachments;
Object.defineProperty(proto, 'allAttachments$', {
get: function allAttachments$() {
var _this3 = this;
return this._dataSync$.map(function (data) {
if (!data._attachments) return {};
return data._attachments;
}).map(function (attachmentsData) {
return Object.entries(attachmentsData);
}).map(function (entries) {
return entries.map(function (entry) {
var id = entry[0];
var attachmentData = entry[1];
return RxAttachment.fromPouchDocument(id, attachmentData, _this3);
});
});
}
});
}
};
var overwritable = exports.overwritable = {};
var hooks = exports.hooks = {
preMigrateDocument: preMigrateDocument,
postMigrateDocument: postMigrateDocument
};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable,
hooks: hooks,
blobBufferUtil: blobBufferUtil
};
}).call(this,require("buffer").Buffer)
},{"./../rx-change-event":29,"./../util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/regenerator":57,"buffer":61,"custom-idle-queue":492}],15:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwritable = exports.prototypes = exports.rxdb = undefined;
exports.encrypt = encrypt;
exports.decrypt = decrypt;
var _aes = require('crypto-js/aes');
var cryptoAes = _interopRequireWildcard(_aes);
var _encUtf = require('crypto-js/enc-utf8');
var cryptoEnc = _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; } }
/**
* this plugin adds the encrpytion-capabilities to rxdb
* It's using crypto-js/aes for password-encryption
* @link https://github.com/brix/crypto-js
*/
var minPassLength = 8;
function encrypt(value, password) {
var encrypted = cryptoAes.encrypt(value, password);
return encrypted.toString();
};
function decrypt(cipherText, password) {
var decrypted = cryptoAes.decrypt(cipherText, password);
return decrypted.toString(cryptoEnc);
};
var _encryptValue = function _encryptValue(value) {
return encrypt(JSON.stringify(value), this._password);
};
var _decryptValue = function _decryptValue(encValue) {
var decrypted = decrypt(encValue, this._password);
return JSON.parse(decrypted);
};
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {
/**
* set crypto-functions for the Crypter.prototype
* @param {[type]} prototype of Crypter
*/
Crypter: function Crypter(proto) {
proto._encryptValue = _encryptValue;
proto._decryptValue = _decryptValue;
}
};
var overwritable = exports.overwritable = {
validatePassword: function validatePassword(password) {
if (password && typeof password !== 'string') throw new TypeError('password is no string');
if (password && password.length < minPassLength) throw new Error('password must have at least ' + minPassLength + ' chars (given: ' + password + ')');
}
};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable
};
},{"crypto-js/aes":482,"crypto-js/enc-utf8":486}],16:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwritable = exports.prototypes = exports.rxdb = exports.spawnInMemory = exports.InMemoryRxCollection = 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 _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
/**
* called in the proto of RxCollection
* @return {Promise}
*/
var spawnInMemory = exports.spawnInMemory = function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5() {
var col, preparePromise;
return _regenerator2['default'].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (!INIT_DONE) {
INIT_DONE = true;
// ensure memory-adapter is added
_core2['default'].plugin(_pouchdbAdapterMemory2['default']);
}
if (!collectionCacheMap.has(this)) {
_context5.next = 5;
break;
}
_context5.next = 4;
return collectionPromiseCacheMap.get(this);
case 4:
return _context5.abrupt('return', collectionCacheMap.get(this));
case 5:
col = new InMemoryRxCollection(this);
preparePromise = col.prepare();
collectionCacheMap.set(this, col);
collectionPromiseCacheMap.set(this, preparePromise);
_context5.next = 11;
return preparePromise;
case 11:
return _context5.abrupt('return', col);
case 12:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
return function spawnInMemory() {
return _ref5.apply(this, arguments);
};
}();
var _rxCollection = require('../rx-collection');
var _rxCollection2 = _interopRequireDefault(_rxCollection);
var _core = require('../core');
var _core2 = _interopRequireDefault(_core);
var _util = require('../util');
var util = _interopRequireWildcard(_util);
var _crypter = require('../crypter');
var _crypter2 = _interopRequireDefault(_crypter);
var _changeEventBuffer = require('../change-event-buffer');
var _changeEventBuffer2 = _interopRequireDefault(_changeEventBuffer);
var _rxSchema = require('../rx-schema');
var _rxSchema2 = _interopRequireDefault(_rxSchema);
var _pouchDb = require('../pouch-db');
var _pouchDb2 = _interopRequireDefault(_pouchDb);
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _pouchdbAdapterMemory = require('pouchdb-adapter-memory');
var _pouchdbAdapterMemory2 = _interopRequireDefault(_pouchdbAdapterMemory);
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 collectionCacheMap = new WeakMap(); /**
* This plugin adds RxCollection.inMemory()
* Which replicates the collection into an in-memory-collection
* So you can do faster queries and also query over encrypted fields
*/
var collectionPromiseCacheMap = new WeakMap();
var BULK_DOC_OPTIONS = {
new_edits: false
};
var InMemoryRxCollection = exports.InMemoryRxCollection = function (_RxCollection$RxColle) {
(0, _inherits3['default'])(InMemoryRxCollection, _RxCollection$RxColle);
function InMemoryRxCollection(parentCollection, pouchSettings) {
(0, _classCallCheck3['default'])(this, InMemoryRxCollection);
var _this = (0, _possibleConstructorReturn3['default'])(this, (InMemoryRxCollection.__proto__ || Object.getPrototypeOf(InMemoryRxCollection)).call(this, parentCollection.database, parentCollection.name, toCleanSchema(parentCollection.schema), pouchSettings, // pouchSettings
{}, parentCollection._methods));
//constructor(database, name, schema, pouchSettings, migrationStrategies, methods) {
_this._isInMemory = true;
_this._parentCollection = parentCollection;
_this._parentCollection.onDestroy.then(function () {
return _this.destroy();
});
_this._changeStreams = [];
/**
* runs on parentCollection.destroy()
* Cleans up everything to free up memory
*/
_this.onDestroy.then(function () {
_this._changeStreams.forEach(function (stream) {
return stream.cancel();
});
_this.pouch.destroy();
});
return _this;
}
(0, _createClass3['default'])(InMemoryRxCollection, [{
key: 'prepare',
value: function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
var _this2 = this;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
this._crypter = _crypter2['default'].create(this.database.password, this.schema);
this.pouch = new _pouchDb2['default']('rxdb-in-memory-' + util.randomCouchString(10), util.adapterObject('memory'), {});
this._observable$ = new util.Rx.Subject();
this._changeEventBuffer = _changeEventBuffer2['default'].create(this);
// INDEXES
_context.next = 6;
return Promise.all(this.schema.indexes.map(function (indexAr) {
return _this2.pouch.createIndex({
index: {
fields: indexAr
}
});
}));
case 6:
this._subs.push(this._observable$.subscribe(function (cE) {
// when data changes, send it to RxDocument in docCache
var doc = _this2._docCache.get(cE.data.doc);
if (doc) doc._handleChangeEvent(cE);
}));
_context.next = 9;
return this._initialSync();
case 9:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function prepare() {
return _ref.apply(this, arguments);
}
return prepare;
}()
/**
* this does the initial sync
* so that the in-memory-collection has the same docs as the original
* @return {Promise}
*/
}, {
key: '_initialSync',
value: function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4() {
var _this3 = this;
var allRows, fromOwnStream, fromParentStream;
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this._parentCollection.pouch.allDocs({
attachments: false,
include_docs: true
});
case 2:
allRows = _context4.sent;
_context4.next = 5;
return this.pouch.bulkDocs({
docs: allRows.rows.map(function (row) {
return row.doc;
}).filter(function (doc) {
return !doc.language;
}) // do not replicate design-docs
.map(function (doc) {
return _this3._parentCollection._handleFromPouch(doc);
})
}, BULK_DOC_OPTIONS);
case 5:
// sync from own to parent
this._parentCollection.watchForChanges();
this.watchForChanges();
fromOwnStream = this.pouch.changes({
since: 'now',
include_docs: true,
live: true
}).on('change', function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2(change) {
var doc;
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
doc = _this3._parentCollection._handleToPouch(change.doc);
// console.log('write to parent:');
// console.dir(doc);
_this3._parentCollection.pouch.bulkDocs({
docs: [doc]
}, BULK_DOC_OPTIONS);
case 2:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this3);
}));
return function (_x) {
return _ref3.apply(this, arguments);
};
}());
this._changeStreams.push(fromOwnStream);
// sync from parent to own
fromParentStream = this._parentCollection.pouch.changes({
since: 'now',
include_docs: true,
live: true
}).on('change', function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3(change) {
var doc;
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
doc = _this3._parentCollection._handleFromPouch(change.doc);
doc = _this3.schema.swapPrimaryToId(doc);
// console.log('write to own2:');
// console.dir(doc);
_this3.pouch.bulkDocs({
docs: [doc]
}, BULK_DOC_OPTIONS);
case 3:
case 'end':
return _context3.stop();
}
}
}, _callee3, _this3);
}));
return function (_x2) {
return _ref4.apply(this, arguments);
};
}());
this._changeStreams.push(fromParentStream);
case 11:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function _initialSync() {
return _ref2.apply(this, arguments);
}
return _initialSync;
}()
/**
* @overwrite
*/
}, {
key: '$emit',
value: function $emit(changeEvent) {
this._observable$.next(changeEvent);
// run compaction each 10 events
if (!this._eventCounter) this._eventCounter = 0;
this._eventCounter++;
if (this._eventCounter === 10) {
this._eventCounter = 0;
this.pouch.compact();
}
// console.log('$emit called:');
// console.dir(changeEvent);
}
}]);
return InMemoryRxCollection;
}(_rxCollection2['default'].RxCollection);
;
function toCleanSchema(rxSchema) {
var newSchemaJson = (0, _clone2['default'])(rxSchema.jsonID);
newSchemaJson.disableKeyCompression = true;
delete newSchemaJson.properties._id;
delete newSchemaJson.properties._rev;
delete newSchemaJson.properties._attachments;
var removeEncryption = function removeEncryption(schema, complete) {
delete schema.encrypted;
Object.values(schema).filter(function (val) {
return (typeof val === 'undefined' ? 'undefined' : (0, _typeof3['default'])(val)) === 'object';
}).forEach(function (val) {
return removeEncryption(val, complete);
});
};
removeEncryption(newSchemaJson, newSchemaJson);
return _rxSchema2['default'].create(newSchemaJson);
}
var INIT_DONE = false;;
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {
RxCollection: function RxCollection(proto) {
proto.inMemory = spawnInMemory;
}
};
var overwritable = exports.overwritable = {};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable,
spawnInMemory: spawnInMemory
};
},{"../change-event-buffer":2,"../core":3,"../crypter":4,"../pouch-db":25,"../rx-collection":30,"../rx-schema":35,"../util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/inherits":53,"babel-runtime/helpers/possibleConstructorReturn":54,"babel-runtime/helpers/typeof":56,"babel-runtime/regenerator":57,"clone":63,"pouchdb-adapter-memory":573}],17:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwritable = exports.prototypes = exports.rxdb = undefined;
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _util = require('../util');
var util = _interopRequireWildcard(_util);
var _rxQuery = require('../rx-query');
var _rxQuery2 = _interopRequireDefault(_rxQuery);
var _rxError = require('../rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
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 dumpRxDatabase = function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
var _this = 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 _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
json = {
name: this.name,
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 _this.collections[colName];
});
_context.next = 5;
return Promise.all(useCollections.map(function (col) {
return col.dump(decrypted);
}));
case 5:
json.collections = _context.sent;
return _context.abrupt('return', json);
case 7:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function dumpRxDatabase() {
return _ref.apply(this, arguments);
};
}(); /**
* this plugin adds the json export/import capabilities to RxDB
*/
var importDumpRxDatabase = function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2(dump) {
var _this2 = this;
var missingCollections;
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
/**
* collections must be created before the import
* because we do not know about the other collection-settings here
*/
missingCollections = dump.collections.filter(function (col) {
return !_this2.collections[col.name];
}).map(function (col) {
return col.name;
});
if (!(missingCollections.length > 0)) {
_context2.next = 3;
break;
}
throw _rxError2['default'].newRxError('You must create the collections before you can import their data', {
missingCollections: missingCollections
});
case 3:
return _context2.abrupt('return', Promise.all(dump.collections.map(function (colDump) {
return _this2.collections[colDump.name].importDump(colDump);
})));
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function importDumpRxDatabase(_x3) {
return _ref2.apply(this, arguments);
};
}();
var dumpRxCollection = function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3() {
var decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var encrypted, json, query, docs;
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
encrypted = !decrypted;
json = {
name: this.name,
schemaHash: this.schema.hash,
encrypted: false,
passwordHash: null,
docs: []
};
if (this.database.password && encrypted) {
json.passwordHash = util.hash(this.database.password);
json.encrypted = true;
}
query = _rxQuery2['default'].create('find', {}, this);
_context3.next = 6;
return this._pouchFind(query, null, encrypted);
case 6:
docs = _context3.sent;
json.docs = docs.map(function (docData) {
delete docData._rev;
return docData;
});
return _context3.abrupt('return', json);
case 9:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
return function dumpRxCollection() {
return _ref3.apply(this, arguments);
};
}();
var importDumpRxCollection = function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4(exportedJSON) {
var _this3 = this;
var importFns;
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!(exportedJSON.schemaHash !== this.schema.hash)) {
_context4.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))) {
_context4.next = 4;
break;
}
throw new Error('json.passwordHash does not match the own');
case 4:
importFns = exportedJSON.docs
// decrypt
.map(function (doc) {
return _this3._crypter.decrypt(doc);
})
// validate schema
.map(function (doc) {
return _this3.schema.validate(doc);
})
// import
.map(function (doc) {
return _this3._pouchPut(doc);
});
return _context4.abrupt('return', Promise.all(importFns));
case 6:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
return function importDumpRxCollection(_x5) {
return _ref4.apply(this, arguments);
};
}();
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {
RxDatabase: function RxDatabase(proto) {
proto.dump = dumpRxDatabase;
proto.importDump = importDumpRxDatabase;
},
RxCollection: function RxCollection(proto) {
proto.dump = dumpRxCollection;
proto.importDump = importDumpRxCollection;
}
};
var overwritable = exports.overwritable = {};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable
};
},{"../rx-error":33,"../rx-query":34,"../util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/regenerator":57}],18:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwritable = exports.prototypes = exports.rxdb = 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.create = create;
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 }; }
/**
* this plugin adds the keycompression-capabilities to rxdb
* if you dont use this, ensure that you set disableKeyComression to false in your schema
*/
var KeyCompressor = function () {
/**
* @param {RxSchema} schema
*/
function KeyCompressor(schema) {
(0, _classCallCheck3['default'])(this, KeyCompressor);
this.schema = schema;
this._table;
this._reverseTable;
this._fullTable;
}
(0, _createClass3['default'])(KeyCompressor, [{
key: '_compressObj',
value: function _compressObj(obj) {
var _this = this;
var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var ret = {};
if ((typeof obj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(obj)) !== 'object') return obj;
if (Array.isArray(obj)) {
return obj.map(function (o) {
return _this._compressObj(o, util.trimDots(path + '.item'));
});
}
Object.keys(obj).forEach(function (key) {
var propertyObj = obj[key];
var fullPath = util.trimDots(path + '.' + key);
var replacedKey = _this.table[fullPath] ? _this.table[fullPath] : key;
var nextObj = propertyObj;
nextObj = _this._compressObj(propertyObj, fullPath);
ret[replacedKey] = nextObj;
});
return ret;
}
/**
* compress the keys of an object via the compression-table
* @param {Object} obj
* @param {Object} compressed obj
*/
}, {
key: 'compress',
value: function compress(obj) {
if (!this.schema.doKeyCompression()) return (0, _clone2['default'])(obj);
return this._compressObj(obj);
}
}, {
key: '_decompressObj',
value: function _decompressObj(obj) {
var _this2 = this;
var reverseTable = this.reverseTable;
// non-object
if ((typeof obj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(obj)) !== 'object' || obj === null) return obj;
// array
if (Array.isArray(obj)) return obj.map(function (item) {
return _this2._decompressObj(item);
});
// object
else {
var ret = {};
Object.keys(obj).forEach(function (key) {
var replacedKey = key;
if ((key.startsWith('|') || key.startsWith('_')) && reverseTable[key]) replacedKey = reverseTable[key];
ret[replacedKey] = _this2._decompressObj(obj[key]);
});
return ret;
}
}
}, {
key: 'decompress',
value: function decompress(obj) {
if (!this.schema.doKeyCompression()) return (0, _clone2['default'])(obj);
var returnObj = this._decompressObj(obj);
return returnObj;
}
/**
* get the full compressed-key-path of a object-path
* @param {string} prePath | 'mainSkill'
* @param {string} prePathCompressed | '|a'
* @param {string[]} remainPathAr | ['attack', 'count']
* @return {string} compressedPath | '|a.|b.|c'
*/
}, {
key: '_transformKey',
value: function _transformKey(prePath, prePathCompressed, remainPathAr) {
var table = this.table;
prePath = util.trimDots(prePath);
prePathCompressed = util.trimDots(prePathCompressed);
var nextPath = remainPathAr.shift();
var nextFullPath = util.trimDots(prePath + '.' + nextPath);
if (table[nextFullPath]) prePathCompressed += '.' + table[nextFullPath];else prePathCompressed += '.' + nextPath;
if (remainPathAr.length > 0) return this._transformKey(nextFullPath, prePathCompressed, remainPathAr);else return util.trimDots(prePathCompressed);
}
/**
* replace the keys of a query-obj with the compressed keys
* @param {{selector: {}}} queryJSON
* @return {{selector: {}}} compressed queryJSON
*/
}, {
key: 'compressQuery',
value: function compressQuery(queryJSON) {
var _this3 = this;
queryJSON = (0, _clone2['default'])(queryJSON);
if (!this.schema.doKeyCompression()) return queryJSON;
// selector
var selector = {};
Object.keys(queryJSON.selector).forEach(function (key) {
var value = queryJSON.selector[key];
if (key.startsWith('$')) {
// $or, $not etc have different structure
var setObj = value.map(function (obj) {
var newObj = {};
Object.keys(obj).forEach(function (k) {
var transKey = _this3._transformKey('', '', k.split('.'));
newObj[transKey] = obj[k];
});
return newObj;
});
selector[key] = setObj;
} else {
var transKey = _this3._transformKey('', '', key.split('.'));
selector[transKey] = value;
}
});
queryJSON.selector = selector;
// sort
if (queryJSON.sort) {
queryJSON.sort = queryJSON.sort.map(function (sortObj) {
var key = Object.keys(sortObj)[0];
var value = sortObj[key];
var ret = {};
ret[_this3._transformKey('', '', key.split('.'))] = value;
return ret;
});
}
return queryJSON;
}
}, {
key: 'table',
get: function get() {
var _this4 = this;
if (!this._table) {
// create new table
var lastKeyNumber = 0;
var nextKey = function nextKey() {
lastKeyNumber++;
return util.numberToLetter(lastKeyNumber - 1);
};
this._table = {};
var jsonSchema = this.schema.normalized;
var propertiesToTable = function propertiesToTable(path, obj) {
Object.keys(obj).map(function (key) {
var propertyObj = obj[key];
var fullPath = key === 'properties' ? path : util.trimDots(path + '.' + key);
if ((typeof propertyObj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(propertyObj)) === 'object' && // do not add schema-attributes
!Array.isArray(propertyObj) && // do not use arrays
!_this4._table[fullPath] && fullPath !== '' && key.length > 3 && // do not compress short keys
!fullPath.startsWith('_') // _id/_rev etc should never be compressed
) _this4._table[fullPath] = '|' + nextKey();
// primary-key is always compressed to _id
if (propertyObj.primary === true) _this4._table[fullPath] = '_id';
if ((typeof propertyObj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(propertyObj)) === 'object' && !Array.isArray(propertyObj)) propertiesToTable(fullPath, propertyObj);
});
};
propertiesToTable('', jsonSchema);
}
return this._table;
}
}, {
key: 'reverseTable',
get: function get() {
var _this5 = this;
if (!this._reverseTable) {
var table = this.table;
this._reverseTable = {};
Object.keys(table).forEach(function (key) {
var value = table[key];
var fieldName = key.split('.').pop();
_this5._reverseTable[value] = fieldName;
});
}
return this._reverseTable;
}
}]);
return KeyCompressor;
}();
function create(schema) {
return new KeyCompressor(schema);
}
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {};
var overwritable = exports.overwritable = {
createKeyCompressor: create
};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable
};
},{"../util":37,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/typeof":56,"clone":63}],19:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwritable = exports.prototypes = exports.rxdb = exports.SIGNAL_TIME = exports.documentID = 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);
exports.create = create;
var _unload = require('unload');
var _unload2 = _interopRequireDefault(_unload);
var _util = require('../util');
var util = _interopRequireWildcard(_util);
var _rxBroadcastChannel = require('../rx-broadcast-channel');
var _rxBroadcastChannel2 = _interopRequireDefault(_rxBroadcastChannel);
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 documentID = exports.documentID = '_local/leader';
/**
* This time defines how 'fast' the communication between the instances is.
* If this time is too low, it's possible that more than one instance becomes leader
* If this time is too height, the leader-election takes longer than necessary
* @type {Number} in milliseconds
*/
/**
* this plugin adds the leader-election-capabilities to rxdb
*/
var SIGNAL_TIME = exports.SIGNAL_TIME = 500;
var LeaderElector = function () {
function LeaderElector(database) {
(0, _classCallCheck3['default'])(this, LeaderElector);
this.destroyed = false;
// things that must be cleared on destroy
this.subs = [];
this.unloads = [];
this.database = database;
this.token = this.database.token;
this.isLeader = false;
this.becomeLeader$ = new util.Rx.BehaviorSubject({
isLeader: false
});
this.isDead = false;
this.isApplying = false;
this.isWaiting = false;
this.bc = _rxBroadcastChannel2['default'].create(this.database, 'leader');
this.electionChannel = this.bc ? 'broadcast' : 'socket';
}
(0, _createClass3['default'])(LeaderElector, [{
key: 'createLeaderObject',
value: function createLeaderObject() {
return {
_id: documentID,
is: '', // token of leader-instance
apply: '', // token of applying instance
t: 0 // time when the leader send a signal the last time
};
}
/**
* returns the leader-document from the _adminPouch
* @return {Promise} leaderDoc
*/
}, {
key: 'getLeaderObject',
value: function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
var obj, ret;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
obj = void 0;
_context.prev = 1;
_context.next = 4;
return this.database._adminPouch.get(documentID);
case 4:
obj = _context.sent;
_context.next = 14;
break;
case 7:
_context.prev = 7;
_context.t0 = _context['catch'](1);
obj = this.createLeaderObject();
_context.next = 12;
return this.database._adminPouch.put(obj);
case 12:
ret = _context.sent;
obj._rev = ret.rev;
case 14:
return _context.abrupt('return', obj);
case 15:
case 'end':
return _context.stop();
}
}
}, _callee, this, [[1, 7]]);
}));
function getLeaderObject() {
return _ref.apply(this, arguments);
}
return getLeaderObject;
}()
/**
* saves the leader-object to the internal adminPouch
* @param {any} newObj [description]
* @return {Promise}
*/
}, {
key: 'setLeaderObject',
value: function setLeaderObject(newObj) {
return this.database._adminPouch.put(newObj);
}
}, {
key: 'getApplyFunction',
value: function getApplyFunction(electionChannel) {
if (electionChannel === 'socket') return this.applySocket.bind(this);
if (electionChannel === 'broadcast') return this.applyBroadcast.bind(this);
throw new Error('this should not happen');
}
/**
* starts applying for leadership
*/
}, {
key: 'applyOnce',
value: function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
var elected;
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!this.isLeader) {
_context2.next = 2;
break;
}
return _context2.abrupt('return', false);
case 2:
if (!this.isDead) {
_context2.next = 4;
break;
}
return _context2.abrupt('return', false);
case 4:
if (!this.isApplying) {
_context2.next = 6;
break;
}
return _context2.abrupt('return', false);
case 6:
if (!this.destroyed) {
_context2.next = 8;
break;
}
return _context2.abrupt('return', false);
case 8:
this.isApplying = true;
_context2.next = 11;
return this.getApplyFunction(this.electionChannel)();
case 11:
elected = _context2.sent;
if (!elected) {
_context2.next = 15;
break;
}
_context2.next = 15;
return this.beLeader();
case 15:
this.isApplying = false;
return _context2.abrupt('return', true);
case 17:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function applyOnce() {
return _ref2.apply(this, arguments);
}
return applyOnce;
}()
/**
* apply via socket
* (critical on chrome with indexedDB due to write-locks)
*/
}, {
key: 'applySocket',
value: function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3() {
var leaderObj, minTime;
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
_context3.next = 3;
return this.getLeaderObject();
case 3:
leaderObj = _context3.sent;
minTime = new Date().getTime() - SIGNAL_TIME * 2;
if (!(leaderObj.t >= minTime)) {
_context3.next = 7;
break;
}
throw new Error('someone else is applying/leader');
case 7:
// write applying to db
leaderObj.apply = this.token;
leaderObj.t = new Date().getTime();
_context3.next = 11;
return this.setLeaderObject(leaderObj);
case 11:
_context3.next = 13;
return util.promiseWait(SIGNAL_TIME * 0.5);
case 13:
_context3.next = 15;
return this.getLeaderObject();
case 15:
leaderObj = _context3.sent;
if (!(leaderObj.apply !== this.token)) {
_context3.next = 18;
break;
}
throw new Error('someone else overwrote apply');
case 18:
return _context3.abrupt('return', true);
case 21:
_context3.prev = 21;
_context3.t0 = _context3['catch'](0);
return _context3.abrupt('return', false);
case 24:
case 'end':
return _context3.stop();
}
}
}, _callee3, this, [[0, 21]]);
}));
function applySocket() {
return _ref3.apply(this, arguments);
}
return applySocket;
}()
/**
* apply via BroadcastChannel-API
* (better performance than socket)
*/
}, {
key: 'applyBroadcast',
value: function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5() {
var _this = this;
var applyTime, subs, errors, whileNoError, ret;
return _regenerator2['default'].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
applyTime = new Date().getTime();
subs = [];
errors = [];
whileNoError = function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4() {
var circles;
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
subs.push(_this.bc.$.filter(function () {
return !!_this.isApplying;
}).filter(function (msg) {
return msg.t >= applyTime;
}).filter(function (msg) {
return msg.type === 'apply';
}).filter(function (msg) {
if (msg.data < applyTime || msg.data === applyTime && msg.it > _this.token) return true;else return false;
}).filter(function () {
return errors.length < 1;
}).subscribe(function (msg) {
return errors.push('other is applying:' + msg.it);
}));
subs.push(_this.bc.$.filter(function () {
return !!_this.isApplying;
}).filter(function (msg) {
return msg.t >= applyTime;
}).filter(function (msg) {
return msg.type === 'tell';
}).filter(function () {
return errors.length < 1;
}).subscribe(function (msg) {
return errors.push('other is leader' + msg.it);
}));
subs.push(_this.bc.$.filter(function () {
return !!_this.isApplying;
}).filter(function (msg) {
return msg.type === 'apply';
}).filter(function (msg) {
if (msg.data > applyTime || msg.data === applyTime && msg.it > _this.token) return true;else return false;
}).subscribe(function () {
return _this.bc.write('apply', applyTime);
}));
circles = 3;
case 4:
if (!(circles > 0)) {
_context4.next = 14;
break;
}
circles--;
_context4.next = 8;
return _this.bc.write('apply', applyTime);
case 8:
_context4.next = 10;
return util.promiseWait(300);
case 10:
if (!(errors.length > 0)) {
_context4.next = 12;
break;
}
return _context4.abrupt('return', false);
case 12:
_context4.next = 4;
break;
case 14:
return _context4.abrupt('return', true);
case 15:
case 'end':
return _context4.stop();
}
}
}, _callee4, _this);
}));
return function whileNoError() {
return _ref5.apply(this, arguments);
};
}();
_context5.next = 6;
return whileNoError();
case 6:
ret = _context5.sent;
subs.map(function (sub) {
return sub.unsubscribe();
});
return _context5.abrupt('return', ret);
case 9:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function applyBroadcast() {
return _ref4.apply(this, arguments);
}
return applyBroadcast;
}()
}, {
key: 'leaderSignal',
value: function () {
var _ref6 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee6() {
var success, leaderObj;
return _regenerator2['default'].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!this.destroyed) {
_context6.next = 2;
break;
}
return _context6.abrupt('return');
case 2:
if (!this.leaderSignal_run) {
_context6.next = 4;
break;
}
return _context6.abrupt('return');
case 4:
this.leaderSignal_run = true;
_context6.t0 = this.electionChannel;
_context6.next = _context6.t0 === 'broadcast' ? 8 : _context6.t0 === 'socket' ? 11 : 31;
break;
case 8:
_context6.next = 10;
return this.bc.write('tell');
case 10:
return _context6.abrupt('break', 31);
case 11:
success = false;
case 12:
if (success) {
_context6.next = 30;
break;
}
_context6.prev = 13;
_context6.next = 16;
return this.getLeaderObject();
case 16:
leaderObj = _context6.sent;
leaderObj.is = this.token;
leaderObj.apply = this.token;
leaderObj.t = new Date().getTime();
_context6.next = 22;
return this.setLeaderObject(leaderObj);
case 22:
success = true;
_context6.next = 28;
break;
case 25:
_context6.prev = 25;
_context6.t1 = _context6['catch'](13);
console.dir(_context6.t1);
case 28:
_context6.next = 12;
break;
case 30:
return _context6.abrupt('break', 31);
case 31:
this.leaderSignal_run = false;
return _context6.abrupt('return');
case 33:
case 'end':
return _context6.stop();
}
}
}, _callee6, this, [[13, 25]]);
}));
function leaderSignal() {
return _ref6.apply(this, arguments);
}
return leaderSignal;
}()
/**
* assigns leadership to this instance
*/
}, {
key: 'beLeader',
value: function () {
var _ref7 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee8() {
var _this2 = this;
return _regenerator2['default'].wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
if (!this.isDead) {
_context8.next = 2;
break;
}
return _context8.abrupt('return', false);
case 2:
if (!this.isLeader) {
_context8.next = 4;
break;
}
return _context8.abrupt('return', false);
case 4:
this.isLeader = true;
this.becomeLeader$.next({
isLeader: true
});
_context8.next = 8;
return this.leaderSignal();
case 8:
_context8.t0 = this.electionChannel;
_context8.next = _context8.t0 === 'broadcast' ? 11 : _context8.t0 === 'socket' ? 14 : 16;
break;
case 11:
this.signalLeadership = this.bc.$.filter(function () {
return !!_this2.isLeader;
})
// BUGFIX: avoids loop-hole when for whatever reason 2 are leader
.filter(function (msg) {
return msg.type !== 'tell';
}).subscribe(function () {
return _this2.leaderSignal();
});
this.subs.push(this.signalLeadership);
return _context8.abrupt('break', 16);
case 14:
(0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee7() {
return _regenerator2['default'].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
if (_this2.destroyed) {
_context7.next = 9;
break;
}
_context7.next = 3;
return util.promiseWait(SIGNAL_TIME);
case 3:
if (_this2.isLeader) {
_context7.next = 5;
break;
}
return _context7.abrupt('return');
case 5:
_context7.next = 7;
return _this2.leaderSignal();
case 7:
_context7.next = 0;
break;
case 9:
case 'end':
return _context7.stop();
}
}
}, _callee7, _this2);
}))();
return _context8.abrupt('break', 16);
case 16:
// this.die() on unload
this.unloads.push(_unload2['default'].add(function () {
_this2.bc && _this2.bc.write('death');
_this2.die();
}));
return _context8.abrupt('return', true);
case 18:
case 'end':
return _context8.stop();
}
}
}, _callee8, this);
}));
function beLeader() {
return _ref7.apply(this, arguments);
}
return beLeader;
}()
}, {
key: 'die',
value: function () {
var _ref9 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee9() {
var success, leaderObj;
return _regenerator2['default'].wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
if (this.isLeader) {
_context9.next = 2;
break;
}
return _context9.abrupt('return', false);
case 2:
if (!this.isDead) {
_context9.next = 4;
break;
}
return _context9.abrupt('return', false);
case 4:
this.isDead = true;
this.isLeader = false;
if (this.signalLeadership) this.signalLeadership.unsubscribe();
// force.write to db
_context9.t0 = this.electionChannel;
_context9.next = _context9.t0 === 'broadcast' ? 10 : _context9.t0 === 'socket' ? 13 : 30;
break;
case 10:
_context9.next = 12;
return this.bc.write('death');
case 12:
return _context9.abrupt('break', 30);
case 13:
success = false;
case 14:
if (success) {
_context9.next = 29;
break;
}
_context9.prev = 15;
_context9.next = 18;
return this.getLeaderObject();
case 18:
leaderObj = _context9.sent;
leaderObj.t = 0;
_context9.next = 22;
return this.setLeaderObject(leaderObj);
case 22:
success = true;
_context9.next = 27;
break;
case 25:
_context9.prev = 25;
_context9.t1 = _context9['catch'](15);
case 27:
_context9.next = 14;
break;
case 29:
return _context9.abrupt('break', 30);
case 30:
return _context9.abrupt('return', true);
case 31:
case 'end':
return _context9.stop();
}
}
}, _callee9, this, [[15, 25]]);
}));
function die() {
return _ref9.apply(this, arguments);
}
return die;
}()
/**
* @return {Promise} promise which resolve when the instance becomes leader
*/
}, {
key: 'waitForLeadership',
value: function () {
var _ref10 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee11() {
var _this3 = this;
var fallbackIntervalTime;
return _regenerator2['default'].wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
if (!this.isLeader) {
_context11.next = 2;
break;
}
return _context11.abrupt('return', Promise.resolve(true));
case 2:
if (this.isWaiting) {
_context11.next = 14;
break;
}
this.isWaiting = true;
// apply now
this.applyOnce();
fallbackIntervalTime = SIGNAL_TIME * 5;
_context11.t0 = this.electionChannel;
_context11.next = _context11.t0 === 'broadcast' ? 9 : _context11.t0 === 'socket' ? 11 : 13;
break;
case 9:
// apply when leader dies
this.subs.push(this.bc.$.filter(function (msg) {
return msg.type === 'death';
}).subscribe(function () {
return _this3.applyOnce();
}));
return _context11.abrupt('break', 13);
case 11:
// no message via socket, so just use the interval but set it lower
fallbackIntervalTime = SIGNAL_TIME * 2;
return _context11.abrupt('break', 13);
case 13:
// apply on interval incase leader dies without notification
(0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee10() {
return _regenerator2['default'].wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (!(!_this3.destroyed && !_this3.isLeader)) {
_context10.next = 16;
break;
}
_context10.next = 3;
return util.promiseWait(fallbackIntervalTime);
case 3:
_context10.t0 = _this3.electionChannel;
_context10.next = _context10.t0 === 'broadcast' ? 6 : _context10.t0 === 'socket' ? 9 : 12;
break;
case 6:
_context10.next = 8;
return util.requestIdlePromise(fallbackIntervalTime);
case 8:
return _context10.abrupt('break', 12);
case 9:
_context10.next = 11;
return _this3.database.requestIdlePromise(fallbackIntervalTime);
case 11:
return _context10.abrupt('break', 12);
case 12:
_context10.next = 14;
return _this3.applyOnce();
case 14:
_context10.next = 0;
break;
case 16:
case 'end':
return _context10.stop();
}
}
}, _callee10, _this3);
}))();
case 14:
return _context11.abrupt('return', this.becomeLeader$.asObservable().filter(function (i) {
return i.isLeader === true;
}).first().toPromise());
case 15:
case 'end':
return _context11.stop();
}
}
}, _callee11, this);
}));
function waitForLeadership() {
return _ref10.apply(this, arguments);
}
return waitForLeadership;
}()
}, {
key: 'destroy',
value: function () {
var _ref12 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee12() {
return _regenerator2['default'].wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
this.destroyed = true;
this.subs.map(function (sub) {
return sub.unsubscribe();
});
this.unloads.map(function (fn) {
return fn();
});
_context12.next = 5;
return this.die();
case 5:
this.bc && this.bc.destroy();
case 6:
case 'end':
return _context12.stop();
}
}
}, _callee12, this);
}));
function destroy() {
return _ref12.apply(this, arguments);
}
return destroy;
}()
}]);
return LeaderElector;
}();
function create(database) {
var elector = new LeaderElector(database);
return elector;
};
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {};
var overwritable = exports.overwritable = {
createLeaderElector: create
};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable
};
},{"../rx-broadcast-channel":28,"../util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/regenerator":57,"unload":769}],20:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwritable = exports.prototypes = exports.rxdb = exports.RxLocalDocument = 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 _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _objectPath = require('object-path');
var _objectPath2 = _interopRequireDefault(_objectPath);
var _deepEqual = require('deep-equal');
var _deepEqual2 = _interopRequireDefault(_deepEqual);
var _rxDocument = require('../rx-document');
var _rxDocument2 = _interopRequireDefault(_rxDocument);
var _rxDatabase = require('../rx-database');
var _rxDatabase2 = _interopRequireDefault(_rxDatabase);
var _rxCollection = require('../rx-collection');
var _rxCollection2 = _interopRequireDefault(_rxCollection);
var _rxChangeEvent = require('../rx-change-event');
var _rxChangeEvent2 = _interopRequireDefault(_rxChangeEvent);
var _docCache = require('../doc-cache');
var _docCache2 = _interopRequireDefault(_docCache);
var _rxError = require('../rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var DOC_CACHE_BY_PARENT = new WeakMap(); /**
* This plugin adds the local-documents-support
* Local documents behave equal then with pouchdb
* @link https://pouchdb.com/guides/local-documents.html
*/
var _getDocCache = function _getDocCache(parent) {
if (!DOC_CACHE_BY_PARENT.has(parent)) {
DOC_CACHE_BY_PARENT.set(parent, _docCache2['default'].create());
}
return DOC_CACHE_BY_PARENT.get(parent);
};
var CHANGE_SUB_BY_PARENT = new WeakMap();
var _getChangeSub = function _getChangeSub(parent) {
if (!CHANGE_SUB_BY_PARENT.has(parent)) {
var sub = parent.$.filter(function (cE) {
return cE.data.isLocal;
}).subscribe(function (cE) {
var docCache = _getDocCache(parent);
var doc = docCache.get(cE.data.doc);
if (doc) doc._handleChangeEvent(cE);
});
parent._subs.push(sub);
CHANGE_SUB_BY_PARENT.set(parent, sub);
}
return CHANGE_SUB_BY_PARENT.get(parent);
};
var LOCAL_PREFIX = '_local/';
var RxLocalDocument = exports.RxLocalDocument = function (_RxDocument$RxDocumen) {
(0, _inherits3['default'])(RxLocalDocument, _RxDocument$RxDocumen);
/**
* @constructor
* @param {string} id
* @param {Object} jsonData
* @param {RxCollection|RxDatabase} parent
*/
function RxLocalDocument(id, jsonData, parent) {
(0, _classCallCheck3['default'])(this, RxLocalDocument);
var _this = (0, _possibleConstructorReturn3['default'])(this, (RxLocalDocument.__proto__ || Object.getPrototypeOf(RxLocalDocument)).call(this, null, jsonData));
_this.id = id;
_this.parent = parent;
return _this;
}
(0, _createClass3['default'])(RxLocalDocument, [{
key: 'toPouchJson',
value: function toPouchJson() {
var data = (0, _clone2['default'])(this._data);
data._id = LOCAL_PREFIX + this.id;
}
}, {
key: '_handleChangeEvent',
//
// overwrites
//
value: function _handleChangeEvent(changeEvent) {
if (changeEvent.data.doc !== this.primary) return;
switch (changeEvent.data.op) {
case 'UPDATE':
var newData = (0, _clone2['default'])(changeEvent.data.v);
var prevSyncData = this._dataSync$.getValue();
var prevData = this._data;
if ((0, _deepEqual2['default'])(prevSyncData, prevData)) {
// document is in sync, overwrite _data
this._data = newData;
if (this._synced$.getValue() !== true) this._synced$.next(true);
} else {
// not in sync, emit to synced$
if (this._synced$.getValue() !== false) this._synced$.next(false);
// overwrite _rev of data
this._data._rev = newData._rev;
}
this._dataSync$.next((0, _clone2['default'])(newData));
break;
case 'REMOVE':
// remove from docCache to assure new upserted RxDocuments will be a new instance
var docCache = _getDocCache(this.parent);
docCache['delete'](this.primary);
this._deleted$.next(true);
break;
}
}
}, {
key: '$emit',
value: function $emit(changeEvent) {
return this.parent.$emit(changeEvent);
}
}, {
key: 'get',
value: function get(objPath) {
if (!this._data) return undefined;
if (typeof objPath !== 'string') throw new TypeError('RxDocument.get(): objPath must be a string');
var valueObj = _objectPath2['default'].get(this._data, objPath);
valueObj = (0, _clone2['default'])(valueObj);
return valueObj;
}
}, {
key: 'get$',
value: function get$(path) {
if (path.includes('.item.')) throw new Error('cannot get observable of in-array fields because order cannot be guessed: ' + path);
if (path === this.primaryPath) throw _rxError2['default'].newRxError('cannot observe primary path');
return this._dataSync$.map(function (data) {
return _objectPath2['default'].get(data, path);
}).distinctUntilChanged().asObservable();
}
}, {
key: 'set',
value: function set(objPath, value) {
if (!value) {
// object path not set, overwrite whole data
var data = (0, _clone2['default'])(objPath);
data._rev = this._data._rev;
this._data = data;
return this;
}
if (objPath === '_id') throw new Error('id cannot be modified');
if (Object.is(this.get(objPath), value)) return;
_objectPath2['default'].set(this._data, objPath, value);
return this;
}
}, {
key: 'save',
value: function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
var saveData, res, changeEvent;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
saveData = (0, _clone2['default'])(this._data);
saveData._id = LOCAL_PREFIX + this.id;
_context.next = 4;
return this.parentPouch.put(saveData);
case 4:
res = _context.sent;
this._data._rev = res.rev;
changeEvent = _rxChangeEvent2['default'].create('UPDATE', _rxDatabase2['default'].isInstanceOf(this.parent) ? this.parent : this.parent.database, _rxCollection2['default'].isInstanceOf(this.parent) ? this.parent : null, this, (0, _clone2['default'])(this._data), true);
this.$emit(changeEvent);
case 8:
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'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
var removeId, changeEvent;
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
removeId = LOCAL_PREFIX + this.id;
_context2.next = 3;
return this.parentPouch.remove(removeId, this._data._rev);
case 3:
_getDocCache(this.parent)['delete'](this.id);
changeEvent = _rxChangeEvent2['default'].create('REMOVE', _rxDatabase2['default'].isInstanceOf(this.parent) ? this.parent : this.parent.database, _rxCollection2['default'].isInstanceOf(this.parent) ? this.parent : null, this, (0, _clone2['default'])(this._data), true);
this.$emit(changeEvent);
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function remove() {
return _ref2.apply(this, arguments);
}
return remove;
}()
}, {
key: 'isLocal',
get: function get() {
return true;
}
}, {
key: 'parentPouch',
get: function get() {
return _getPouchByParent(this.parent);
}
}, {
key: 'allAttachments$',
get: function get() {
// this is overwritte here because we cannot re-set getters on the prototype
throw new Error('cant use attachments on local documents');
}
}, {
key: 'primaryPath',
get: function get() {
return 'id';
}
}, {
key: 'primary',
get: function get() {
return this.id;
}
}, {
key: '$',
get: function get() {
return this._dataSync$.asObservable();
}
}]);
return RxLocalDocument;
}(_rxDocument2['default'].RxDocument);
;
var INIT_DONE = false;
var _init = function _init() {
if (INIT_DONE) return;else INIT_DONE = true;
/**
* overwrite things that not work on local documents
* with throwing function
*/
var getThrowingFun = function getThrowingFun(k) {
return function () {
throw new Error('Function ' + k + ' is not useable on local documents');
};
};
['populate', 'update', 'putAttachment', 'getAttachment', 'allAttachments'].forEach(function (k) {
return RxLocalDocument.prototype[k] = getThrowingFun(k);
});
};
RxLocalDocument.create = function (id, data, parent) {
_init();
_getChangeSub(parent);
var newDoc = new RxLocalDocument(id, data, parent);
_getDocCache(parent).set(id, newDoc);
return newDoc;
};
var _getPouchByParent = function _getPouchByParent(parent) {
if (_rxDatabase2['default'].isInstanceOf(parent)) return parent._adminPouch; // database
else return parent.pouch; // collection
};
/**
* save the local-document-data
* throws if already exists
* @return {RxLocalDocument}
*/
var insertLocal = function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3(id, data) {
var existing, pouch, saveData, res, newDoc;
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(_rxCollection2['default'].isInstanceOf(this) && this._isInMemory)) {
_context3.next = 2;
break;
}
return _context3.abrupt('return', this._parentCollection.insertLocal(id, data));
case 2:
data = (0, _clone2['default'])(data);
_context3.next = 5;
return this.getLocal(id);
case 5:
existing = _context3.sent;
if (!existing) {
_context3.next = 8;
break;
}
throw _rxError2['default'].newRxError('Local document already exists', {
id: id,
data: data
});
case 8:
// create new one
pouch = _getPouchByParent(this);
saveData = (0, _clone2['default'])(data);
saveData._id = LOCAL_PREFIX + id;
_context3.next = 13;
return pouch.put(saveData);
case 13:
res = _context3.sent;
data._rev = res.rev;
newDoc = RxLocalDocument.create(id, data, this);
return _context3.abrupt('return', newDoc);
case 17:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
return function insertLocal(_x, _x2) {
return _ref3.apply(this, arguments);
};
}();
/**
* save the local-document-data
* overwrites existing if exists
* @return {RxLocalDocument}
*/
var upsertLocal = function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4(id, data) {
var existing, doc;
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!(_rxCollection2['default'].isInstanceOf(this) && this._isInMemory)) {
_context4.next = 2;
break;
}
return _context4.abrupt('return', this._parentCollection.upsertLocal(id, data));
case 2:
_context4.next = 4;
return this.getLocal(id);
case 4:
existing = _context4.sent;
if (existing) {
_context4.next = 10;
break;
}
// create new one
doc = this.insertLocal(id, data);
return _context4.abrupt('return', doc);
case 10:
// update existing
data._rev = existing._data._rev;
existing._data = data;
_context4.next = 14;
return existing.save();
case 14:
return _context4.abrupt('return', existing);
case 15:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
return function upsertLocal(_x3, _x4) {
return _ref4.apply(this, arguments);
};
}();
var getLocal = function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5(id) {
var pouch, docCache, found, docData, doc;
return _regenerator2['default'].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (!(_rxCollection2['default'].isInstanceOf(this) && this._isInMemory)) {
_context5.next = 2;
break;
}
return _context5.abrupt('return', this._parentCollection.getLocal(id));
case 2:
pouch = _getPouchByParent(this);
docCache = _getDocCache(this);
// check in doc-cache
found = docCache.get(id);
// check in pouch
if (found) {
_context5.next = 19;
break;
}
_context5.prev = 6;
_context5.next = 9;
return pouch.get(LOCAL_PREFIX + id);
case 9:
docData = _context5.sent;
if (docData) {
_context5.next = 12;
break;
}
return _context5.abrupt('return', null);
case 12:
doc = RxLocalDocument.create(id, docData, this);
return _context5.abrupt('return', doc);
case 16:
_context5.prev = 16;
_context5.t0 = _context5['catch'](6);
return _context5.abrupt('return', null);
case 19:
return _context5.abrupt('return', found);
case 20:
case 'end':
return _context5.stop();
}
}
}, _callee5, this, [[6, 16]]);
}));
return function getLocal(_x5) {
return _ref5.apply(this, arguments);
};
}();
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {
RxCollection: function RxCollection(proto) {
proto.insertLocal = insertLocal;
proto.upsertLocal = upsertLocal;
proto.getLocal = getLocal;
},
RxDatabase: function RxDatabase(proto) {
proto.insertLocal = insertLocal;
proto.upsertLocal = upsertLocal;
proto.getLocal = getLocal;
}
};
var overwritable = exports.overwritable = {};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable
};
},{"../doc-cache":6,"../rx-change-event":29,"../rx-collection":30,"../rx-database":31,"../rx-document":32,"../rx-error":33,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/inherits":53,"babel-runtime/helpers/possibleConstructorReturn":54,"babel-runtime/regenerator":57,"clone":63,"deep-equal":496,"object-path":567}],21:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwritable = exports.prototypes = exports.rxdb = exports.RxReplicationState = 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);
exports.createRxReplicationState = createRxReplicationState;
exports.watchForChanges = watchForChanges;
exports.sync = sync;
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _pouchdbReplication = require('pouchdb-replication');
var _pouchdbReplication2 = _interopRequireDefault(_pouchdbReplication);
var _util = require('../util');
var util = _interopRequireWildcard(_util);
var _core = require('../core');
var _core2 = _interopRequireDefault(_core);
var _rxCollection = require('../rx-collection');
var _rxCollection2 = _interopRequireDefault(_rxCollection);
var _rxChangeEvent = require('../rx-change-event');
var _rxChangeEvent2 = _interopRequireDefault(_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 }; }
// add pouchdb-replication-plugin
/**
* this plugin adds the RxCollection.sync()-function to rxdb
* you can use it to sync collections with remote or local couchdb-instances
*/
_core2['default'].plugin(_pouchdbReplication2['default']);
var RxReplicationState = exports.RxReplicationState = function () {
function RxReplicationState(collection) {
var _this = this;
(0, _classCallCheck3['default'])(this, RxReplicationState);
this._subs = [];
this.collection = collection;
this._pouchEventEmitterObject = null;
this._subjects = {
change: new util.Rx.Subject(),
docs: new util.Rx.Subject(),
active: new util.Rx.BehaviorSubject(false),
complete: new util.Rx.BehaviorSubject(false),
error: new util.Rx.Subject()
};
// create getters
Object.keys(this._subjects).forEach(function (key) {
Object.defineProperty(_this, key + '$', {
get: function get() {
return this._subjects[key].asObservable();
}
});
});
}
(0, _createClass3['default'])(RxReplicationState, [{
key: 'setPouchEventEmitter',
value: function setPouchEventEmitter(evEmitter) {
var _this2 = this;
if (this._pouchEventEmitterObject) throw new Error('already added');
this._pouchEventEmitterObject = evEmitter;
// change
this._subs.push(util.Rx.Observable.fromEvent(evEmitter, 'change').subscribe(function (ev) {
return _this2._subjects.change.next(ev);
}));
// docs
this._subs.push(util.Rx.Observable.fromEvent(evEmitter, 'change').subscribe(function (ev) {
if (_this2._subjects.docs.observers.length === 0 || ev.direction !== 'pull') return;
ev.change.docs.filter(function (doc) {
return doc.language !== 'query';
}) // remove internal docs
.map(function (doc) {
return _this2.collection._handleFromPouch(doc);
}) // do primary-swap and keycompression
.forEach(function (doc) {
return _this2._subjects.docs.next(doc);
});
}));
// error
this._subs.push(util.Rx.Observable.fromEvent(evEmitter, 'error').subscribe(function (ev) {
return _this2._subjects.error.next(ev);
}));
// active
this._subs.push(util.Rx.Observable.fromEvent(evEmitter, 'active').subscribe(function () {
return _this2._subjects.active.next(true);
}));
this._subs.push(util.Rx.Observable.fromEvent(evEmitter, 'paused').subscribe(function () {
return _this2._subjects.active.next(false);
}));
// complete
this._subs.push(util.Rx.Observable.fromEvent(evEmitter, 'complete').subscribe(function (info) {
return _this2._subjects.complete.next(info);
}));
}
}, {
key: 'cancel',
value: function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (this._pouchEventEmitterObject) this._pouchEventEmitterObject.cancel();
this._subs.forEach(function (sub) {
return sub.unsubscribe();
});
case 2:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function cancel() {
return _ref.apply(this, arguments);
}
return cancel;
}()
}]);
return RxReplicationState;
}();
function createRxReplicationState(collection) {
return new RxReplicationState(collection);
}
/**
* waits for external changes to the database
* and ensures they are emitted to the internal RxChangeEvent-Stream
* TODO this can be removed by listening to the pull-change-events of the RxReplicationState
*/
function watchForChanges() {
var _this3 = this;
if (this.synced) return;
/**
* 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(this.pouch.changes({
since: 'now',
live: true,
include_docs: true
}), 'change').filter(function (c) {
return c.id.charAt(0) !== '_';
}).map(function (c) {
return c.doc;
}).filter(function (doc) {
return !_this3._changeEventBuffer.buffer.map(function (cE) {
return cE.data.v._rev;
}).includes(doc._rev);
}).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) {
_this3.$emit(_rxChangeEvent2['default'].fromPouchChange(doc, _this3));
});
this._subs.push(pouch$);
var ob2 = this.$.map(function (cE) {
return cE.data.v;
}).map(function (doc) {
if (doc && sendChanges[doc._rev]) sendChanges[doc._rev] = 'NO';
}).subscribe();
this._subs.push(ob2);
this.synced = true;
}
function sync(_ref2) {
var _this4 = this;
var remote = _ref2.remote,
_ref2$waitForLeadersh = _ref2.waitForLeadership,
waitForLeadership = _ref2$waitForLeadersh === undefined ? true : _ref2$waitForLeadersh,
_ref2$direction = _ref2.direction,
direction = _ref2$direction === undefined ? {
pull: true,
push: true
} : _ref2$direction,
_ref2$options = _ref2.options,
options = _ref2$options === undefined ? {
live: true,
retry: true
} : _ref2$options,
query = _ref2.query;
options = (0, _clone2['default'])(options);
// if remote is RxCollection, get internal pouchdb
if (_rxCollection2['default'].isInstanceOf(remote)) remote = remote.pouch;
if (query && this !== query.collection) throw new Error('RxCollection.sync() query must be from the same RxCollection');
var syncFun = util.pouchReplicationFunction(this.pouch, direction);
if (query) options.selector = query.keyCompress().selector;
var repState = createRxReplicationState(this);
// run internal so .sync() does not have to be async
(0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
var pouchSync;
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!waitForLeadership) {
_context2.next = 5;
break;
}
_context2.next = 3;
return _this4.database.waitForLeadership();
case 3:
_context2.next = 7;
break;
case 5:
_context2.next = 7;
return util.promiseWait(0);
case 7:
pouchSync = syncFun(remote, options);
_this4.watchForChanges();
repState.setPouchEventEmitter(pouchSync);
_this4._repStates.push(repState);
case 11:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this4);
}))();
return repState;
};
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {
RxCollection: function RxCollection(proto) {
proto.watchForChanges = watchForChanges;
proto.sync = sync;
}
};
var overwritable = exports.overwritable = {};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
overwritable: overwritable,
watchForChanges: watchForChanges,
sync: sync
};
},{"../core":3,"../rx-change-event":29,"../rx-collection":30,"../util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/regenerator":57,"clone":63,"pouchdb-replication":605}],22:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hooks = exports.rxdb = undefined;
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
exports.checkFieldNameRegex = checkFieldNameRegex;
exports.validateFieldsDeep = validateFieldsDeep;
exports.checkSchema = checkSchema;
var _objectPath = require('object-path');
var _objectPath2 = _interopRequireDefault(_objectPath);
var _rxDocument = require('../rx-document');
var _rxDocument2 = _interopRequireDefault(_rxDocument);
var _rxError = require('../rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
var _rxSchema = require('../rx-schema');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* checks if the fieldname is allowed
* this makes sure that the fieldnames can be transformed into javascript-vars
* and does not conquer the observe$ and populate_ fields
* @param {string} fieldName
* @throws {Error}
*/
/**
* does additional checks over the schema-json
* to ensure nothing is broken or not supported
*/
function checkFieldNameRegex(fieldName) {
if (fieldName === '') return;
if (['properties', 'language'].includes(fieldName)) throw new Error('fieldname is not allowed: ' + fieldName);
var regexStr = '^[a-zA-Z][[a-zA-Z0-9_]*]?[a-zA-Z0-9]$';
var regex = new RegExp(regexStr);
if (!fieldName.match(regex)) {
throw _rxError2['default'].newRxError('fieldnames do not match the regex', {
regex: regexStr,
fieldName: fieldName
});
}
};
/**
* validate that all schema-related things are ok
* @param {object} jsonSchema
* @return {boolean} true always
*/
function validateFieldsDeep(jsonSchema) {
function checkField(fieldName, schemaObj, path) {
if (typeof fieldName === 'string' && (typeof schemaObj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(schemaObj)) === 'object' && !Array.isArray(schemaObj)) checkFieldNameRegex(fieldName);
// 'item' only allowed it type=='array'
if (schemaObj.hasOwnProperty('item') && schemaObj.type !== 'array') throw new Error('name \'item\' reserved for array-fields: ' + fieldName);
// if ref given, must be type=='string' or type=='array' with string-items
if (schemaObj.hasOwnProperty('ref')) {
switch (schemaObj.type) {
case 'string':
break;
case 'array':
if (!schemaObj.items || !schemaObj.items.type || schemaObj.items.type !== 'string') throw new Error('fieldname ' + fieldName + ' has a ref-array but items-type is not string');
break;
default:
throw new Error('fieldname ' + fieldName + ' has a ref but is not type string or array');
break;
}
}
// if primary is ref, throw
if (schemaObj.hasOwnProperty('ref') && schemaObj.primary) throw new Error('fieldname ' + fieldName + ' cannot be primary and ref at same time');
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['default']) throw new Error('default-values 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 _ ' + fieldName);
}
}
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;
};
/**
* does the checking
* @param {object} jsonId json-object like in json-schema-standard
* @throws {Error} if something is not ok
*/
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');
// check version
if (!jsonID.hasOwnProperty('version') || typeof jsonID.version !== 'number' || jsonID.version < 0) throw new Error('schema need an number>=0 as version; given: ' + jsonID.version);
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');
}
// check if RxDocument-property
if (_rxDocument2['default'].properties().includes(key)) throw new Error('top-level fieldname is not allowed: ' + key);
});
// 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) {
if (!Array.isArray(jsonID.compoundIndexes)) throw new Error('compoundIndexes must be an array');
jsonID.compoundIndexes.forEach(function (ar) {
if (!Array.isArray(ar)) throw new Error('compoundIndexes must contain arrays');
ar.forEach(function (str) {
if (typeof str !== 'string') throw new Error('compoundIndexes.array must contains strings');
});
});
}
// check that indexes are string
(0, _rxSchema.getIndexes)(jsonID).reduce(function (a, b) {
return a.concat(b);
}, []).filter(function (elem, pos, arr) {
return arr.indexOf(elem) === pos;
}) // unique
.map(function (key) {
var schemaObj = _objectPath2['default'].get(jsonID, 'properties.' + key.replace('.', '.properties.'));
if (!schemaObj || (typeof schemaObj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(schemaObj)) !== 'object') throw new Error('given index(' + key + ') is not defined in schema');
return {
key: key,
schemaObj: schemaObj
};
}).filter(function (index) {
return index.schemaObj.type !== 'string' && index.schemaObj.type !== 'integer';
}).forEach(function (index) {
throw new Error('given indexKey (' + index.key + ') is not type:string but\n ' + index.schemaObj.type);
});
};
var rxdb = exports.rxdb = true;
var hooks = exports.hooks = {
preCreateRxSchema: checkSchema
};
exports['default'] = {
rxdb: rxdb,
hooks: hooks
};
},{"../rx-document":32,"../rx-error":33,"../rx-schema":35,"babel-runtime/helpers/typeof":56,"object-path":567}],23:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.prototypes = exports.rxdb = exports.RxQueryUpdate = undefined;
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var RxQueryUpdate = exports.RxQueryUpdate = function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee(updateObj) {
var docs;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.exec();
case 2:
docs = _context.sent;
if (docs) {
_context.next = 5;
break;
}
return _context.abrupt('return', null);
case 5:
if (!Array.isArray(docs)) {
_context.next = 10;
break;
}
_context.next = 8;
return Promise.all(docs.map(function (doc) {
return doc.update(updateObj);
}));
case 8:
_context.next = 12;
break;
case 10:
_context.next = 12;
return docs.update(updateObj);
case 12:
return _context.abrupt('return', docs);
case 13:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function RxQueryUpdate(_x) {
return _ref.apply(this, arguments);
};
}();
exports.update = update;
var _modifyjs = require('modifyjs');
var _modifyjs2 = _interopRequireDefault(_modifyjs);
var _deepEqual = require('deep-equal');
var _deepEqual2 = _interopRequireDefault(_deepEqual);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* this plugin allows delta-updates with mongo-like-syntax
* It's using modifyjs internally
* @link https://github.com/lgandecki/modifyjs
*/
function update(updateObj) {
var _this = this;
var newDoc = (0, _modifyjs2['default'])(this._data, updateObj);
Object.keys(this._data).forEach(function (previousPropName) {
if (newDoc[previousPropName]) {
// if we don't check inequality, it triggers an update attempt on fields that didn't really change,
// which causes problems with "readonly" fields
if (!(0, _deepEqual2['default'])(_this._data[previousPropName], newDoc[previousPropName])) _this._data[previousPropName] = newDoc[previousPropName];
} else delete _this._data[previousPropName];
});
delete newDoc._rev;
delete newDoc._id;
Object.keys(newDoc).filter(function (newPropName) {
return !(0, _deepEqual2['default'])(_this._data[newPropName], newDoc[newPropName]);
}).forEach(function (newPropName) {
return _this._data[newPropName] = newDoc[newPropName];
});
return this.save();
}
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {
RxDocument: function RxDocument(proto) {
proto.update = update;
},
RxQuery: function RxQuery(proto) {
proto.update = RxQueryUpdate;
}
};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes
};
},{"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/regenerator":57,"deep-equal":496,"modifyjs":562}],24:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hooks = exports.prototypes = exports.rxdb = undefined;
var _isMyJsonValid = require('is-my-json-valid');
var _isMyJsonValid2 = _interopRequireDefault(_isMyJsonValid);
var _rxError = require('../rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
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 }; }
/**
* cache the validators by the schema-hash
* so we can reuse them when multiple collections have the same schema
* @type {Object}
*/
var validatorsCache = {};
/**
* returns the parsed validator from is-my-json-valid
* @param {string} [schemaPath=''] if given, the schema for the sub-path is used
* @
*/
/**
* this plugin validates documents before they can be inserted into the RxCollection.
* It's using is-my-json-valid as jsonschema-validator
* @link https://github.com/mafintosh/is-my-json-valid
*/
var _getValidator = function _getValidator() {
var schemaPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var hash = this.hash;
if (!validatorsCache[hash]) validatorsCache[hash] = {};
var validatorsOfHash = validatorsCache[hash];
if (!validatorsOfHash[schemaPath]) {
var schemaPart = schemaPath === '' ? this.jsonID : this.getSchemaByObjectPath(schemaPath);
if (!schemaPart) {
throw _rxError2['default'].newRxError('Sub-schema not found, does the schemaPath exists in your schema?', {
schemaPath: schemaPath
});
}
validatorsOfHash[schemaPath] = (0, _isMyJsonValid2['default'])(schemaPart);
}
return validatorsOfHash[schemaPath];
};
/**
* validates the given object against the schema
* @param {any} obj
* @param {String} [schemaPath=''] if given, the sub-schema will be validated
* @throws {RxError} if not valid
* @return {any} obj if validation successful
*/
var validate = function validate(obj) {
var schemaPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var useValidator = this._getValidator(schemaPath);
var isValid = useValidator(obj);
if (isValid) return obj;else {
throw _rxError2['default'].newRxError('object does not match schema', {
errors: useValidator.errors,
schemaPath: schemaPath,
obj: obj,
schema: this.jsonID
});
};
};
var runAfterSchemaCreated = function runAfterSchemaCreated(rxSchema) {
// pre-generate the isMyJsonValid-validator from the schema
util.requestIdleCallbackIfAvailable(function () {
rxSchema._getValidator();
});
};
var rxdb = exports.rxdb = true;
var prototypes = exports.prototypes = {
/**
* set validate-function for the RxSchema.prototype
* @param {[type]} prototype of RxSchema
*/
RxSchema: function RxSchema(proto) {
proto._getValidator = _getValidator;
proto.validate = validate;
}
};
var hooks = exports.hooks = {
createRxSchema: runAfterSchemaCreated
};
exports['default'] = {
rxdb: rxdb,
prototypes: prototypes,
hooks: hooks
};
},{"../rx-error":33,"../util":37,"is-my-json-valid":529}],25:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _pouchdbCore = require('pouchdb-core');
var _pouchdbCore2 = _interopRequireDefault(_pouchdbCore);
var _pouchdbFind = require('pouchdb-find');
var _pouchdbFind2 = _interopRequireDefault(_pouchdbFind);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* this handles the pouchdb-instance
* to easy add modules and manipulate things
* Adapters can be found here:
* @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules
*/
_pouchdbCore2['default'].plugin(_pouchdbFind2['default']);
/**
* get the number of all undeleted documents
* @param {PouchDB} pouchdb instance
* @return {Promise} number of documents
*/
// pouchdb-find
_pouchdbCore2['default'].countAllUndeleted = function (pouchdb) {
return pouchdb.allDocs({
include_docs: false,
attachments: false
}).then(function (docs) {
return docs.rows.filter(function (row) {
return !row.id.startsWith('_design/');
}).length;
});
};
/**
* get a batch of documents from the pouch-instance
* @param {PouchDB} pouchdb instance
* @param {number} limit
* @return {Promise<{}[]>} array with documents
*/
_pouchdbCore2['default'].getBatch = function (pouchdb, limit) {
if (limit <= 1) throw new Error('PouchDB.getBatch: limit must be > 2');
return pouchdb.allDocs({
include_docs: true,
attachments: false,
limit: limit
}).then(function (docs) {
return docs.rows.map(function (row) {
return row.doc;
}).filter(function (doc) {
return !doc._id.startsWith('_design');
});
});
};
exports['default'] = _pouchdbCore2['default'];
},{"pouchdb-core":595,"pouchdb-find":598}],26:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* the query-cache makes sure that on every query-state, exactly one instance can exist
* if you use the same mango-query more then once, it will only search the database once.
*/
var QueryCache = function () {
function QueryCache() {
(0, _classCallCheck3["default"])(this, QueryCache);
this.subs = [];
this._map = {};
}
/**
* check if an equal query is in the cache,
* if true, return the cached one,
* if false, save the given one and return it
* @param {RxQuery} query
* @return {RxQuery}
*/
(0, _createClass3["default"])(QueryCache, [{
key: "getByQuery",
value: function getByQuery(query) {
var stringRep = query.toString();
var has = this._map[stringRep];
if (!has) {
this._map[stringRep] = query;
return query;
} else return has;
}
}, {
key: "destroy",
value: function destroy() {
this.subs.forEach(function (sub) {
return sub.unsubscribe();
});
this._map = {};
}
}]);
return QueryCache;
}();
;
function create() {
return new QueryCache();
}
exports["default"] = {
create: create
};
},{"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51}],27:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.enableDebugging = enableDebugging;
exports.enable = enable;
exports.create = create;
var _pouchdbSelectorCore = require('pouchdb-selector-core');
var _objectPath = require('object-path');
var _objectPath2 = _interopRequireDefault(_objectPath);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* if a query is observed and a changeEvent comes in,
* the QueryChangeDetector tries to execute the changeEvent-delta on the exisiting query-results
* or tells the query it should re-exec on the database if previous not possible.
*
* This works equal to meteors oplog-observe-driver
* @link https://github.com/meteor/docs/blob/version-NEXT/long-form/oplog-observe-driver.md
*/
var DEBUG = false;
var ENABLED = false;
var QueryChangeDetector = function () {
function QueryChangeDetector(query) {
(0, _classCallCheck3['default'])(this, QueryChangeDetector);
this.query = query;
this.primaryKey = this.query.collection.schema.primaryPath;
}
/**
* @param {ChangeEvent[]} changeEvents
* @return {boolean|Object[]} true if mustReExec, false if no change, array if calculated new results
*/
(0, _createClass3['default'])(QueryChangeDetector, [{
key: 'runChangeDetection',
value: function runChangeDetection(changeEvents) {
var _this = this;
if (changeEvents.length === 0) return false;
if (!ENABLED) return true;
var resultsData = this.query._resultsData;
var changed = false;
var found = changeEvents.find(function (changeEvent) {
var res = _this.handleSingleChange(resultsData, changeEvent);
if (Array.isArray(res)) {
changed = true;
resultsData = res;
return false;
} else if (res) return true;
});
if (found) return true;
if (!changed) return false;else return resultsData;
}
}, {
key: '_debugMessage',
value: function _debugMessage(key) {
var changeEventData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var title = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'optimized';
console.dir({
name: 'QueryChangeDetector',
title: title,
query: this.query.toString(),
key: key,
changeEventData: changeEventData
});
}
/**
* handle a single ChangeEvent and try to calculate the new results
* @param {Object[]} resultsData of previous results
* @param {ChangeEvent} changeEvent
* @return {boolean|Object[]} true if mustReExec, false if no change, array if calculated new results
*/
}, {
key: 'handleSingleChange',
value: function handleSingleChange(resultsData, changeEvent) {
var _this2 = this;
var results = resultsData.slice(0); // copy to stay immutable
var options = this.query.toJSON();
var docData = changeEvent.data.v;
var wasDocInResults = this._isDocInResultData(docData, resultsData);
var doesMatchNow = this.doesDocMatchQuery(docData);
var isFilled = !options.limit || options.limit && resultsData.length >= options.limit;
var limitAndFilled = options.limit && resultsData.length >= options.limit;
if (DEBUG) {
console.log('!!!:!!!: handleSingleChange()'); // TODO this should not be an error
this._debugMessage('start', changeEvent.data.v, 'handleSingleChange()');
console.log('changeEvent.data:');
console.dir(changeEvent.data);
console.log('wasDocInResults: ' + wasDocInResults);
console.log('doesMatchNow: ' + doesMatchNow);
console.log('isFilled: ' + isFilled);
}
var _sortAfter = null;
var sortAfter = function sortAfter() {
if (_sortAfter === null) _sortAfter = _this2._isSortedBefore(results[results.length - 1], docData);
return _sortAfter;
};
var _sortBefore = null;
var sortBefore = function sortBefore() {
if (_sortBefore === null) _sortBefore = _this2._isSortedBefore(docData, results[0]);
return _sortBefore;
};
var _sortFieldChanged = null;
var sortFieldChanged = function sortFieldChanged() {
if (_sortFieldChanged === null) {
var docBefore = resultsData.find(function (doc) {
return doc[_this2.primaryKey] === docData[_this2.primaryKey];
});
_sortFieldChanged = _this2._sortFieldChanged(docBefore, docData);
}
return _sortFieldChanged;
};
if (changeEvent.data.op === 'REMOVE') {
// R1 (never matched)
if (!doesMatchNow) {
DEBUG && this._debugMessage('R1', docData);
return false;
}
// R2 sorted before got removed but results not filled
if (options.skip && doesMatchNow && sortBefore() && !isFilled) {
DEBUG && this._debugMessage('R2', docData);
results.shift();
return results;
}
// R3 (was in results and got removed)
if (doesMatchNow && wasDocInResults && !isFilled) {
DEBUG && this._debugMessage('R3', docData);
results = results.filter(function (doc) {
return doc[_this2.primaryKey] !== docData[_this2.primaryKey];
});
return results;
}
// R3.1 was in results and got removed, no limit, no skip
if (doesMatchNow && wasDocInResults && !options.limit && !options.skip) {
DEBUG && this._debugMessage('R3.1', docData);
results = results.filter(function (doc) {
return doc[_this2.primaryKey] !== docData[_this2.primaryKey];
});
return results;
}
// R4 matching but after results got removed
if (doesMatchNow && options.limit && sortAfter()) {
DEBUG && this._debugMessage('R4', docData);
return false;
}
} else {
// U1 doc not matched and also not matches now
if (!options.skip && !options.limit && !wasDocInResults && !doesMatchNow) {
DEBUG && this._debugMessage('U1', docData);
return false;
}
// U2 still matching -> only resort
if (!options.skip && !options.limit && wasDocInResults && doesMatchNow) {
// DEBUG && this._debugMessage('U2', docData);
// replace but make sure its the same position
var wasDoc = results.find(function (doc) {
return doc[_this2.primaryKey] === docData[_this2.primaryKey];
});
var i = results.indexOf(wasDoc);
results[i] = docData;
if (sortFieldChanged()) {
DEBUG && this._debugMessage('U2 - resort', docData);
return this._resortDocData(results);
} else {
DEBUG && this._debugMessage('U2 - no-resort', docData);
return results;
}
}
// U3 not matched, but matches now, no.skip, limit < length
if (!options.skip && !limitAndFilled && !wasDocInResults && doesMatchNow) {
DEBUG && this._debugMessage('U3', docData);
results.push(docData);
// console.log('U3: preSort:');
// console.dir(results);
var sorted = this._resortDocData(results);
// console.log('U3: postSort:');
// console.dir(sorted);
return sorted;
}
}
// if no optimisation-algo matches, return mustReExec:true
return true;
}
/**
* check if the document matches the query
* @param {object} docData
* @return {boolean}
*/
}, {
key: 'doesDocMatchQuery',
value: function doesDocMatchQuery(docData) {
docData = this.query.collection.schema.swapPrimaryToId(docData);
var inMemoryFields = Object.keys(this.query.toJSON().selector);
var retDocs = (0, _pouchdbSelectorCore.filterInMemoryFields)([{
doc: docData
}], {
selector: (0, _pouchdbSelectorCore.massageSelector)(this.query.toJSON().selector)
}, inMemoryFields);
var ret = retDocs.length === 1;
return ret;
}
/**
* check if the document exists in the results data
* @param {object} docData
* @param {object[]} resultData
*/
}, {
key: '_isDocInResultData',
value: function _isDocInResultData(docData, resultData) {
var primaryPath = this.query.collection.schema.primaryPath;
var first = resultData.find(function (doc) {
return doc[primaryPath] === docData[primaryPath];
});
return !!first;
}
/**
* checks if the sort-relevant fields have changed
* @param {object} docDataBefore
* @param {object} docDataAfter
* @return {boolean}
*/
}, {
key: '_sortFieldChanged',
value: function _sortFieldChanged(docDataBefore, docDataAfter) {
var options = this.query.toJSON();
var sortFields = options.sort.map(function (sortObj) {
return Object.keys(sortObj).pop();
});
var changed = false;
sortFields.find(function (field) {
var beforeData = _objectPath2['default'].get(docDataBefore, field);
var afterData = _objectPath2['default'].get(docDataAfter, field);
if (beforeData !== afterData) {
changed = true;
return true;
} else return false;
});
return changed;
}
/**
* checks if the newDocLeft would be placed before docDataRight
* when the query would be reExecuted
* @param {Object} docDataNew
* @param {Object} docDataIs
* @return {boolean} true if before, false if after
*/
}, {
key: '_isSortedBefore',
value: function _isSortedBefore(docDataLeft, docDataRight) {
var options = this.query.toJSON();
var inMemoryFields = Object.keys(this.query.toJSON().selector);
var swappedLeft = this.query.collection.schema.swapPrimaryToId(docDataLeft);
var swappedRight = this.query.collection.schema.swapPrimaryToId(docDataRight);
var rows = [swappedLeft, swappedRight].map(function (doc) {
return {
id: doc._id,
doc: doc
};
});
// TODO use createFieldSorter
var sortedRows = (0, _pouchdbSelectorCore.filterInMemoryFields)(rows, {
selector: (0, _pouchdbSelectorCore.massageSelector)(this.query.toJSON().selector),
sort: options.sort
}, inMemoryFields);
return sortedRows[0].id === swappedLeft._id;
}
/**
* reruns the sort on the given resultsData
* @param {object[]} resultsData
* @return {object[]}
*/
}, {
key: '_resortDocData',
value: function _resortDocData(resultsData) {
var _this3 = this;
var rows = resultsData.map(function (doc) {
return {
doc: _this3.query.collection.schema.swapPrimaryToId(doc)
};
});
var options = this.query.toJSON();
var inMemoryFields = Object.keys(this.query.toJSON().selector);
// TODO use createFieldSorter
var sortedRows = (0, _pouchdbSelectorCore.filterInMemoryFields)(rows, {
selector: (0, _pouchdbSelectorCore.massageSelector)(this.query.toJSON().selector),
sort: options.sort
}, inMemoryFields);
var sortedDocs = sortedRows.map(function (row) {
return row.doc;
}).map(function (doc) {
return _this3.query.collection.schema.swapIdToPrimary(doc);
});
return sortedDocs;
}
}]);
return QueryChangeDetector;
}();
function enableDebugging() {
console.log('QueryChangeDetector.enableDebugging()');
DEBUG = true;
};
function enable() {
var set = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
console.log('QueryChangeDetector.enableDebugging(' + set + ')');
ENABLED = set;
}
/**
* @param {RxQuery} query
* @return {QueryChangeDetector}
*/
function create(query) {
var ret = new QueryChangeDetector(query);
return ret;
}
exports['default'] = {
create: create,
enableDebugging: enableDebugging,
enable: enable
};
},{"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"object-path":567,"pouchdb-selector-core":606}],28:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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.canIUse = canIUse;
exports.create = create;
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 }; }
/**
* this is a wrapper for BroadcastChannel to integrate it with RxJS
* @link https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
*/
var RxBroadcastChannel = function () {
function RxBroadcastChannel(database, name) {
(0, _classCallCheck3['default'])(this, RxBroadcastChannel);
this.name = name;
this.database = database;
this.token = database.token;
}
/**
* @return {BroadcastChannel}
*/
(0, _createClass3['default'])(RxBroadcastChannel, [{
key: 'write',
/**
* write data to the channel
* @param {string} type
* @param {Object} data
* @return {Promise}
*/
value: function write(type, data) {
return this.bc.postMessage(JSON.stringify({
type: type,
it: this.token,
data: data,
t: new Date().getTime()
}));
}
}, {
key: 'destroy',
value: function destroy() {
this._bc && this._bc.close();
}
}, {
key: 'bc',
get: function get() {
if (!this._bc) {
this._bc = new BroadcastChannel('RxDB:' + this.database.name + ':' + this.name);
}
return this._bc;
}
/**
* @return {Observable}
*/
}, {
key: '$',
get: function get() {
var _this = this;
if (!this._$) {
this._$ = util.Rx.Observable.fromEvent(this.bc, 'message').map(function (msg) {
return msg.data;
}).map(function (strMsg) {
return JSON.parse(strMsg);
}).filter(function (msg) {
return msg.it !== _this.token;
});
}
return this._$;
}
}]);
return RxBroadcastChannel;
}();
/**
* Detect if client can use BroadcastChannel
* @return {Boolean}
*/
var _canIUse = null;
function canIUse() {
if (_canIUse === null) {
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') _canIUse = true;else _canIUse = false;
}
return _canIUse;
}
/**
* returns null if no bc available
* @return {BroadcastChannel} bc which is observable
*/
function create(database, name) {
if (!canIUse()) return null;
return new RxBroadcastChannel(database, name);
}
exports['default'] = {
create: create,
canIUse: canIUse
};
},{"./util":37,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/typeof":56}],29:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RxChangeEvent = undefined;
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.fromJSON = fromJSON;
exports.fromPouchChange = fromPouchChange;
exports.create = create;
exports.isInstanceOf = isInstanceOf;
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 RxChangeEvent = exports.RxChangeEvent = function () {
function RxChangeEvent(data) {
(0, _classCallCheck3['default'])(this, RxChangeEvent);
this.data = data;
}
(0, _createClass3['default'])(RxChangeEvent, [{
key: 'toJSON',
value: function toJSON() {
var ret = {
op: this.data.op,
t: this.data.t,
db: this.data.db,
it: this.data.it,
isLocal: this.data.isLocal
};
if (this.data.col) ret.col = this.data.col;
if (this.data.doc) ret.doc = this.data.doc;
if (this.data.v) ret.v = this.data.v;
return ret;
}
}, {
key: 'isIntern',
value: function isIntern() {
if (this.data.col && this.data.col.charAt(0) === '_') return true;
return false;
}
}, {
key: 'isSocket',
value: function isSocket() {
if (this.data.col && this.data.col === '_socket') return true;
return false;
}
}, {
key: 'hash',
get: function get() {
if (!this._hash) this._hash = util.hash(this.data);
return this._hash;
}
}]);
return RxChangeEvent;
}(); /**
* RxChangeEvents a emitted when something in the database changes
* they can be grabbed by the observables of database, collection and document
*/
function fromJSON(data) {
return new RxChangeEvent(data);
}
function fromPouchChange(changeDoc, collection) {
var op = changeDoc._rev.startsWith('1-') ? 'INSERT' : 'UPDATE';
if (changeDoc._deleted) op = 'REMOVE';
// decompress / primarySwap
changeDoc = collection._handleFromPouch(changeDoc);
var data = {
op: op,
t: new Date().getTime(),
db: 'remote',
col: collection.name,
it: collection.database.token,
doc: changeDoc[collection.schema.primaryPath],
v: changeDoc
};
return new RxChangeEvent(data);
}
function create(op, database, collection, doc, value) {
var isLocal = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
var data = {
op: op,
t: new Date().getTime(),
db: database.name,
it: database.token,
isLocal: isLocal
};
if (collection) data.col = collection.name;
if (doc) data.doc = doc.primary;
if (value) data.v = value;
return new RxChangeEvent(data);
}
function isInstanceOf(obj) {
return obj instanceof RxChangeEvent;
}
exports['default'] = {
fromJSON: fromJSON,
fromPouchChange: fromPouchChange,
create: create,
isInstanceOf: isInstanceOf
};
},{"./util":37,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51}],30:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.create = exports.RxCollection = undefined;
var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
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 _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
/**
* creates and prepares a new collection
* @param {RxDatabase} database
* @param {string} name
* @param {RxSchema} schema
* @param {?Object} [pouchSettings={}]
* @param {?Object} [migrationStrategies={}]
* @return {Promise.} promise with collection
*/
var create = exports.create = function () {
var _ref12 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee11(_ref11) {
var database = _ref11.database,
name = _ref11.name,
schema = _ref11.schema,
_ref11$pouchSettings = _ref11.pouchSettings,
pouchSettings = _ref11$pouchSettings === undefined ? {} : _ref11$pouchSettings,
_ref11$migrationStrat = _ref11.migrationStrategies,
migrationStrategies = _ref11$migrationStrat === undefined ? {} : _ref11$migrationStrat,
_ref11$autoMigrate = _ref11.autoMigrate,
autoMigrate = _ref11$autoMigrate === undefined ? true : _ref11$autoMigrate,
_ref11$statics = _ref11.statics,
statics = _ref11$statics === undefined ? {} : _ref11$statics,
_ref11$methods = _ref11.methods,
methods = _ref11$methods === undefined ? {} : _ref11$methods,
_ref11$attachments = _ref11.attachments,
attachments = _ref11$attachments === undefined ? {} : _ref11$attachments;
var collection;
return _regenerator2['default'].wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
if (_rxSchema2['default'].isInstanceOf(schema)) {
_context11.next = 2;
break;
}
throw new TypeError('given schema is no Schema-object');
case 2:
if (_rxDatabase2['default'].isInstanceOf(database)) {
_context11.next = 4;
break;
}
throw new TypeError('given database is no Database-object');
case 4:
if (!(typeof autoMigrate !== 'boolean')) {
_context11.next = 6;
break;
}
throw new TypeError('autoMigrate must be boolean');
case 6:
util.validateCouchDBString(name);
checkMigrationStrategies(schema, migrationStrategies);
// check ORM-methods
checkOrmMethods(statics);
checkOrmMethods(methods);
checkOrmMethods(attachments);
Object.keys(methods).filter(function (funName) {
return schema.topLevelFields.includes(funName);
}).forEach(function (funName) {
throw new Error('collection-method not allowed because fieldname is in the schema ' + funName);
});
collection = new RxCollection(database, name, schema, pouchSettings, migrationStrategies, methods, attachments);
_context11.next = 15;
return collection.prepare();
case 15:
// ORM add statics
Object.entries(statics).forEach(function (entry) {
var fun = entry.pop();
var funName = entry.pop();
collection.__defineGetter__(funName, function () {
return fun.bind(collection);
});
});
if (!autoMigrate) {
_context11.next = 19;
break;
}
_context11.next = 19;
return collection.migratePromise();
case 19:
(0, _hooks.runPluginHooks)('createRxCollection', collection);
return _context11.abrupt('return', collection);
case 21:
case 'end':
return _context11.stop();
}
}
}, _callee11, this);
}));
return function create(_x22) {
return _ref12.apply(this, arguments);
};
}();
exports.properties = properties;
exports.isInstanceOf = isInstanceOf;
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _rxDocument = require('./rx-document');
var _rxDocument2 = _interopRequireDefault(_rxDocument);
var _rxQuery = require('./rx-query');
var _rxQuery2 = _interopRequireDefault(_rxQuery);
var _rxChangeEvent = require('./rx-change-event');
var _rxChangeEvent2 = _interopRequireDefault(_rxChangeEvent);
var _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
var _dataMigrator = require('./data-migrator');
var _dataMigrator2 = _interopRequireDefault(_dataMigrator);
var _crypter = require('./crypter');
var _crypter2 = _interopRequireDefault(_crypter);
var _docCache = require('./doc-cache');
var _docCache2 = _interopRequireDefault(_docCache);
var _queryCache = require('./query-cache');
var _queryCache2 = _interopRequireDefault(_queryCache);
var _changeEventBuffer = require('./change-event-buffer');
var _changeEventBuffer2 = _interopRequireDefault(_changeEventBuffer);
var _overwritable = require('./overwritable');
var _overwritable2 = _interopRequireDefault(_overwritable);
var _hooks = require('./hooks');
var _rxSchema = require('./rx-schema');
var _rxSchema2 = _interopRequireDefault(_rxSchema);
var _rxDatabase = require('./rx-database');
var _rxDatabase2 = _interopRequireDefault(_rxDatabase);
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 HOOKS_WHEN = ['pre', 'post'];
var HOOKS_KEYS = ['insert', 'save', 'remove', 'create'];
var RxCollection = exports.RxCollection = function () {
function RxCollection(database, name, schema) {
var pouchSettings = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var migrationStrategies = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
var _this = this;
var methods = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
var attachments = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {};
(0, _classCallCheck3['default'])(this, RxCollection);
this._isInMemory = false;
this.destroyed = false;
this.database = database;
this.name = name;
this.schema = schema;
this._migrationStrategies = migrationStrategies;
this._pouchSettings = pouchSettings;
this._methods = methods; // orm of documents
this._attachments = attachments; // orm of attachments
this._atomicUpsertLocks = {};
this._docCache = _docCache2['default'].create();
this._queryCache = _queryCache2['default'].create();
// defaults
this.synced = false;
this.hooks = {};
this._subs = [];
this._repStates = [];
this.pouch = null; // this is needed to preserve this name
// set HOOKS-functions dynamically
HOOKS_KEYS.forEach(function (key) {
HOOKS_WHEN.map(function (when) {
var fnName = when + util.ucfirst(key);
_this[fnName] = function (fun, parallel) {
return _this.addHook(when, key, fun, parallel);
};
});
});
}
(0, _createClass3['default'])(RxCollection, [{
key: 'prepare',
value: function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
var _this2 = this;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
this._dataMigrator = _dataMigrator2['default'].create(this, this._migrationStrategies);
this._crypter = _crypter2['default'].create(this.database.password, this.schema);
this.pouch = this.database._spawnPouchDB(this.name, this.schema.version, this._pouchSettings);
// ensure that we wait until db is useable
_context.next = 5;
return this.database.lockedRun(function () {
return _this2.pouch.info();
});
case 5:
this._observable$ = this.database.$.filter(function (event) {
return event.data.col === _this2.name;
});
this._changeEventBuffer = _changeEventBuffer2['default'].create(this);
// INDEXES
_context.next = 9;
return Promise.all(this.schema.indexes.map(function (indexAr) {
var compressedIdx = indexAr.map(function (key) {
if (!_this2.schema.doKeyCompression()) return key;else return _this2._keyCompressor._transformKey('', '', key.split('.'));
});
return _this2.database.lockedRun(function () {
return _this2.pouch.createIndex({
index: {
fields: compressedIdx
}
});
});
}));
case 9:
this._subs.push(this._observable$.filter(function (cE) {
return !cE.data.isLocal;
}).subscribe(function (cE) {
// when data changes, send it to RxDocument in docCache
var doc = _this2._docCache.get(cE.data.doc);
if (doc) doc._handleChangeEvent(cE);
}));
case 10:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function prepare() {
return _ref.apply(this, arguments);
}
return prepare;
}()
}, {
key: 'migrationNeeded',
/**
* checks if a migration is needed
* @return {boolean}
*/
value: function migrationNeeded() {
if (this.schema.version === 0) return false;
return this._dataMigrator._getOldCollections().then(function (oldCols) {
return oldCols.length > 0;
});
}
/**
* @param {number} [batchSize=10] amount of documents handled in parallel
* @return {Observable} emits the migration-status
*/
}, {
key: 'migrate',
value: function migrate() {
var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
return this._dataMigrator.migrate(batchSize);
}
/**
* does the same thing as .migrate() but returns promise
* @param {number} [batchSize=10] amount of documents handled in parallel
* @return {Promise} resolves when finished
*/
}, {
key: 'migratePromise',
value: function migratePromise() {
var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
return this._dataMigrator.migratePromise(batchSize);
}
/**
* wrappers for Pouch.put/get to handle keycompression etc
*/
}, {
key: '_handleToPouch',
value: function _handleToPouch(docData) {
var data = (0, _clone2['default'])(docData);
data = this._crypter.encrypt(data);
data = this.schema.swapPrimaryToId(data);
if (this.schema.doKeyCompression()) data = this._keyCompressor.compress(data);
return data;
}
}, {
key: '_handleFromPouch',
value: function _handleFromPouch(docData) {
var noDecrypt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var data = (0, _clone2['default'])(docData);
data = this.schema.swapIdToPrimary(data);
if (this.schema.doKeyCompression()) data = this._keyCompressor.decompress(data);
if (noDecrypt) return data;
data = this._crypter.decrypt(data);
return data;
}
/**
* [overwrite description]
* @param {object} obj
* @param {boolean} [overwrite=false] if true, it will overwrite existing document
*/
}, {
key: '_pouchPut',
value: function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2(obj) {
var _this3 = this;
var overwrite = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var ret, exist;
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
obj = this._handleToPouch(obj);
ret = null;
_context2.prev = 2;
_context2.next = 5;
return this.database.lockedRun(function () {
return _this3.pouch.put(obj);
});
case 5:
ret = _context2.sent;
_context2.next = 21;
break;
case 8:
_context2.prev = 8;
_context2.t0 = _context2['catch'](2);
if (!(overwrite && _context2.t0.status === 409)) {
_context2.next = 20;
break;
}
_context2.next = 13;
return this.database.lockedRun(function () {
return _this3.pouch.get(obj._id);
});
case 13:
exist = _context2.sent;
obj._rev = exist._rev;
_context2.next = 17;
return this.database.lockedRun(function () {
return _this3.pouch.put(obj);
});
case 17:
ret = _context2.sent;
_context2.next = 21;
break;
case 20:
throw _context2.t0;
case 21:
return _context2.abrupt('return', ret);
case 22:
case 'end':
return _context2.stop();
}
}
}, _callee2, this, [[2, 8]]);
}));
function _pouchPut(_x9) {
return _ref2.apply(this, arguments);
}
return _pouchPut;
}()
/**
* get document from pouchdb by its _id
* @param {[type]} key [description]
* @return {[type]} [description]
*/
}, {
key: '_pouchGet',
value: function _pouchGet(key) {
var _this4 = this;
return this.pouch.get(key).then(function (doc) {
return _this4._handleFromPouch(doc);
});
}
/**
* wrapps pouch-find
* @param {RxQuery} rxQuery
* @param {?number} limit overwrites the limit
* @param {?boolean} noDecrypt if true, decryption will not be made
* @return {Object[]} array with documents-data
*/
}, {
key: '_pouchFind',
value: function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3(rxQuery, limit) {
var _this5 = this;
var noDecrypt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var compressedQueryJSON, docsCompressed, docs;
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
compressedQueryJSON = rxQuery.keyCompress();
if (limit) compressedQueryJSON.limit = limit;
_context3.next = 4;
return this.database.lockedRun(function () {
return _this5.pouch.find(compressedQueryJSON);
});
case 4:
docsCompressed = _context3.sent;
docs = docsCompressed.docs.map(function (doc) {
return _this5._handleFromPouch(doc, noDecrypt);
});
return _context3.abrupt('return', docs);
case 7:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function _pouchFind(_x11, _x12) {
return _ref3.apply(this, arguments);
}
return _pouchFind;
}()
/**
* assigns the ORM-methods to the RxDocument
* @param {RxDocument} doc
*/
}, {
key: '_assignMethodsToDocument',
value: function _assignMethodsToDocument(doc) {
Object.entries(this._methods).forEach(function (entry) {
var funName = entry[0];
var fun = entry[1];
doc.__defineGetter__(funName, function () {
return fun.bind(doc);
});
});
}
/**
* create a RxDocument-instance from the jsonData
* @param {Object} json documentData
* @return {Promise}
*/
}, {
key: '_createDocument',
value: function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4(json) {
var id, cacheDoc, doc;
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
// return from cache if exsists
id = json[this.schema.primaryPath];
cacheDoc = this._docCache.get(id);
if (!cacheDoc) {
_context4.next = 4;
break;
}
return _context4.abrupt('return', cacheDoc);
case 4:
doc = _rxDocument2['default'].create(this, json);
this._assignMethodsToDocument(doc);
this._docCache.set(id, doc);
this._runHooksSync('post', 'create', doc);
return _context4.abrupt('return', doc);
case 9:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function _createDocument(_x13) {
return _ref4.apply(this, arguments);
}
return _createDocument;
}()
/**
* create RxDocument from the docs-array
* @return {Promise} documents
*/
}, {
key: '_createDocuments',
value: function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5(docsJSON) {
var _this6 = this;
return _regenerator2['default'].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
return _context5.abrupt('return', Promise.all(docsJSON.map(function (json) {
return _this6._createDocument(json);
})));
case 1:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function _createDocuments(_x14) {
return _ref5.apply(this, arguments);
}
return _createDocuments;
}()
/**
* returns observable
*/
}, {
key: '$emit',
value: function $emit(changeEvent) {
return this.database.$emit(changeEvent);
}
/**
* @param {Object|RxDocument} json data or RxDocument if temporary
* @param {RxDocument} doc which was created
* @return {Promise}
*/
}, {
key: 'insert',
value: function () {
var _ref6 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee6(json) {
var tempDoc, insertResult, newDoc, emitEvent;
return _regenerator2['default'].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
// inserting a temporary-document
tempDoc = null;
if (!_rxDocument2['default'].isInstanceOf(json)) {
_context6.next = 6;
break;
}
tempDoc = json;
if (json._isTemporary) {
_context6.next = 5;
break;
}
throw new Error('You cannot insert an existing document');
case 5:
json = json.toJSON();
case 6:
json = (0, _clone2['default'])(json);
json = this.schema.fillObjectWithDefaults(json);
if (!json._id) {
_context6.next = 10;
break;
}
throw new Error('do not provide ._id, it will be generated');
case 10:
// fill _id
if (this.schema.primaryPath === '_id' && !json._id) json._id = util.generateId();
_context6.next = 13;
return this._runHooks('pre', 'insert', json);
case 13:
this.schema.validate(json);
_context6.next = 16;
return this._pouchPut(json);
case 16:
insertResult = _context6.sent;
json[this.schema.primaryPath] = insertResult.id;
json._rev = insertResult.rev;
newDoc = tempDoc;
if (!tempDoc) {
_context6.next = 24;
break;
}
tempDoc._data = json;
_context6.next = 27;
break;
case 24:
_context6.next = 26;
return this._createDocument(json);
case 26:
newDoc = _context6.sent;
case 27:
_context6.next = 29;
return this._runHooks('post', 'insert', newDoc);
case 29:
// event
emitEvent = _rxChangeEvent2['default'].create('INSERT', this.database, this, newDoc, json);
this.$emit(emitEvent);
return _context6.abrupt('return', newDoc);
case 32:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
function insert(_x15) {
return _ref6.apply(this, arguments);
}
return insert;
}()
/**
* same as insert but overwrites existing document with same primary
*/
}, {
key: 'upsert',
value: function () {
var _ref7 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee7(json) {
var primary, existing, newDoc;
return _regenerator2['default'].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
json = (0, _clone2['default'])(json);
primary = json[this.schema.primaryPath];
if (primary) {
_context7.next = 4;
break;
}
throw _rxError2['default'].newRxError('RxCollection.upsert() does not work without primary', {
primaryPath: this.schema.primaryPath,
data: json
});
case 4:
_context7.next = 6;
return this.findOne(primary).exec();
case 6:
existing = _context7.sent;
if (!existing) {
_context7.next = 15;
break;
}
json._rev = existing._rev;
existing._data = json;
_context7.next = 12;
return existing.save();
case 12:
return _context7.abrupt('return', existing);
case 15:
_context7.next = 17;
return this.insert(json);
case 17:
newDoc = _context7.sent;
return _context7.abrupt('return', newDoc);
case 19:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
function upsert(_x16) {
return _ref7.apply(this, arguments);
}
return upsert;
}()
/**
* ensures that the given document exists
* @param {string} primary
* @param {any} json
* @return {Promise} promise that resolves when finished
*/
}, {
key: '_atomicUpsertEnsureRxDocumentExists',
value: function _atomicUpsertEnsureRxDocumentExists(primary, json) {
var _this7 = this;
return this.findOne(primary).exec().then(function (doc) {
if (!doc) return _this7.insert(json);
});
}
/**
* upserts to a RxDocument, uses atomicUpdate if document already exists
* @param {object} json
* @return {Promise}
*/
}, {
key: 'atomicUpsert',
value: function atomicUpsert(json) {
var _this8 = this;
json = (0, _clone2['default'])(json);
var primary = json[this.schema.primaryPath];
if (!primary) throw new Error('RxCollection.atomicUpsert() does not work without primary');
// ensure that it wont try 2 parallel inserts
if (!this._atomicUpsertLocks[primary]) this._atomicUpsertLocks[primary] = this._atomicUpsertEnsureRxDocumentExists(primary, json);
return this._atomicUpsertLocks[primary].then(function () {
return _this8.findOne(primary).exec();
}).then(function (doc) {
return doc.atomicUpdate(function (innerDoc) {
json._rev = innerDoc._rev;
innerDoc._data = json;
});
});
}
/**
* takes a mongoDB-query-object and returns the documents
* @param {object} queryObj
* @return {RxDocument[]} found documents
*/
}, {
key: 'find',
value: function find(queryObj) {
if (typeof queryObj === 'string') throw new Error('if you want to search by _id, use .findOne(_id)');
var query = _rxQuery2['default'].create('find', queryObj, this);
return query;
}
}, {
key: 'findOne',
value: function findOne(queryObj) {
var query = void 0;
if (typeof queryObj === 'string') {
query = _rxQuery2['default'].create('findOne', {
_id: queryObj
}, this);
} else query = _rxQuery2['default'].create('findOne', queryObj, this);
if (typeof queryObj === 'number' || Array.isArray(queryObj)) throw new TypeError('.findOne() needs a queryObject or string');
return query;
}
/**
* export to json
* @param {boolean} decrypted if true, all encrypted values will be decrypted
*/
}, {
key: 'dump',
value: function dump() {
throw _rxError2['default'].pluginMissing('json-dump');
}
/**
* imports the json-data into the collection
* @param {Array} exportedJSON should be an array of raw-data
*/
}, {
key: 'importDump',
value: function () {
var _ref8 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee8() {
return _regenerator2['default'].wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
throw _rxError2['default'].pluginMissing('json-dump');
case 1:
case 'end':
return _context8.stop();
}
}
}, _callee8, this);
}));
function importDump() {
return _ref8.apply(this, arguments);
}
return importDump;
}()
/**
* waits for external changes to the database
* and ensures they are emitted to the internal RxChangeEvent-Stream
* TODO this can be removed by listening to the pull-change-events of the RxReplicationState
*/
}, {
key: 'watchForChanges',
value: function watchForChanges() {
throw _rxError2['default'].pluginMissing('replication');
}
/**
* sync with another database
*/
}, {
key: 'sync',
value: function sync() {
throw _rxError2['default'].pluginMissing('replication');
}
/**
* Create a replicated in-memory-collection
*/
}, {
key: 'inMemory',
value: function inMemory() {
throw _rxError2['default'].pluginMissing('in-memory');
}
/**
* HOOKS
*/
}, {
key: 'addHook',
value: function addHook(when, key, fun) {
var parallel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
if (typeof fun !== 'function') throw new TypeError(key + '-hook must be a function');
if (!HOOKS_WHEN.includes(when)) throw new TypeError('hooks-when not known');
if (!HOOKS_KEYS.includes(key)) throw new Error('hook-name ' + key + 'not known');
if (when === 'post' && key === 'create' && parallel === true) throw new Error('.postCreate-hooks cannot be async');
var runName = parallel ? 'parallel' : 'series';
this.hooks[key] = this.hooks[key] || {};
this.hooks[key][when] = this.hooks[key][when] || {
series: [],
parallel: []
};
this.hooks[key][when][runName].push(fun);
}
}, {
key: 'getHooks',
value: function getHooks(when, key) {
try {
return this.hooks[key][when];
} catch (e) {
return {
series: [],
parallel: []
};
}
}
}, {
key: '_runHooks',
value: function () {
var _ref9 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee9(when, key, doc) {
var hooks, i;
return _regenerator2['default'].wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
hooks = this.getHooks(when, key);
if (hooks) {
_context9.next = 3;
break;
}
return _context9.abrupt('return');
case 3:
i = 0;
case 4:
if (!(i < hooks.series.length)) {
_context9.next = 10;
break;
}
_context9.next = 7;
return hooks.series[i](doc);
case 7:
i++;
_context9.next = 4;
break;
case 10:
_context9.next = 12;
return Promise.all(hooks.parallel.map(function (hook) {
return hook(doc);
}));
case 12:
case 'end':
return _context9.stop();
}
}
}, _callee9, this);
}));
function _runHooks(_x18, _x19, _x20) {
return _ref9.apply(this, arguments);
}
return _runHooks;
}()
/**
* does the same as ._runHooks() but with non-async-functions
*/
}, {
key: '_runHooksSync',
value: function _runHooksSync(when, key, doc) {
var hooks = this.getHooks(when, key);
if (!hooks) return;
hooks.series.forEach(function (hook) {
return hook(doc);
});
}
/**
* creates a temporaryDocument which can be saved later
* @param {Object} docData
* @return {RxDocument}
*/
}, {
key: 'newDocument',
value: function newDocument() {
var docData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
docData = this.schema.fillObjectWithDefaults(docData);
var doc = _rxDocument2['default'].create(this, docData);
doc._isTemporary = true;
this._assignMethodsToDocument(doc);
this._runHooksSync('post', 'create', doc);
return doc;
}
/**
* returns a promise that is resolved when the collection gets destroyed
* @return {Promise}
*/
}, {
key: 'destroy',
value: function () {
var _ref10 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee10() {
return _regenerator2['default'].wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (!this.destroyed) {
_context10.next = 2;
break;
}
return _context10.abrupt('return');
case 2:
this._onDestroyCall && this._onDestroyCall();
this._subs.forEach(function (sub) {
return sub.unsubscribe();
});
this._changeEventBuffer && this._changeEventBuffer.destroy();
this._queryCache.destroy();
this._repStates.forEach(function (sync) {
return sync.cancel();
});
delete this.database.collections[this.name];
this.destroyed = true;
case 9:
case 'end':
return _context10.stop();
}
}
}, _callee10, this);
}));
function destroy() {
return _ref10.apply(this, arguments);
}
return destroy;
}()
/**
* remove all data
* @return {Promise}
*/
}, {
key: 'remove',
value: function remove() {
return this.database.removeCollection(this.name);
}
}, {
key: '_keyCompressor',
get: function get() {
if (!this.__keyCompressor) this.__keyCompressor = _overwritable2['default'].createKeyCompressor(this.schema);
return this.__keyCompressor;
}
}, {
key: '$',
get: function get() {
return this._observable$;
}
}, {
key: 'onDestroy',
get: function get() {
var _this9 = this;
if (!this._onDestroy) this._onDestroy = new Promise(function (res) {
return _this9._onDestroyCall = res;
});
return this._onDestroy;
}
}]);
return RxCollection;
}();
/**
* checks if the migrationStrategies are ok, throws if not
* @param {RxSchema} schema
* @param {Object} migrationStrategies
* @throws {Error|TypeError} if not ok
* @return {boolean}
*/
var checkMigrationStrategies = function checkMigrationStrategies(schema, migrationStrategies) {
// migrationStrategies must be object not array
if ((typeof migrationStrategies === 'undefined' ? 'undefined' : (0, _typeof3['default'])(migrationStrategies)) !== 'object' || Array.isArray(migrationStrategies)) throw new TypeError('migrationStrategies must be an object');
// for every previousVersion there must be strategy
if (schema.previousVersions.length !== Object.keys(migrationStrategies).length) {
throw _rxError2['default'].newRxError('A migrationStrategy is missing or too much', {
have: Object.keys(migrationStrategies),
should: schema.previousVersions
});
}
// every strategy must have number as property and be a function
schema.previousVersions.map(function (vNr) {
return {
v: vNr,
s: migrationStrategies[vNr + 1 + '']
};
}).filter(function (strat) {
return typeof strat.s !== 'function';
}).forEach(function (strat) {
throw new TypeError('migrationStrategy(v' + strat.v + ') must be a function; is : ' + (typeof strat === 'undefined' ? 'undefined' : (0, _typeof3['default'])(strat)));
});
return true;
};
/**
* returns all possible properties of a RxCollection-instance
* @return {string[]} property-names
*/
var _properties = null;
function properties() {
if (!_properties) {
var pseudoInstance = new RxCollection();
var ownProperties = Object.getOwnPropertyNames(pseudoInstance);
var prototypeProperties = Object.getOwnPropertyNames(Object.getPrototypeOf(pseudoInstance));
_properties = [].concat((0, _toConsumableArray3['default'])(ownProperties), (0, _toConsumableArray3['default'])(prototypeProperties));
}
return _properties;
}
/**
* checks if the given static methods are allowed
* @param {{}} statics [description]
* @throws if not allowed
*/
var checkOrmMethods = function checkOrmMethods(statics) {
Object.entries(statics).forEach(function (entry) {
if (typeof entry[0] !== 'string') throw new TypeError('given static method-name (' + entry[0] + ') is not a string');
if (entry[0].startsWith('_')) throw new TypeError('static method-names cannot start with underscore _ (' + entry[0] + ')');
if (typeof entry[1] !== 'function') throw new TypeError('given static method (' + entry[0] + ') is not a function but ' + (0, _typeof3['default'])(entry[1]));
if (properties().includes(entry[0]) || _rxDocument2['default'].properties().includes(entry[0])) throw new Error('statics-name not allowed: ' + entry[0]);
});
};function isInstanceOf(obj) {
return obj instanceof RxCollection;
}
exports['default'] = {
create: create,
properties: properties,
isInstanceOf: isInstanceOf,
RxCollection: RxCollection
};
},{"./change-event-buffer":2,"./crypter":4,"./data-migrator":5,"./doc-cache":6,"./hooks":7,"./overwritable":11,"./query-cache":26,"./rx-change-event":29,"./rx-database":31,"./rx-document":32,"./rx-error":33,"./rx-query":34,"./rx-schema":35,"./util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/toConsumableArray":55,"babel-runtime/helpers/typeof":56,"babel-runtime/regenerator":57,"clone":63}],31:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RxSchema = exports.checkAdapter = exports.removeDatabase = exports.create = exports.RxDatabase = undefined;
var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
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 _ref8 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee7(_ref7) {
var name = _ref7.name,
adapter = _ref7.adapter,
password = _ref7.password,
_ref7$multiInstance = _ref7.multiInstance,
multiInstance = _ref7$multiInstance === undefined ? true : _ref7$multiInstance,
_ref7$ignoreDuplicate = _ref7.ignoreDuplicate,
ignoreDuplicate = _ref7$ignoreDuplicate === undefined ? false : _ref7$ignoreDuplicate;
var db;
return _regenerator2['default'].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
util.validateCouchDBString(name);
// check if pouchdb-adapter
if (!(typeof adapter === 'string')) {
_context7.next = 6;
break;
}
if (!(!_pouchDb2['default'].adapters || !_pouchDb2['default'].adapters[adapter])) {
_context7.next = 4;
break;
}
throw new Error('Adapter ' + adapter + ' not added.\n Use RxDB.plugin(require(\'pouchdb-adapter-' + adapter + '\');');
case 4:
_context7.next = 9;
break;
case 6:
util.isLevelDown(adapter);
if (!(!_pouchDb2['default'].adapters || !_pouchDb2['default'].adapters.leveldb)) {
_context7.next = 9;
break;
}
throw new Error('To use leveldown-adapters, you have to add the leveldb-plugin.\n Use RxDB.plugin(require(\'pouchdb-adapter-leveldb\'));');
case 9:
if (password) _overwritable2['default'].validatePassword(password);
// check if combination already used
if (!ignoreDuplicate) _isNameAdapterUsed(name, adapter);
// add to used_map
if (!USED_COMBINATIONS[name]) USED_COMBINATIONS[name] = [];
USED_COMBINATIONS[name].push(adapter);
db = new RxDatabase(name, adapter, password, multiInstance);
_context7.next = 16;
return db.prepare();
case 16:
(0, _hooks.runPluginHooks)('createRxDatabase', db);
return _context7.abrupt('return', db);
case 18:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
return function create(_x5) {
return _ref8.apply(this, arguments);
};
}();
var removeDatabase = exports.removeDatabase = function () {
var _ref9 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee8(databaseName, adapter) {
var adminPouch, socketPouch, collectionsPouch, collectionsData;
return _regenerator2['default'].wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
adminPouch = _internalAdminPouch(databaseName, adapter);
socketPouch = _spawnPouchDB2(databaseName, adapter, '_socket', 0);
collectionsPouch = _internalCollectionsPouch(databaseName, adapter);
_context8.next = 5;
return collectionsPouch.allDocs({
include_docs: true
});
case 5:
collectionsData = _context8.sent;
// remove collections
Promise.all(collectionsData.rows.map(function (colDoc) {
return colDoc.id;
}).map(function (id) {
var split = id.split('-');
var name = split[0];
var version = parseInt(split[1], 10);
var pouch = _spawnPouchDB2(databaseName, adapter, name, version);
return pouch.destroy();
}));
// remove internals
_context8.next = 9;
return Promise.all([collectionsPouch.destroy(), adminPouch.destroy(), socketPouch.destroy()]);
case 9:
case 'end':
return _context8.stop();
}
}
}, _callee8, this);
}));
return function removeDatabase(_x7, _x8) {
return _ref9.apply(this, arguments);
};
}();
/**
* check is the given adapter can be used
*/
var checkAdapter = exports.checkAdapter = function () {
var _ref10 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee9(adapter) {
return _regenerator2['default'].wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
_context9.next = 2;
return _overwritable2['default'].checkAdapter(adapter);
case 2:
return _context9.abrupt('return', _context9.sent);
case 3:
case 'end':
return _context9.stop();
}
}
}, _callee9, this);
}));
return function checkAdapter(_x9) {
return _ref10.apply(this, arguments);
};
}();
exports.properties = properties;
exports.isInstanceOf = isInstanceOf;
var _randomToken = require('random-token');
var _randomToken2 = _interopRequireDefault(_randomToken);
var _customIdleQueue = require('custom-idle-queue');
var _customIdleQueue2 = _interopRequireDefault(_customIdleQueue);
var _pouchDb = require('./pouch-db');
var _pouchDb2 = _interopRequireDefault(_pouchDb);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
var _rxCollection = require('./rx-collection');
var _rxCollection2 = _interopRequireDefault(_rxCollection);
var _rxSchema = require('./rx-schema');
var _rxSchema2 = _interopRequireDefault(_rxSchema);
var _rxChangeEvent = require('./rx-change-event');
var _rxChangeEvent2 = _interopRequireDefault(_rxChangeEvent);
var _socket = require('./socket');
var _socket2 = _interopRequireDefault(_socket);
var _overwritable = require('./overwritable');
var _overwritable2 = _interopRequireDefault(_overwritable);
var _hooks = require('./hooks');
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 }; }
/**
* stores the combinations
* of used database-names with their adapters
* so we can throw when the same database is created more then once
* @type {Object} map with {dbName -> array}
*/
var USED_COMBINATIONS = {};
var RxDatabase = exports.RxDatabase = function () {
function RxDatabase(name, adapter, password, multiInstance) {
(0, _classCallCheck3['default'])(this, RxDatabase);
this.name = name;
this.adapter = adapter;
this.password = password;
this.multiInstance = multiInstance;
this.idleQueue = new _customIdleQueue2['default']();
this.token = (0, _randomToken2['default'])(10);
this._subs = [];
this.destroyed = false;
// cache for collection-objects
this.collections = {};
// rx
this.subject = new util.Rx.Subject();
this.observable$ = this.subject.asObservable().filter(function (cEvent) {
return _rxChangeEvent2['default'].isInstanceOf(cEvent);
});
}
(0, _createClass3['default'])(RxDatabase, [{
key: 'prepare',
/**
* do the async things for this database
*/
value: function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
var _this = this;
var pwHashDoc;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!this.password) {
_context.next = 22;
break;
}
_context.next = 3;
return this.lockedRun(function () {
return _this._adminPouch.info();
});
case 3:
pwHashDoc = null;
_context.prev = 4;
_context.next = 7;
return this.lockedRun(function () {
return _this._adminPouch.get('_local/pwHash');
});
case 7:
pwHashDoc = _context.sent;
_context.next = 12;
break;
case 10:
_context.prev = 10;
_context.t0 = _context['catch'](4);
case 12:
if (pwHashDoc) {
_context.next = 20;
break;
}
_context.prev = 13;
_context.next = 16;
return this.lockedRun(function () {
return _this._adminPouch.put({
_id: '_local/pwHash',
value: util.hash(_this.password)
});
});
case 16:
_context.next = 20;
break;
case 18:
_context.prev = 18;
_context.t1 = _context['catch'](13);
case 20:
if (!(pwHashDoc && this.password && util.hash(this.password) !== pwHashDoc.value)) {
_context.next = 22;
break;
}
throw new Error('another instance on this adapter has a different password');
case 22:
if (!this.multiInstance) {
_context.next = 27;
break;
}
_context.next = 25;
return _socket2['default'].create(this);
case 25:
this.socket = _context.sent;
// TODO only subscribe when sth is listening to the event-chain
this._subs.push(this.socket.messages$.subscribe(function (cE) {
return _this.$emit(cE);
}));
case 27:
case 'end':
return _context.stop();
}
}
}, _callee, this, [[4, 10], [13, 18]]);
}));
function prepare() {
return _ref.apply(this, arguments);
}
return prepare;
}()
}, {
key: '_spawnPouchDB',
/**
* spawns a new pouch-instance
* @param {string} collectionName
* @param {string} schemaVersion
* @param {Object} [pouchSettings={}] pouchSettings
* @type {Object}
*/
value: function _spawnPouchDB(collectionName, schemaVersion) {
var pouchSettings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
return _spawnPouchDB2(this.name, this.adapter, collectionName, schemaVersion, pouchSettings);
}
}, {
key: 'waitForLeadership',
value: function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (this.multiInstance) {
_context2.next = 2;
break;
}
return _context2.abrupt('return', true);
case 2:
return _context2.abrupt('return', this.leaderElector.waitForLeadership());
case 3:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function waitForLeadership() {
return _ref2.apply(this, arguments);
}
return waitForLeadership;
}()
/**
* writes the changeEvent to the socket
* @param {RxChangeEvent} changeEvent
* @return {Promise}
*/
}, {
key: 'writeToSocket',
value: function writeToSocket(changeEvent) {
if (this.multiInstance && !changeEvent.isIntern() && this.socket) {
return this.socket.write(changeEvent).then(function () {
return true;
});
} else return Promise.resolve(false);
}
/**
* throw a new event into the event-cicle
*/
}, {
key: '$emit',
value: function $emit(changeEvent) {
if (!changeEvent) return;
// throw in own cycle
this.subject.next(changeEvent);
// write to socket if event was created by self
if (changeEvent.data.it === this.token) this.writeToSocket(changeEvent);
}
/**
* @return {Observable} observable
*/
}, {
key: '_collectionNamePrimary',
/**
* returns the primary for a given collection-data
* used in the internal pouchdb-instances
* @param {string} name
* @param {RxSchema} schema
*/
value: function _collectionNamePrimary(name, schema) {
return name + '-' + schema.version;
}
/**
* removes the collection-doc from this._collectionsPouch
* @return {Promise}
*/
}, {
key: 'removeCollectionDoc',
value: function removeCollectionDoc(name, schema) {
var _this2 = this;
var docId = this._collectionNamePrimary(name, schema);
return this._collectionsPouch.get(docId).then(function (doc) {
return _this2.lockedRun(function () {
return _this2._collectionsPouch.remove(doc);
});
});
}
/**
* removes all internal docs of a given collection
* @param {string} collectionName
* @return {Promise} resolves all known collection-versions
*/
}, {
key: '_removeAllOfCollection',
value: function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3(collectionName) {
var _this3 = this;
var data, relevantDocs;
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.lockedRun(function () {
return _this3._collectionsPouch.allDocs({
include_docs: true
});
});
case 2:
data = _context3.sent;
relevantDocs = data.rows.map(function (row) {
return row.doc;
}).filter(function (doc) {
var name = doc._id.split('-')[0];
return name === collectionName;
});
_context3.next = 6;
return Promise.all(relevantDocs.map(function (doc) {
return _this3.lockedRun(function () {
return _this3._collectionsPouch.remove(doc);
});
}));
case 6:
return _context3.abrupt('return', relevantDocs.map(function (doc) {
return doc.version;
}));
case 7:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function _removeAllOfCollection(_x2) {
return _ref3.apply(this, arguments);
}
return _removeAllOfCollection;
}()
/**
* create or fetch a collection
* @param {{name: string, schema: Object, pouchSettings = {}, migrationStrategies = {}}} args
* @return {Collection}
*/
}, {
key: 'collection',
value: function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4(args) {
var _this4 = this;
var internalPrimary, schemaHash, collectionDoc, collection, cEvent;
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
args.database = this;
if (!(args.name.charAt(0) === '_')) {
_context4.next = 3;
break;
}
throw new Error('collection(' + args.name + '): collection-names cannot start with underscore _');
case 3:
if (!this.collections[args.name]) {
_context4.next = 5;
break;
}
throw new Error('collection(' + args.name + ') already exists. use myDatabase.' + args.name + ' to get it');
case 5:
if (args.schema) {
_context4.next = 7;
break;
}
throw new Error('collection(' + args.name + '): schema is missing');
case 7:
if (!_rxSchema2['default'].isInstanceOf(args.schema)) args.schema = _rxSchema2['default'].create(args.schema);
internalPrimary = this._collectionNamePrimary(args.name, args.schema);
// check unallowed collection-names
if (!properties().includes(args.name)) {
_context4.next = 11;
break;
}
throw new Error('Collection-name ' + args.name + ' not allowed');
case 11:
// check schemaHash
schemaHash = args.schema.hash;
collectionDoc = null;
_context4.prev = 13;
_context4.next = 16;
return this.lockedRun(function () {
return _this4._collectionsPouch.get(internalPrimary);
});
case 16:
collectionDoc = _context4.sent;
_context4.next = 21;
break;
case 19:
_context4.prev = 19;
_context4.t0 = _context4['catch'](13);
case 21:
if (!(collectionDoc && collectionDoc.schemaHash !== schemaHash)) {
_context4.next = 23;
break;
}
throw new Error('collection(' + args.name + '): another instance created this collection with a different schema');
case 23:
_context4.next = 25;
return _rxCollection2['default'].create(args);
case 25:
collection = _context4.sent;
if (!(Object.keys(collection.schema.encryptedPaths).length > 0 && !this.password)) {
_context4.next = 28;
break;
}
throw new Error('collection(' + args.name + '): schema encrypted but no password given');
case 28:
if (collectionDoc) {
_context4.next = 36;
break;
}
_context4.prev = 29;
_context4.next = 32;
return this.lockedRun(function () {
return _this4._collectionsPouch.put({
_id: internalPrimary,
schemaHash: schemaHash,
schema: collection.schema.normalized,
version: collection.schema.version
});
});
case 32:
_context4.next = 36;
break;
case 34:
_context4.prev = 34;
_context4.t1 = _context4['catch'](29);
case 36:
cEvent = _rxChangeEvent2['default'].create('RxDatabase.collection', this);
cEvent.data.v = collection.name;
cEvent.data.col = '_collections';
this.$emit(cEvent);
this.collections[args.name] = collection;
this.__defineGetter__(args.name, function () {
return _this4.collections[args.name];
});
return _context4.abrupt('return', collection);
case 43:
case 'end':
return _context4.stop();
}
}
}, _callee4, this, [[13, 19], [29, 34]]);
}));
function collection(_x3) {
return _ref4.apply(this, arguments);
}
return collection;
}()
/**
* delete all data of the collection and its previous versions
* @param {string} collectionName
* @return {Promise}
*/
}, {
key: 'removeCollection',
value: function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5(collectionName) {
var _this5 = this;
var knownVersions, pouches;
return _regenerator2['default'].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (!this.collections[collectionName]) {
_context5.next = 3;
break;
}
_context5.next = 3;
return this.collections[collectionName].destroy();
case 3:
_context5.next = 5;
return this._removeAllOfCollection(collectionName);
case 5:
knownVersions = _context5.sent;
// get all relevant pouchdb-instances
pouches = knownVersions.map(function (v) {
return _this5._spawnPouchDB(collectionName, v);
});
// remove documents
return _context5.abrupt('return', Promise.all(pouches.map(function (pouch) {
return _this5.lockedRun(function () {
return pouch.destroy();
});
})));
case 8:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function removeCollection(_x4) {
return _ref5.apply(this, arguments);
}
return removeCollection;
}()
/**
* runs the given function between idleQueue-locking
* @return {any}
*/
}, {
key: 'lockedRun',
value: function lockedRun(fun) {
return this.idleQueue.wrapCall(fun);
}
}, {
key: 'requestIdlePromise',
value: function requestIdlePromise() {
return this.idleQueue.requestIdlePromise();
}
/**
* export to json
* @param {boolean} decrypted
* @param {?string[]} collections array with collectionNames or null if all
*/
}, {
key: 'dump',
value: function dump() {
throw _rxError2['default'].pluginMissing('json-dump');
}
/**
* import json
* @param {Object} dump
*/
}, {
key: 'importDump',
value: function importDump() {
throw _rxError2['default'].pluginMissing('json-dump');
}
/**
* destroys the database-instance and all collections
* @return {Promise}
*/
}, {
key: 'destroy',
value: function () {
var _ref6 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee6() {
var _this6 = this;
return _regenerator2['default'].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!this.destroyed) {
_context6.next = 2;
break;
}
return _context6.abrupt('return');
case 2:
this.destroyed = true;
_context6.t0 = this.socket;
if (!_context6.t0) {
_context6.next = 7;
break;
}
_context6.next = 7;
return this.socket.destroy();
case 7:
if (!this._leaderElector) {
_context6.next = 10;
break;
}
_context6.next = 10;
return this._leaderElector.destroy();
case 10:
this._subs.map(function (sub) {
return sub.unsubscribe();
});
// destroy all collections
_context6.next = 13;
return Promise.all(Object.keys(this.collections).map(function (key) {
return _this6.collections[key];
}).map(function (col) {
return col.destroy();
}));
case 13:
// remove combination from USED_COMBINATIONS-map
_removeUsedCombination(this.name, this.adapter);
case 14:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
function destroy() {
return _ref6.apply(this, arguments);
}
return destroy;
}()
/**
* deletes the database and its stored data
* @return {Promise}
*/
}, {
key: 'remove',
value: function remove() {
var _this7 = this;
return this.destroy().then(function () {
return removeDatabase(_this7.name, _this7.adapter);
});
}
}, {
key: '_adminPouch',
get: function get() {
if (!this.__adminPouch) this.__adminPouch = _internalAdminPouch(this.name, this.adapter);
return this.__adminPouch;
}
}, {
key: '_collectionsPouch',
get: function get() {
if (!this.__collectionsPouch) this.__collectionsPouch = _internalCollectionsPouch(this.name, this.adapter);
return this.__collectionsPouch;
}
}, {
key: 'leaderElector',
get: function get() {
if (!this._leaderElector) this._leaderElector = _overwritable2['default'].createLeaderElector(this);
return this._leaderElector;
}
}, {
key: 'isLeader',
get: function get() {
if (!this.multiInstance) return true;
return this.leaderElector.isLeader;
}
}, {
key: '$',
get: function get() {
return this.observable$;
}
}]);
return RxDatabase;
}();
/**
* returns all possible properties of a RxDatabase-instance
* @return {string[]} property-names
*/
var _properties = null;
function properties() {
if (!_properties) {
var pseudoInstance = new RxDatabase();
var ownProperties = Object.getOwnPropertyNames(pseudoInstance);
var prototypeProperties = Object.getOwnPropertyNames(Object.getPrototypeOf(pseudoInstance));
_properties = [].concat((0, _toConsumableArray3['default'])(ownProperties), (0, _toConsumableArray3['default'])(prototypeProperties));
}
return _properties;
}
/**
* checks if an instance with same name and adapter already exists
* @param {string} name
* @param {any} adapter
* @throws {RxError} if used
*/
function _isNameAdapterUsed(name, adapter) {
if (!USED_COMBINATIONS[name]) return false;
var used = false;
USED_COMBINATIONS[name].forEach(function (ad) {
if (ad === adapter) used = true;
});
if (used) {
throw _rxError2['default'].newRxError('RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\n' + 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional', {
name: name,
adapter: adapter,
link: 'https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate'
});
}
}
function _removeUsedCombination(name, adapter) {
if (!USED_COMBINATIONS[name]) return;
var index = USED_COMBINATIONS[name].indexOf(adapter);
USED_COMBINATIONS[name].splice(index, 1);
}
function _spawnPouchDB2(dbName, adapter, collectionName, schemaVersion) {
var pouchSettings = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
var pouchLocation = dbName + '-rxdb-' + schemaVersion + '-' + collectionName;
var pouchDbParameters = {
location: pouchLocation,
adapter: util.adapterObject(adapter),
settings: pouchSettings
};
(0, _hooks.runPluginHooks)('preCreatePouchDb', pouchDbParameters);
return new _pouchDb2['default'](pouchDbParameters.location, pouchDbParameters.adapter, pouchDbParameters.settings);
}
function _internalAdminPouch(name, adapter) {
return _spawnPouchDB2(name, adapter, '_admin', 0, {
auto_compaction: false, // no compaction because this only stores local documents
revs_limit: 1
});
}
function _internalCollectionsPouch(name, adapter) {
return _spawnPouchDB2(name, adapter, '_collections', 0, {
auto_compaction: false, // no compaction because this only stores local documents
revs_limit: 1
});
}
;
function isInstanceOf(obj) {
return obj instanceof RxDatabase;
}
// TODO is this needed?
exports.RxSchema = _rxSchema2['default'];
exports['default'] = {
create: create,
removeDatabase: removeDatabase,
checkAdapter: checkAdapter,
isInstanceOf: isInstanceOf,
RxDatabase: RxDatabase,
RxSchema: _rxSchema2['default']
};
},{"./hooks":7,"./overwritable":11,"./pouch-db":25,"./rx-change-event":29,"./rx-collection":30,"./rx-error":33,"./rx-schema":35,"./socket":36,"./util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/toConsumableArray":55,"babel-runtime/regenerator":57,"custom-idle-queue":492,"random-token":612}],32:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RxDocument = undefined;
var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
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.create = create;
exports.createAr = createAr;
exports.properties = properties;
exports.isInstanceOf = isInstanceOf;
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _objectPath = require('object-path');
var _objectPath2 = _interopRequireDefault(_objectPath);
var _deepEqual = require('deep-equal');
var _deepEqual2 = _interopRequireDefault(_deepEqual);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _rxChangeEvent = require('./rx-change-event');
var _rxChangeEvent2 = _interopRequireDefault(_rxChangeEvent);
var _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
var _hooks = require('./hooks');
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 = exports.RxDocument = function () {
function RxDocument(collection, jsonData) {
(0, _classCallCheck3['default'])(this, RxDocument);
this.collection = collection;
// if true, this is a temporary document
this._isTemporary = false;
// assume that this is always equal to the doc-data in the database
this._dataSync$ = new util.Rx.BehaviorSubject((0, _clone2['default'])(jsonData));
// current doc-data, changes when setting values etc
this._data = (0, _clone2['default'])(jsonData);
// atomic-update-functions that have not run yes
this._atomicUpdates = [];
// resolve-functions to resolve the promises of atomicUpdate
this._atomicUpdatesResolveFunctions = new WeakMap();
// false when _data !== _dataSync
this._synced$ = new util.Rx.BehaviorSubject(true);
this._deleted$ = new util.Rx.BehaviorSubject(false);
}
(0, _createClass3['default'])(RxDocument, [{
key: 'prepare',
value: function prepare() {
// set getter/setter/observable
this._defineGetterSetter(this, '');
}
}, {
key: 'resync',
value: function resync() {
var syncedData = this._dataSync$.getValue();
if (this._synced$.getValue() && (0, _deepEqual2['default'])(syncedData, this._data)) return;else {
this._data = (0, _clone2['default'])(this._dataSync$.getValue());
this._synced$.next(true);
}
}
/**
* returns the observable which emits the plain-data of this document
* @return {Observable}
*/
}, {
key: '_handleChangeEvent',
/**
* @param {ChangeEvent}
*/
value: function _handleChangeEvent(changeEvent) {
if (changeEvent.data.doc !== this.primary) return;
// TODO check if new _rev is higher then current
switch (changeEvent.data.op) {
case 'INSERT':
break;
case 'UPDATE':
var newData = (0, _clone2['default'])(changeEvent.data.v);
var prevSyncData = this._dataSync$.getValue();
var prevData = this._data;
if ((0, _deepEqual2['default'])(prevSyncData, prevData)) {
// document is in sync, overwrite _data
this._data = newData;
if (this._synced$.getValue() !== true) this._synced$.next(true);
} else {
// not in sync, emit to synced$
if (this._synced$.getValue() !== false) this._synced$.next(false);
// overwrite _rev of data
this._data._rev = newData._rev;
}
this._dataSync$.next((0, _clone2['default'])(newData));
break;
case 'REMOVE':
// remove from docCache to assure new upserted RxDocuments will be a new instance
this.collection._docCache['delete'](this.primary);
this._deleted$.next(true);
break;
}
}
/**
* emits the changeEvent to the upper instance (RxCollection)
* @param {RxChangeEvent} changeEvent
*/
}, {
key: '$emit',
value: function $emit(changeEvent) {
return this.collection.$emit(changeEvent);
}
/**
* returns observable of the value of the given path
* @param {string} path
* @return {Observable}
*/
}, {
key: 'get$',
value: function get$(path) {
if (path.includes('.item.')) throw new Error('cannot get observable of in-array fields because order cannot be guessed: ' + path);
if (path === this.primaryPath) throw _rxError2['default'].newRxError('cannot observe primary path');
// final fields cannot be modified and so also not observed
if (this.collection.schema.finalFields.includes(path)) {
throw _rxError2['default'].newRxError('final fields cannot be observed', {
path: path
});
}
var schemaObj = this.collection.schema.getSchemaByObjectPath(path);
if (!schemaObj) throw new Error('cannot observe a non-existed field (' + path + ')');
return this._dataSync$.map(function (data) {
return _objectPath2['default'].get(data, path);
}).distinctUntilChanged().asObservable();
}
/**
* populate the given path
* @param {string} path
* @return {Promise}
*/
}, {
key: 'populate',
value: function populate(path) {
var schemaObj = this.collection.schema.getSchemaByObjectPath(path);
var value = this.get(path);
if (!schemaObj) throw new Error('cannot populate a non-existed field (' + path + ')');
if (!schemaObj.ref) throw new Error('cannot populate because path has no ref (' + path + ')');
var refCollection = this.collection.database.collections[schemaObj.ref];
if (!refCollection) throw new Error('ref-collection (' + schemaObj.ref + ') not in database');
if (schemaObj.type === 'array') return Promise.all(value.map(function (id) {
return refCollection.findOne(id).exec();
}));else return refCollection.findOne(value).exec();
}
/**
* get data by objectPath
* @param {string} objPath
* @return {object} valueObj
*/
}, {
key: 'get',
value: function get(objPath) {
if (!this._data) return undefined;
if (typeof objPath !== 'string') throw new TypeError('RxDocument.get(): objPath must be a string');
var valueObj = _objectPath2['default'].get(this._data, objPath);
valueObj = (0, _clone2['default'])(valueObj);
// direct return if array or non-object
if ((typeof valueObj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(valueObj)) !== 'object' || Array.isArray(valueObj)) return valueObj;
this._defineGetterSetter(valueObj, objPath);
return valueObj;
}
}, {
key: '_defineGetterSetter',
value: function _defineGetterSetter(valueObj) {
var _this = this;
var objPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
if (valueObj === null) return;
var pathProperties = this.collection.schema.getSchemaByObjectPath(objPath);
if (pathProperties.properties) pathProperties = pathProperties.properties;
Object.keys(pathProperties).forEach(function (key) {
var fullPath = util.trimDots(objPath + '.' + key);
// getter - value
valueObj.__defineGetter__(key, function () {
return _this.get(fullPath);
});
// getter - observable$
Object.defineProperty(valueObj, key + '$', {
get: function get() {
return _this.get$(fullPath);
},
enumerable: false,
configurable: false
});
// getter - populate_
Object.defineProperty(valueObj, key + '_', {
get: function get() {
return _this.populate(fullPath);
},
enumerable: false,
configurable: false
});
// setter - value
valueObj.__defineSetter__(key, function (val) {
return _this.set(fullPath, val);
});
});
}
}, {
key: 'toJSON',
value: function toJSON() {
return (0, _clone2['default'])(this._data);
}
/**
* 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');
// primary cannot be modified
if (!this._isTemporary && objPath === this.primaryPath) {
throw new Error('RxDocument.set(): primary-key (' + this.primaryPath + ')\n cannot be modified');
}
// final fields cannot be modified
if (!this._isTemporary && this.collection.schema.finalFields.includes(objPath)) {
throw _rxError2['default'].newRxError('final fields cannot be modified', {
path: objPath,
value: value
});
}
// check if equal
if (Object.is(this.get(objPath), value)) return;
// 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 + '\n when rootPath ' + rootPath + ' not selected');
}
// check schema of changed field
if (!this._isTemporary) this.collection.schema.validate(value, objPath);
_objectPath2['default'].set(this._data, objPath, value);
return this;
}
}, {
key: 'update',
/**
* updates document
* @overwritten by plugin (optinal)
* @param {object} updateObj mongodb-like syntax
*/
value: function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
throw _rxError2['default'].pluginMissing('update');
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function update() {
return _ref.apply(this, arguments);
}
return update;
}()
}, {
key: 'putAttachment',
value: function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
throw _rxError2['default'].pluginMissing('attachments');
case 1:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function putAttachment() {
return _ref2.apply(this, arguments);
}
return putAttachment;
}()
}, {
key: 'getAttachment',
value: function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3() {
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
throw _rxError2['default'].pluginMissing('attachments');
case 1:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function getAttachment() {
return _ref3.apply(this, arguments);
}
return getAttachment;
}()
}, {
key: 'allAttachments',
value: function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4() {
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
throw _rxError2['default'].pluginMissing('attachments');
case 1:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function allAttachments() {
return _ref4.apply(this, arguments);
}
return allAttachments;
}()
}, {
key: 'atomicUpdate',
/**
* [atomicUpdate description]
* @param {[type]} fun [description]
* @return {Promise} [description]
*/
value: function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5(fun) {
var _this2 = this;
var retPromise;
return _regenerator2['default'].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
this._atomicUpdates.push(fun);
retPromise = new Promise(function (resolve, reject) {
_this2._atomicUpdatesResolveFunctions.set(fun, {
resolve: resolve,
reject: reject
});
});
this._runAtomicUpdates();
return _context5.abrupt('return', retPromise);
case 4:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function atomicUpdate(_x2) {
return _ref5.apply(this, arguments);
}
return atomicUpdate;
}()
}, {
key: '_runAtomicUpdates',
value: function () {
var _ref6 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee6() {
var fun;
return _regenerator2['default'].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!this.__runAtomicUpdates_running) {
_context6.next = 4;
break;
}
return _context6.abrupt('return');
case 4:
this.__runAtomicUpdates_running = true;
case 5:
if (!(this._atomicUpdates.length === 0)) {
_context6.next = 8;
break;
}
this.__runAtomicUpdates_running = false;
return _context6.abrupt('return');
case 8:
;
fun = this._atomicUpdates.shift();
_context6.prev = 10;
_context6.next = 13;
return fun(this);
case 13:
_context6.next = 15;
return this.save();
case 15:
_context6.next = 20;
break;
case 17:
_context6.prev = 17;
_context6.t0 = _context6['catch'](10);
this._atomicUpdatesResolveFunctions.get(fun).reject(_context6.t0);
case 20:
this._atomicUpdatesResolveFunctions.get(fun).resolve(this); // resolve promise
this.__runAtomicUpdates_running = false;
this._runAtomicUpdates();
case 23:
case 'end':
return _context6.stop();
}
}
}, _callee6, this, [[10, 17]]);
}));
function _runAtomicUpdates() {
return _ref6.apply(this, arguments);
}
return _runAtomicUpdates;
}()
/**
* save document if its data has changed
* @return {boolean} false if nothing to save
*/
}, {
key: 'save',
value: function () {
var _ref7 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee7() {
var ret, emitValue, changeEvent;
return _regenerator2['default'].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
if (!this._isTemporary) {
_context7.next = 2;
break;
}
return _context7.abrupt('return', this._saveTemporary());
case 2:
if (!this._deleted$.getValue()) {
_context7.next = 4;
break;
}
throw new Error('RxDocument.save(): cant save deleted document');
case 4:
if (!(0, _deepEqual2['default'])(this._data, this._dataSync$.getValue())) {
_context7.next = 7;
break;
}
this._synced$.next(true);
return _context7.abrupt('return', false);
case 7:
_context7.next = 9;
return this.collection._runHooks('pre', 'save', this);
case 9:
this.collection.schema.validate(this._data);
_context7.next = 12;
return this.collection._pouchPut((0, _clone2['default'])(this._data));
case 12:
ret = _context7.sent;
if (ret.ok) {
_context7.next = 15;
break;
}
throw new Error('RxDocument.save(): error ' + JSON.stringify(ret));
case 15:
emitValue = (0, _clone2['default'])(this._data);
emitValue._rev = ret.rev;
this._data = emitValue;
_context7.next = 20;
return this.collection._runHooks('post', 'save', this);
case 20:
// event
this._synced$.next(true);
this._dataSync$.next((0, _clone2['default'])(emitValue));
changeEvent = _rxChangeEvent2['default'].create('UPDATE', this.collection.database, this.collection, this, emitValue);
this.$emit(changeEvent);
return _context7.abrupt('return', true);
case 25:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
function save() {
return _ref7.apply(this, arguments);
}
return save;
}()
/**
* does the same as .save() but for temporary documents
* Saving a temporary doc is basically the same as RxCollection.insert()
* @return {Promise}
*/
}, {
key: '_saveTemporary',
value: function () {
var _ref8 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee8() {
return _regenerator2['default'].wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return this.collection.insert(this);
case 2:
this._isTemporary = false;
this.collection._docCache.set(this.primary, this);
// internal events
this._synced$.next(true);
this._dataSync$.next((0, _clone2['default'])(this._data));
return _context8.abrupt('return', true);
case 7:
case 'end':
return _context8.stop();
}
}
}, _callee8, this);
}));
function _saveTemporary() {
return _ref8.apply(this, arguments);
}
return _saveTemporary;
}()
}, {
key: 'remove',
value: function () {
var _ref9 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee9() {
var _this3 = this;
return _regenerator2['default'].wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
if (!this.deleted) {
_context9.next = 2;
break;
}
throw new Error('RxDocument.remove(): Document is already deleted');
case 2:
_context9.next = 4;
return this.collection._runHooks('pre', 'remove', this);
case 4:
_context9.next = 6;
return this.collection.database.lockedRun(function () {
return _this3.collection.pouch.remove(_this3.primary, _this3._data._rev);
});
case 6:
this.$emit(_rxChangeEvent2['default'].create('REMOVE', this.collection.database, this.collection, this, this._data));
_context9.next = 9;
return this.collection._runHooks('post', 'remove', this);
case 9:
_context9.next = 11;
return util.promiseWait(0);
case 11:
return _context9.abrupt('return');
case 12:
case 'end':
return _context9.stop();
}
}
}, _callee9, this);
}));
function remove() {
return _ref9.apply(this, arguments);
}
return remove;
}()
}, {
key: 'destroy',
value: function destroy() {
throw new Error('RxDocument.destroy() does not exist');
}
}, {
key: 'primaryPath',
get: function get() {
return this.collection.schema.primaryPath;
}
}, {
key: 'primary',
get: function get() {
return this._data[this.primaryPath];
}
}, {
key: 'revision',
get: function get() {
return this._data._rev;
}
}, {
key: 'deleted$',
get: function get() {
return this._deleted$.asObservable();
}
}, {
key: 'deleted',
get: function get() {
return this._deleted$.getValue();
}
}, {
key: 'synced$',
get: function get() {
return this._synced$.asObservable().distinctUntilChanged();
}
}, {
key: 'synced',
get: function get() {
return this._synced$.getValue();
}
}, {
key: '$',
get: function get() {
return this._dataSync$.asObservable();
}
}, {
key: 'allAttachments$',
get: function get() {
throw _rxError2['default'].pluginMissing('attachments');
}
}]);
return RxDocument;
}();
function create(collection, jsonData) {
if (jsonData[collection.schema.primaryPath] && jsonData[collection.schema.primaryPath].startsWith('_design')) return null;
var doc = new RxDocument(collection, jsonData);
doc.prepare();
(0, _hooks.runPluginHooks)('createRxDocument', doc);
return doc;
}
function createAr(collection, jsonDataAr) {
return jsonDataAr.map(function (jsonData) {
return create(collection, jsonData);
}).filter(function (doc) {
return doc !== null;
});
}
/**
* returns all possible properties of a RxDocument
* @return {string[]} property-names
*/
var _properties = void 0;
function properties() {
if (!_properties) {
var reserved = ['deleted', 'synced'];
var pseudoRxDocument = new RxDocument();
var ownProperties = Object.getOwnPropertyNames(pseudoRxDocument);
var prototypeProperties = Object.getOwnPropertyNames(Object.getPrototypeOf(pseudoRxDocument));
_properties = [].concat((0, _toConsumableArray3['default'])(ownProperties), (0, _toConsumableArray3['default'])(prototypeProperties), reserved);
}
return _properties;
}
function isInstanceOf(obj) {
return obj instanceof RxDocument;
}
exports['default'] = {
create: create,
createAr: createAr,
properties: properties,
RxDocument: RxDocument,
isInstanceOf: isInstanceOf
};
},{"./hooks":7,"./rx-change-event":29,"./rx-error":33,"./util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/toConsumableArray":55,"babel-runtime/helpers/typeof":56,"babel-runtime/regenerator":57,"clone":63,"deep-equal":496,"object-path":567}],33:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newRxError = exports.RxError = undefined;
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
exports.pluginMissing = pluginMissing;
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 }; }
/**
* transform an object of parameters to a presentable string
* @param {any} parameters
* @return {string}
*/
var parametersToString = function parametersToString(parameters) {
var ret = '';
if (Object.keys(parameters).length === 0) return ret;
ret += 'Given parameters: {\n';
ret += Object.keys(parameters).map(function (k) {
var paramStr = '[object Object]';
try {
paramStr = JSON.stringify(parameters[k], null, 2);
} catch (e) {}
return k + ':' + paramStr;
}).join('\n');
ret += '}';
return ret;
}; /**
* here we use custom errors with the additional field 'parameters'
*/
var messageForError = function messageForError(message, parameters) {
return 'RxError:' + '\n' + message + '\n' + parametersToString(parameters);
};
var RxError = exports.RxError = function (_Error) {
(0, _inherits3['default'])(RxError, _Error);
function RxError(message) {
var parameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
(0, _classCallCheck3['default'])(this, RxError);
var mes = messageForError(message, parameters);
var _this = (0, _possibleConstructorReturn3['default'])(this, (RxError.__proto__ || Object.getPrototypeOf(RxError)).call(this, mes));
_this.message = mes;
_this.parameters = parameters;
_this.rxdb = true; // tag them as internal
return _this;
}
(0, _createClass3['default'])(RxError, [{
key: 'toString',
value: function toString() {
return this.message;
}
}, {
key: 'name',
get: function get() {
return 'RxError';
}
}]);
return RxError;
}(Error);
;
function pluginMissing(pluginKey) {
return new RxError('You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n - es5-require:\n RxDB.plugin(require(\'rxdb/plugins/' + pluginKey + '\'))\n - es6-import:\n import ' + util.ucfirst(pluginKey) + 'Plugin from \'rxdb/plugins/' + pluginKey + '\';\n RxDB.plugin(' + util.ucfirst(pluginKey) + 'Plugin);\n ', {
pluginKey: pluginKey
});
};
// const errorKeySearchLink = key => 'https://github.com/pubkey/rxdb/search?q=' + key + '+path%3Asrc%2Fmodules';
// const verboseErrorModuleLink = 'https://pubkey.github.io/rxdb/custom-builds.html#verbose-error';
var newRxError = exports.newRxError = function newRxError(message, parameters) {
return new RxError(message, parameters);
};
exports['default'] = {
newRxError: newRxError,
pluginMissing: pluginMissing
};
},{"./util":37,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/inherits":53,"babel-runtime/helpers/possibleConstructorReturn":54}],34:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RxQuery = 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 _defineProperty2 = require('babel-runtime/helpers/defineProperty');
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
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.isInstanceOf = isInstanceOf;
var _deepEqual = require('deep-equal');
var _deepEqual2 = _interopRequireDefault(_deepEqual);
var _mquery = require('./mquery/mquery');
var _mquery2 = _interopRequireDefault(_mquery);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _queryChangeDetector = require('./query-change-detector');
var _queryChangeDetector2 = _interopRequireDefault(_queryChangeDetector);
var _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
var _hooks = require('./hooks');
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 _queryCount = 0;
var newQueryID = function newQueryID() {
return ++_queryCount;
};
var RxQuery = exports.RxQuery = function () {
function RxQuery(op, queryObj, collection) {
(0, _classCallCheck3['default'])(this, RxQuery);
this.op = op;
this.collection = collection;
this.id = newQueryID();
if (!queryObj) queryObj = this._defaultQuery();
this.mquery = new _mquery2['default'](queryObj);
this._queryChangeDetector = _queryChangeDetector2['default'].create(this);
this._resultsData = null;
this._results$ = new util.Rx.BehaviorSubject(null);
this._latestChangeEvent = -1;
this._runningPromise = Promise.resolve(true);
/**
* if this is true, the results-state is not equal to the database
* which means that the query must run against the database again
* @type {Boolean}
*/
this._mustReExec = true;
/**
* counts how often the execution on the whole db was done
* (used for tests and debugging)
* @type {Number}
*/
this._execOverDatabaseCount = 0;
}
(0, _createClass3['default'])(RxQuery, [{
key: '_defaultQuery',
value: function _defaultQuery() {
return (0, _defineProperty3['default'])({}, this.collection.schema.primaryPath, {});
}
// returns a clone of this RxQuery
}, {
key: '_clone',
value: function _clone() {
var cloned = new RxQuery(this.op, this._defaultQuery(), this.collection);
cloned.mquery = this.mquery.clone();
return cloned;
}
/**
* run this query through the QueryCache
* @return {RxQuery} can be this or another query with the equal state
*/
}, {
key: '_tunnelQueryCache',
value: function _tunnelQueryCache() {
return this.collection._queryCache.getByQuery(this);
}
}, {
key: 'toString',
value: function toString() {
if (!this.stringRep) {
var stringObj = util.sortObject({
op: this.op,
options: this.mquery.options,
_conditions: this.mquery._conditions,
_path: this.mquery._path,
_fields: this.mquery._fields
}, true);
this.stringRep = JSON.stringify(stringObj, util.stringifyFilter);
}
return this.stringRep;
}
/**
* ensures that the results of this query is equal to the results which a query over the database would give
* @return {Promise} true if results have changed
*/
}, {
key: '_ensureEqual',
value: function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
var ret, resolve, missedChangeEvents, runChangeEvents, changeResult, latestAfter, newResultData;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(this._latestChangeEvent >= this.collection._changeEventBuffer.counter)) {
_context.next = 2;
break;
}
return _context.abrupt('return', false);
case 2:
ret = false;
// make sure it does not run in parallel
_context.next = 5;
return this._runningPromise;
case 5:
// console.log('_ensureEqual(' + this.toString() + ') '+ this._mustReExec);
resolve = void 0;
this._runningPromise = new Promise(function (res) {
resolve = res;
});
if (this._mustReExec) {
_context.next = 21;
break;
}
missedChangeEvents = this.collection._changeEventBuffer.getFrom(this._latestChangeEvent + 1);
if (!(missedChangeEvents === null)) {
_context.next = 13;
break;
}
// out of bounds -> reExec
this._mustReExec = true;
_context.next = 21;
break;
case 13:
// console.dir(missedChangeEvents);
this._latestChangeEvent = this.collection._changeEventBuffer.counter;
runChangeEvents = this.collection._changeEventBuffer.reduceByLastOfDoc(missedChangeEvents);
changeResult = this._queryChangeDetector.runChangeDetection(runChangeEvents);
if (!Array.isArray(changeResult) && changeResult) this._mustReExec = true;
if (!(Array.isArray(changeResult) && !(0, _deepEqual2['default'])(changeResult, this._resultsData))) {
_context.next = 21;
break;
}
ret = true;
_context.next = 21;
return this._setResultData(changeResult);
case 21:
if (!this._mustReExec) {
_context.next = 31;
break;
}
// counter can change while _execOverDatabase() is running
latestAfter = this.collection._changeEventBuffer.counter;
_context.next = 25;
return this._execOverDatabase();
case 25:
newResultData = _context.sent;
this._latestChangeEvent = latestAfter;
if ((0, _deepEqual2['default'])(newResultData, this._resultsData)) {
_context.next = 31;
break;
}
ret = true;
_context.next = 31;
return this._setResultData(newResultData);
case 31:
// console.log('_ensureEqual DONE (' + this.toString() + ')');
resolve(true);
return _context.abrupt('return', ret);
case 33:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function _ensureEqual() {
return _ref2.apply(this, arguments);
}
return _ensureEqual;
}()
}, {
key: '_setResultData',
value: function _setResultData(newResultData) {
var _this = this;
this._resultsData = newResultData;
return this.collection._createDocuments(this._resultsData).then(function (newResults) {
return _this._results$.next(newResults);
});
}
/**
* executes the query on the database
* @return {Promise<{}[]>} results-array with document-data
*/
}, {
key: '_execOverDatabase',
value: function _execOverDatabase() {
var _this2 = this;
this._execOverDatabaseCount++;
var docsPromise = void 0;
switch (this.op) {
case 'find':
docsPromise = this.collection._pouchFind(this);
break;
case 'findOne':
docsPromise = this.collection._pouchFind(this, 1);
break;
default:
throw new Error('RxQuery.exec(): op (' + this.op + ') not known');
}
return docsPromise.then(function (docsData) {
_this2._mustReExec = false;
return docsData;
});
}
}, {
key: 'toJSON',
value: function toJSON() {
if (this._toJSON) return this._toJSON;
var primPath = this.collection.schema.primaryPath;
var json = {
selector: this.mquery._conditions
};
var options = this.mquery._optionsForExec();
// sort
if (options.sort) {
var sortArray = [];
Object.keys(options.sort).map(function (fieldName) {
var dirInt = options.sort[fieldName];
var dir = 'asc';
if (dirInt === -1) dir = 'desc';
var pushMe = {};
// TODO run primary-swap somewhere else
if (fieldName === primPath) fieldName = '_id';
pushMe[fieldName] = dir;
sortArray.push(pushMe);
});
json.sort = sortArray;
} else {
// sort by primaryKey as default
// (always use _id because there is no primary-swap on json.sort)
json.sort = [{
_id: 'asc'
}];
}
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';
// strip empty selectors
Object.entries(json.selector).filter(function (entry) {
return (0, _typeof3['default'])(entry[1]) === 'object';
}).filter(function (entry) {
return entry[1] !== null;
}).filter(function (entry) {
return !Array.isArray(entry[1]);
}).filter(function (entry) {
return Object.keys(entry[1]).length === 0;
}).forEach(function (entry) {
return delete json.selector[entry[0]];
});
// primary swap
if (primPath !== '_id' && json.selector[primPath]) {
// selector
json.selector._id = json.selector[primPath];
delete json.selector[primPath];
}
this._toJSON = json;
return this._toJSON;
}
}, {
key: 'keyCompress',
/**
* get the key-compression version of this query
* @return {{selector: {}, sort: []}} compressedQuery
*/
value: function keyCompress() {
if (!this.collection.schema.doKeyCompression()) return this.toJSON();else {
if (!this._keyCompress) {
this._keyCompress = this.collection._keyCompressor.compressQuery(this.toJSON());
}
return this._keyCompress;
}
}
/**
* deletes all found documents
* @return {Promise(RxDocument|RxDocument[])} promise with deleted documents
*/
}, {
key: 'remove',
value: function remove() {
var ret = void 0;
return this.exec().then(function (docs) {
ret = docs;
if (Array.isArray(docs)) return Promise.all(docs.map(function (doc) {
return doc.remove();
}));else return docs.remove();
}).then(function () {
return ret;
});
}
/**
* updates all found documents
* @overwritten by plugin (optinal)
* @param {object} updateObj
* @return {Promise(RxDocument|RxDocument[])} promise with updated documents
*/
}, {
key: 'update',
value: function update() {
throw _rxError2['default'].pluginMissing('update');
}
/**
* execute the query
* @return {Promise} found documents
*/
}, {
key: 'exec',
value: function exec() {
return this.$.first().toPromise();
}
/**
* regex cannot run on primary _id
* @link https://docs.cloudant.com/cloudant_query.html#creating-selector-expressions
*/
}, {
key: 'regex',
value: function regex(params) {
var clonedThis = this._clone();
if (this.mquery._path === this.collection.schema.primaryPath) throw new Error('You cannot use .regex() on the primary field \'' + this.mquery._path + '\'');
clonedThis.mquery.regex(params);
return clonedThis._tunnelQueryCache();
}
}, {
key: 'sort',
/**
* make sure it searches index because of pouchdb-find bug
* @link https://github.com/nolanlawson/pouchdb-find/issues/204
*/
value: function sort(params) {
var throwNotInSchema = function throwNotInSchema(key) {
throw new Error('RxQuery.sort(' + key + ') does not work because ' + key + ' is not defined in the schema');
};
var clonedThis = this._clone();
// workarround because sort wont work on unused keys
if ((typeof params === 'undefined' ? 'undefined' : (0, _typeof3['default'])(params)) !== 'object') {
var checkParam = params.charAt(0) === '-' ? params.substring(1) : params;
if (!clonedThis.mquery._conditions[checkParam]) {
var schemaObj = clonedThis.collection.schema.getSchemaByObjectPath(checkParam);
if (!schemaObj) throwNotInSchema(checkParam);
if (schemaObj.type === 'integer')
// TODO change back to -Infinity when issue resolved
// @link https://github.com/pouchdb/pouchdb/issues/6454
clonedThis.mquery.where(checkParam).gt(-9999999999999999999999999999); // -Infinity does not work since pouchdb 6.2.0
else clonedThis.mquery.where(checkParam).gt(null);
}
} else {
Object.keys(params).filter(function (k) {
return !clonedThis.mquery._conditions[k] || !clonedThis.mquery._conditions[k].$gt;
}).forEach(function (k) {
var schemaObj = clonedThis.collection.schema.getSchemaByObjectPath(k);
if (!schemaObj) throwNotInSchema(k);
if (schemaObj.type === 'integer')
// TODO change back to -Infinity when issue resolved
// @link https://github.com/pouchdb/pouchdb/issues/6454
clonedThis.mquery.where(k).gt(-9999999999999999999999999999); // -Infinity does not work since pouchdb 6.2.0
else clonedThis.mquery.where(k).gt(null);
});
}
clonedThis.mquery.sort(params);
return clonedThis._tunnelQueryCache();
}
}, {
key: 'limit',
value: function limit(amount) {
if (this.op === 'findOne') throw new Error('.limit() cannot be called on .findOne()');else {
var clonedThis = this._clone();
clonedThis.mquery.limit(amount);
return clonedThis._tunnelQueryCache();
}
}
}, {
key: '$',
get: function get() {
var _this3 = this;
if (!this._$) {
var res$ = this._results$.mergeMap(function (results) {
return _this3._ensureEqual().then(function (hasChanged) {
if (hasChanged) return 'WAITFORNEXTEMIT';else return results;
});
}).filter(function (results) {
return results !== 'WAITFORNEXTEMIT';
}).asObservable();
var changeEvents$ = this.collection.$.filter(function (cEvent) {
return ['INSERT', 'UPDATE', 'REMOVE'].includes(cEvent.data.op);
}).mergeMap((0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt('return', _this3._ensureEqual());
case 1:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this3);
}))).filter(function () {
return false;
});
this._$ = util.Rx.Observable.merge(res$, changeEvents$).filter(function (x) {
return x !== null;
}).map(function (results) {
if (_this3.op !== 'findOne') return results;else if (results.length === 0) return null;else return results[0];
});
}
return this._$;
}
}]);
return RxQuery;
}();
/**
* tunnel the proto-functions of mquery to RxQuery
* @param {any} rxQueryProto [description]
* @param {string[]} mQueryProtoKeys [description]
* @return {void} [description]
*/
var protoMerge = function protoMerge(rxQueryProto, mQueryProtoKeys) {
mQueryProtoKeys.filter(function (attrName) {
return !attrName.startsWith('_');
}).filter(function (attrName) {
return !rxQueryProto[attrName];
}).forEach(function (attrName) {
rxQueryProto[attrName] = function (p1) {
var clonedThis = this._clone();
clonedThis.mquery[attrName](p1);
return clonedThis._tunnelQueryCache();
};
});
};
var protoMerged = false;
function create(op, queryObj, collection) {
if (queryObj && (typeof queryObj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(queryObj)) !== 'object') throw new TypeError('query must be an object');
if (Array.isArray(queryObj)) throw new TypeError('query cannot be an array');
var ret = new RxQuery(op, queryObj, collection);
if (!protoMerged) {
protoMerged = true;
protoMerge(Object.getPrototypeOf(ret), Object.getOwnPropertyNames(ret.mquery.__proto__));
}
(0, _hooks.runPluginHooks)('createRxQuery', ret);
return ret;
}
function isInstanceOf(obj) {
return obj instanceof RxQuery;
}
exports['default'] = {
create: create,
RxQuery: RxQuery,
isInstanceOf: isInstanceOf
};
},{"./hooks":7,"./mquery/mquery":9,"./query-change-detector":27,"./rx-error":33,"./util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/defineProperty":52,"babel-runtime/helpers/typeof":56,"babel-runtime/regenerator":57,"deep-equal":496}],35:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RxSchema = 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.getEncryptedPaths = getEncryptedPaths;
exports.hasCrypt = hasCrypt;
exports.getIndexes = getIndexes;
exports.getPrimary = getPrimary;
exports.getFinalFields = getFinalFields;
exports.normalize = normalize;
exports.create = create;
exports.isInstanceOf = isInstanceOf;
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 _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
var _hooks = require('./hooks');
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 = exports.RxSchema = function () {
function RxSchema(jsonID) {
var _this = this;
(0, _classCallCheck3['default'])(this, RxSchema);
this.jsonID = jsonID;
this.compoundIndexes = this.jsonID.compoundIndexes;
// make indexes required
this.indexes = getIndexes(this.jsonID);
this.indexes.forEach(function (indexAr) {
indexAr.filter(function (index) {
return !_this.jsonID.required.includes(index);
}).filter(function (index) {
return !index.includes('.');
}) // TODO make them sub-required
.forEach(function (index) {
return _this.jsonID.required.push(index);
});
});
// primary is always required
this.primaryPath = getPrimary(this.jsonID);
if (this.primaryPath) this.jsonID.required.push(this.primaryPath);
// final fields are always required
this.finalFields = getFinalFields(this.jsonID);
this.jsonID.required = this.jsonID.required.concat(this.finalFields).filter(function (elem, pos, arr) {
return arr.indexOf(elem) === pos;
}); // unique;
// add primary to schema if not there (if _id)
if (!this.jsonID.properties[this.primaryPath]) {
this.jsonID.properties[this.primaryPath] = {
type: 'string',
minLength: 1
};
}
}
/**
* @return {number}
*/
(0, _createClass3['default'])(RxSchema, [{
key: 'getSchemaByObjectPath',
value: function getSchemaByObjectPath(path) {
path = path.replace(/\./g, '.properties.');
path = 'properties.' + path;
path = util.trimDots(path);
var ret = _objectPath2['default'].get(this.jsonID, path);
return ret;
}
}, {
key: 'validate',
/**
* validate if the obj matches the schema
* @overwritten by plugin (required)
* @param {Object} obj
* @param {string} schemaPath if given, validates agains deep-path of schema
* @throws {Error} if not valid
* @param {Object} obj equal to input-obj
*/
value: function validate() {
throw _rxError2['default'].pluginMissing('validate');
}
}, {
key: 'fillObjectWithDefaults',
/**
* fills all unset fields with default-values if set
* @param {object} obj
* @return {object}
*/
value: function fillObjectWithDefaults(obj) {
obj = (0, _clone2['default'])(obj);
Object.entries(this.defaultValues).filter(function (entry) {
return !obj.hasOwnProperty(entry[0]);
}).forEach(function (entry) {
obj[entry[0]] = entry[1];
});
return obj;
}
}, {
key: 'swapIdToPrimary',
value: function swapIdToPrimary(obj) {
if (this.primaryPath === '_id' || obj[this.primaryPath]) return obj;
obj[this.primaryPath] = obj._id;
delete obj._id;
return obj;
}
}, {
key: 'swapPrimaryToId',
value: function swapPrimaryToId(obj) {
var _this2 = this;
if (this.primaryPath === '_id') return obj;
var ret = {};
Object.entries(obj).forEach(function (entry) {
var newKey = entry[0] === _this2.primaryPath ? '_id' : entry[0];
ret[newKey] = entry[1];
});
return ret;
}
/**
* returns true if key-compression should be done
*/
}, {
key: 'doKeyCompression',
value: function doKeyCompression() {
return !!!this.jsonID.disableKeyCompression;
}
}, {
key: 'version',
get: function get() {
return this.jsonID.version;
}
/**
* @return {number[]} array with previous version-numbers
*/
}, {
key: 'previousVersions',
get: function get() {
var c = 0;
return new Array(this.version).fill(0).map(function () {
return c++;
});
}
/**
* true if schema contains at least one encrypted path
* @type {boolean}
*/
}, {
key: 'crypt',
get: function get() {
if (!this._crypt) this._crypt = hasCrypt(this.jsonID);
return this._crypt;
}
}, {
key: 'normalized',
get: function get() {
if (!this._normalized) this._normalized = normalize(this.jsonID);
return this._normalized;
}
}, {
key: 'topLevelFields',
get: function get() {
return Object.keys(this.normalized.properties);
}
}, {
key: 'defaultValues',
get: function get() {
var _this3 = this;
if (!this._defaultValues) {
this._defaultValues = {};
Object.entries(this.normalized.properties).filter(function (entry) {
return entry[1]['default'];
}).forEach(function (entry) {
return _this3._defaultValues[entry[0]] = entry[1]['default'];
});
}
return this._defaultValues;
}
/**
* get all encrypted paths
*/
}, {
key: 'encryptedPaths',
get: function get() {
if (!this._encryptedPaths) this._encryptedPaths = getEncryptedPaths(this.jsonID);
return this._encryptedPaths;
}
}, {
key: 'hash',
get: function get() {
if (!this._hash) this._hash = util.hash(this.normalized);
return this._hash;
}
}]);
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.properties, '');
return ret;
}
/**
* returns true if schema contains an encrypted field
* @param {object} jsonSchema with schema
* @return {boolean} isEncrypted
*/
function hasCrypt(jsonSchema) {
var paths = getEncryptedPaths(jsonSchema);
if (Object.keys(paths).length > 0) return true;else return false;
}
function getIndexes(jsonID) {
var prePath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var indexes = [];
Object.entries(jsonID).forEach(function (entry) {
var key = entry[0];
var obj = entry[1];
var path = key === 'properties' ? prePath : util.trimDots(prePath + '.' + key);
if (obj.index) indexes.push([path]);
if ((typeof obj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(obj)) === 'object' && !Array.isArray(obj)) {
var add = getIndexes(obj, path);
indexes = indexes.concat(add);
}
});
if (prePath === '') {
var addCompound = jsonID.compoundIndexes || [];
indexes = indexes.concat(addCompound);
}
indexes = indexes.filter(function (elem, pos, arr) {
return arr.indexOf(elem) === pos;
}); // unique;
return indexes;
}
/**
* returns the primary path of a jsonschema
* @param {Object} jsonID
* @return {string} primaryPath which is _id if none defined
*/
function getPrimary(jsonID) {
var ret = Object.keys(jsonID.properties).filter(function (key) {
return jsonID.properties[key].primary;
}).shift();
if (!ret) return '_id';else return ret;
}
/**
* returns the final-fields of the schema
* @param {Object} jsonId
* @return {string[]} field-names of the final-fields
*/
function getFinalFields(jsonId) {
return Object.keys(jsonId.properties).filter(function (key) {
return jsonId.properties[key].final;
});
}
/**
* orders the schemas attributes by alphabetical order
* @param {Object} jsonSchema
* @return {Object} jsonSchema - ordered
*/
function normalize(jsonSchema) {
return util.sortObject((0, _clone2['default'])(jsonSchema));
}
/**
* fills the schema-json with default-settings
* @param {Object} schemaObj
* @return {Object} cloned schemaObj
*/
var fillWithDefaultSettings = function fillWithDefaultSettings(schemaObj) {
schemaObj = (0, _clone2['default'])(schemaObj);
// additionalProperties is always false
schemaObj.additionalProperties = false;
// fill with key-compression-state ()
if (!schemaObj.hasOwnProperty('disableKeyCompression')) schemaObj.disableKeyCompression = false;
// compoundIndexes must be array
schemaObj.compoundIndexes = schemaObj.compoundIndexes || [];
// required must be array
schemaObj.required = schemaObj.required || [];
// add _rev
schemaObj.properties._rev = {
type: 'string',
minLength: 1
};
// add attachments
schemaObj.properties._attachments = {
type: 'object'
};
// version is 0 by default
schemaObj.version = schemaObj.version || 0;
return schemaObj;
};
function create(jsonID) {
var runPreCreateHooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (runPreCreateHooks) (0, _hooks.runPluginHooks)('preCreateRxSchema', jsonID);
var schema = new RxSchema(fillWithDefaultSettings(jsonID));
(0, _hooks.runPluginHooks)('createRxSchema', schema);
return schema;
}
function isInstanceOf(obj) {
return obj instanceof RxSchema;
}
exports['default'] = {
RxSchema: RxSchema,
getEncryptedPaths: getEncryptedPaths,
hasCrypt: hasCrypt,
getIndexes: getIndexes,
getPrimary: getPrimary,
getFinalFields: getFinalFields,
normalize: normalize,
create: create,
isInstanceOf: isInstanceOf
};
},{"./hooks":7,"./rx-error":33,"./util":37,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/helpers/typeof":56,"clone":63,"object-path":567}],36:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PULL_TIME = exports.EVENT_TTL = 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);
exports.create = create;
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _rxChangeEvent = require('./rx-change-event');
var _rxChangeEvent2 = _interopRequireDefault(_rxChangeEvent);
var _rxBroadcastChannel = require('./rx-broadcast-channel');
var _rxBroadcastChannel2 = _interopRequireDefault(_rxBroadcastChannel);
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 EVENT_TTL = 5000; // after this age, events will be deleted
var PULL_TIME = _rxBroadcastChannel2['default'].canIUse() ? EVENT_TTL / 2 : 200;
var Socket = function () {
function Socket(database) {
(0, _classCallCheck3['default'])(this, Socket);
this._destroyed = false;
this.database = database;
this.token = database.token;
this.subs = [];
this.pullCount = 0;
this.pull_running = false;
this.lastPull = new Date().getTime();
this.receivedEvents = {};
this.bc = _rxBroadcastChannel2['default'].create(this.database, 'socket');
this.messages$ = new util.Rx.Subject();
}
/**
* @return {Observable}
*/
(0, _createClass3['default'])(Socket, [{
key: 'prepare',
value: function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
var _this = this;
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
// create socket-collection
this.pouch = this.database._spawnPouchDB('_socket', 0, {
auto_compaction: false, // this is false because its done manually at .pull()
revs_limit: 1
});
// pull on BroadcastChannel-message
if (this.bc) {
this.subs.push(this.bc.$.filter(function (msg) {
return msg.type === 'pull';
}).subscribe(function () {
return _this.pull();
}));
}
// pull on intervall
(0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (_this._destroyed) {
_context.next = 8;
break;
}
_context.next = 3;
return util.promiseWait(PULL_TIME);
case 3:
if (!(_this.messages$.observers.length > 0 && !_this._destroyed)) {
_context.next = 6;
break;
}
_context.next = 6;
return _this.pull();
case 6:
_context.next = 0;
break;
case 8:
case 'end':
return _context.stop();
}
}
}, _callee, _this);
}))();
return _context2.abrupt('return', this);
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function prepare() {
return _ref.apply(this, arguments);
}
return prepare;
}()
/**
* write the given event to the socket
*/
}, {
key: 'write',
value: function () {
var _ref3 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee3(changeEvent) {
var _this2 = this;
var socketDoc;
return _regenerator2['default'].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
socketDoc = changeEvent.toJSON();
delete socketDoc.db;
// TODO find a way to getAll on local documents
// socketDoc._id = '_local/' + util.fastUnsecureHash(socketDoc);
socketDoc._id = '' + util.fastUnsecureHash(socketDoc) + socketDoc.t;
_context3.next = 5;
return this.database.lockedRun(function () {
return _this2.pouch.put(socketDoc);
});
case 5:
_context3.t0 = this.bc;
if (!_context3.t0) {
_context3.next = 9;
break;
}
_context3.next = 9;
return this.bc.write('pull');
case 9:
return _context3.abrupt('return', true);
case 10:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function write(_x) {
return _ref3.apply(this, arguments);
}
return write;
}()
/**
* get all docs from the socket-collection
*/
}, {
key: 'fetchDocs',
value: function () {
var _ref4 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee4() {
var _this3 = this;
var result;
return _regenerator2['default'].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.database.lockedRun(function () {
return _this3.pouch.allDocs({
include_docs: true
});
});
case 2:
result = _context4.sent;
return _context4.abrupt('return', result.rows.map(function (row) {
return row.doc;
}));
case 4:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function fetchDocs() {
return _ref4.apply(this, arguments);
}
return fetchDocs;
}()
/**
* delete the document from the socket-database.
* This mutes errors because they are likely but not bad on multiInstance
* @param {any} doc
* @return {Promise} success
*/
}, {
key: 'deleteDoc',
value: function () {
var _ref5 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee5(doc) {
var _this4 = this;
var success;
return _regenerator2['default'].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
success = true;
_context5.prev = 1;
_context5.next = 4;
return this.database.lockedRun(function () {
return _this4.pouch.remove(doc);
});
case 4:
_context5.next = 9;
break;
case 6:
_context5.prev = 6;
_context5.t0 = _context5['catch'](1);
success = false;
case 9:
return _context5.abrupt('return', success);
case 10:
case 'end':
return _context5.stop();
}
}
}, _callee5, this, [[1, 6]]);
}));
function deleteDoc(_x2) {
return _ref5.apply(this, arguments);
}
return deleteDoc;
}()
/**
* runs a cleanup to delete the given docs
* @param {array} docsData docs to be deleted
* @return {void}
*/
}, {
key: '_cleanupDocs',
value: function _cleanupDocs(docsData) {
var _this5 = this;
// delete docs on idle
docsData.forEach(function (docData) {
_this5.database.requestIdlePromise().then(function () {
if (_this5._destroyed) return;
_this5.deleteDoc(docData);
});
});
// run a compaction if more than one doc was deleted
if (docsData.length > 0) {
this.database.requestIdlePromise().then(function () {
if (_this5._destroyed) return;
_this5.database.lockedRun(function () {
return _this5.pouch.compact();
});
});
}
}
/**
* grab all new events from the socket-pouchdb
* and throw them into this.messages$
*/
}, {
key: 'pull',
value: function () {
var _ref6 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee6() {
var _this6 = this;
var minTime, docs, maxAge, delDocs;
return _regenerator2['default'].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!this.isPulling) {
_context6.next = 3;
break;
}
this._repullAfter = true;
return _context6.abrupt('return', false);
case 3:
this.isPulling = true;
this.pullCount++;
// w8 for idle-time because this is a non-prio-task
_context6.next = 7;
return util.requestIdlePromise(EVENT_TTL / 2);
case 7:
if (!this._destroyed) {
_context6.next = 9;
break;
}
return _context6.abrupt('return');
case 9:
minTime = this.lastPull - 100; // TODO evaluate this value (100)
_context6.next = 12;
return this.fetchDocs();
case 12:
docs = _context6.sent;
if (!this._destroyed) {
_context6.next = 15;
break;
}
return _context6.abrupt('return');
case 15:
docs.filter(function (doc) {
return doc.it !== _this6.token;
}) // do not get events emitted by self
// do not get events older than minTime
.filter(function (doc) {
return doc.t > minTime;
})
// sort timestamp
.sort(function (a, b) {
if (a.t > b.t) return 1;
return -1;
}).map(function (doc) {
return _rxChangeEvent2['default'].fromJSON(doc);
})
// make sure the same event is not emitted twice
.filter(function (cE) {
if (_this6.receivedEvents[cE.hash]) return false;
return _this6.receivedEvents[cE.hash] = new Date().getTime();
})
// prevent memory leak of this.receivedEvents
.filter(function (cE) {
return setTimeout(function () {
return delete _this6.receivedEvents[cE.hash];
}, EVENT_TTL * 3);
})
// emit to messages
.forEach(function (cE) {
return _this6.messages$.next(cE);
});
if (!this._destroyed) {
_context6.next = 18;
break;
}
return _context6.abrupt('return');
case 18:
// delete old documents
maxAge = new Date().getTime() - EVENT_TTL;
delDocs = docs.filter(function (doc) {
return doc.t < maxAge;
});
this._cleanupDocs(delDocs);
this.lastPull = new Date().getTime();
this.isPulling = false;
if (this._repull) {
this._repull = false;
this.pull();
}
return _context6.abrupt('return', true);
case 25:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
function pull() {
return _ref6.apply(this, arguments);
}
return pull;
}()
}, {
key: 'destroy',
value: function () {
var _ref7 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee7() {
return _regenerator2['default'].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
this._destroyed = true;
this.subs.map(function (sub) {
return sub.unsubscribe();
});
this.bc && this.bc.destroy();
case 3:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
function destroy() {
return _ref7.apply(this, arguments);
}
return destroy;
}()
}, {
key: '$',
get: function get() {
if (!this._$) this._$ = this.messages$.asObservable();
return this._$;
}
}]);
return Socket;
}();
/**
* creates a socket
* @return {Promise}
*/
function create(database) {
var socket = new Socket(database);
return socket.prepare();
}
exports.EVENT_TTL = EVENT_TTL;
exports.PULL_TIME = PULL_TIME;
exports['default'] = {
create: create,
EVENT_TTL: EVENT_TTL,
PULL_TIME: PULL_TIME
};
},{"./rx-broadcast-channel":28,"./rx-change-event":29,"./util":37,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/classCallCheck":50,"babel-runtime/helpers/createClass":51,"babel-runtime/regenerator":57}],37:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.requestIdlePromise = exports.promiseWait = 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);
/**
* [promiseWait description]
* @param {Number} [ms=0]
* @return {Promise}
*/
var promiseWait = exports.promiseWait = function () {
var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee() {
var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return _regenerator2['default'].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', new Promise(function (res) {
return setTimeout(res, ms);
}));
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function promiseWait() {
return _ref.apply(this, arguments);
};
}();
var requestIdlePromise = exports.requestIdlePromise = function () {
var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee2() {
var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
return _regenerator2['default'].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!((typeof window === 'undefined' ? 'undefined' : (0, _typeof3['default'])(window)) === 'object' && window.requestIdleCallback)) {
_context2.next = 4;
break;
}
return _context2.abrupt('return', new Promise(function (res) {
return window.requestIdleCallback(res, {
timeout: timeout
});
}));
case 4:
return _context2.abrupt('return', new Promise(function (res) {
return setTimeout(res, 0);
}));
case 5:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function requestIdlePromise() {
return _ref2.apply(this, arguments);
};
}();
/**
* run the callback if requestIdleCallback available
* do nothing if not
* @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback
* @param {function} fun
* @return {void}
*/
exports.isLevelDown = isLevelDown;
exports.fastUnsecureHash = fastUnsecureHash;
exports.hash = hash;
exports.generateId = generateId;
exports.nextTick = nextTick;
exports.requestIdleCallbackIfAvailable = requestIdleCallbackIfAvailable;
exports.ucfirst = ucfirst;
exports.numberToLetter = numberToLetter;
exports.trimDots = trimDots;
exports.validateCouchDBString = validateCouchDBString;
exports.sortObject = sortObject;
exports.stringifyFilter = stringifyFilter;
exports.pouchReplicationFunction = pouchReplicationFunction;
exports.randomCouchString = randomCouchString;
exports.shuffleArray = shuffleArray;
exports.adapterObject = adapterObject;
var _randomToken = require('random-token');
var _randomToken2 = _interopRequireDefault(_randomToken);
var _rxError = require('./rx-error');
var _rxError2 = _interopRequireDefault(_rxError);
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/from');
require('rxjs/add/observable/fromEvent');
require('rxjs/add/observable/defer');
require('rxjs/add/operator/publishReplay');
require('rxjs/add/operator/publish');
require('rxjs/add/operator/timeout');
require('rxjs/add/operator/delay');
require('rxjs/add/operator/do');
require('rxjs/add/operator/map');
require('rxjs/add/operator/mergeMap');
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');
require('rxjs/add/operator/distinct');
var _sparkMd = require('spark-md5');
var _sparkMd2 = _interopRequireDefault(_sparkMd);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var Rx = exports.Rx = {
Observable: _Observable.Observable,
Subject: _Subject.Subject,
BehaviorSubject: _BehaviorSubject.BehaviorSubject
};
/**
* check if the given module is a leveldown-adapter
* throws if not
*/
// rxjs cherry-pick
/**
* this contains a mapping to basic dependencies
* which should be easy to change
*/
function isLevelDown(adapter) {
if (!adapter || typeof adapter.super_ !== 'function' || typeof adapter.destroy !== 'function') throw new Error('given leveldown is no valid adapter');
}
/**
* 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
*/
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;
}
/**
* spark-md5 is used here
* because pouchdb uses the same
* and build-size could be reduced by 9kb
*/
function hash(obj) {
var msg = obj;
if (typeof obj !== 'string') msg = JSON.stringify(obj);
return _sparkMd2['default'].hash(msg);
}
/**
* generate a new _id as db-primary-key
* @return {string}
*/
function generateId() {
return (0, _randomToken2['default'])(10) + ':' + new Date().getTime();
}
/**
* returns a promise that resolves on the next tick
* @return {Promise}
*/
function nextTick() {
return new Promise(function (res) {
return setTimeout(res, 0);
});
}function requestIdleCallbackIfAvailable(fun) {
if ((typeof window === 'undefined' ? 'undefined' : (0, _typeof3['default'])(window)) === 'object' && window.requestIdleCallback) window.requestIdleCallback(fun);
}
/**
* uppercase first char
* @param {string} str
* @return {string} Str
*/
function ucfirst(str) {
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
/**
* @link https://de.wikipedia.org/wiki/Base58
* this does not start with the numbers to generate valid variable-names
*/
var base58Chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789';
var base58Length = base58Chars.length;
/**
* transform a number to a string by using only base58 chars
* @link https://github.com/matthewmueller/number-to-letter/blob/master/index.js
* @param {number} nr | 10000000
* @return {string} the string-representation of the number | '2oMX'
*/
function numberToLetter(nr) {
var digits = [];
do {
var v = nr % base58Length;
digits.push(v);
nr = Math.floor(nr / base58Length);
} while (nr-- > 0);
return digits.reverse().map(function (d) {
return base58Chars[d];
}).join('');
}
/**
* removes trailing and ending dots from the string
* @param {string} str
* @return {string} str without wrapping dots
*/
function trimDots(str) {
// start
while (str.charAt(0) === '.') {
str = str.substr(1);
} // end
while (str.slice(-1) === '.') {
str = str.slice(0, -1);
}return str;
}
/**
* validates that a given string is ok to be used with couchdb-collection-names
* @link https://wiki.apache.org/couchdb/HTTP_database_API
* @param {string} name
* @throws {Error}
* @return {boolean} true
*/
function validateCouchDBString(name) {
if (typeof name !== 'string' || name.length === 0) throw new TypeError('given name is no string or empty');
// do not check, if foldername is given
if (name.includes('/') || // unix
name.includes('\\') // windows
) return true;
var regStr = '^[a-z][a-z0-9]*$';
var reg = new RegExp(regStr);
if (!name.match(reg)) {
throw new _rxError2['default'].newRxError('collection- and database-names must match the regex\n info: if your database-name specifies a folder, the name must contain the slash-char \'/\' or \'\\\'\n ', {
regex: regStr,
givenName: name
});
}
return true;
}
/**
* deep-sort an object so its attributes are in lexical order.
* Also sorts the arrays inside of the object if no-array-sort not set
* @param {Object} obj unsorted
* @param {?boolean} noArraysort
* @return {Object} sorted
*/
function sortObject(obj) {
var noArraySort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!obj) return obj; // do not sort null, false or undefined
// array
if (!noArraySort && Array.isArray(obj)) {
return obj.sort(function (a, b) {
if (typeof a === 'string' && typeof b === 'string') return a.localeCompare(b);
if ((typeof a === 'undefined' ? 'undefined' : (0, _typeof3['default'])(a)) === 'object') return 1;else return -1;
}).map(function (i) {
return sortObject(i);
});
}
// object
if ((typeof obj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(obj)) === 'object') {
if (obj instanceof RegExp) return obj;
var out = {};
Object.keys(obj).sort(function (a, b) {
return a.localeCompare(b);
}).forEach(function (key) {
out[key] = sortObject(obj[key]);
});
return out;
}
// everything else
return obj;
}
/**
* used to JSON.stringify() objects that contain a regex
* @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs!
*/
function stringifyFilter(key, value) {
if (value instanceof RegExp) return value.toString();
return value;
}
/**
* get the correct function-name for pouchdb-replication
* @param {object} pouch - instance of pouchdb
* @return {function}
*/
function pouchReplicationFunction(pouch, _ref3) {
var _ref3$pull = _ref3.pull,
pull = _ref3$pull === undefined ? true : _ref3$pull,
_ref3$push = _ref3.push,
push = _ref3$push === undefined ? true : _ref3$push;
if (pull && push) return pouch.sync.bind(pouch);
if (!pull && push) return pouch.replicate.to.bind(pouch);
if (pull && !push) return pouch.replicate.from.bind(pouch);
if (!pull && !push) throw new Error('replication-direction must either be push or pull or both. But not none.');
}
/**
* get a random string which can be used with couchdb
* @link http://stackoverflow.com/a/1349426/3443137
* @param {number} [length=10] length
* @return {string}
*/
function randomCouchString() {
var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
var text = '';
var possible = 'abcdefghijklmnopqrstuvwxyz';
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}return text;
}
/**
* shuffle the given array
* @param {Array} arr
* @return {Array}
*/
function shuffleArray(arr) {
return arr.sort(function () {
return Math.random() - 0.5;
});
};
/**
* transforms the given adapter into a pouch-compatible object
* @return {Object} adapterObject
*/
function adapterObject(adapter) {
var adapterObj = {
db: adapter
};
if (typeof adapter === 'string') {
adapterObj = {
adapter: adapter
};
}
return adapterObj;
};
},{"./rx-error":33,"babel-runtime/helpers/asyncToGenerator":49,"babel-runtime/helpers/typeof":56,"babel-runtime/regenerator":57,"random-token":612,"rxjs/BehaviorSubject":631,"rxjs/Observable":634,"rxjs/Subject":639,"rxjs/add/observable/defer":643,"rxjs/add/observable/from":644,"rxjs/add/observable/fromEvent":645,"rxjs/add/observable/interval":646,"rxjs/add/observable/merge":647,"rxjs/add/operator/delay":648,"rxjs/add/operator/distinct":649,"rxjs/add/operator/distinctUntilChanged":650,"rxjs/add/operator/do":651,"rxjs/add/operator/filter":652,"rxjs/add/operator/first":653,"rxjs/add/operator/map":654,"rxjs/add/operator/mergeMap":655,"rxjs/add/operator/publish":656,"rxjs/add/operator/publishReplay":657,"rxjs/add/operator/startWith":658,"rxjs/add/operator/timeout":659,"rxjs/add/operator/toPromise":660,"spark-md5":743}],38:[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, []);
}
};
}
},{}],39:[function(require,module,exports){
/**
* @file Invokes function, returning an object of the results.
* @version 1.1.1
* @author Xotic750
* @copyright Xotic750
* @license {@link MIT}
* @module attempt-x
*/
'use strict';
var getArgs = function _getArgs(args) {
var length = args.length >>> 0;
var array = [];
var argLength = length - 1;
if (argLength < 1) {
return array;
}
array.length = argLength;
for (var index = 1; index < length; index += 1) {
array[index - 1] = args[index];
}
return array;
};
/**
* This method attempts to invoke the function, returning either the result or
* the caught error object. Any additional arguments are provided to the
* function when it's invoked.
*
* @param {Function} fn - The function to attempt.
* @param {...*} [args] - The arguments to invoke the function with.
* @returns {Object} Returns an object of the result.
* @example
* var attempt = require('attempt-x');
*
* function thrower() {
* throw new Error('Threw');
* }
*
* attempt(thrower, 1, 2);
* // {
* // threw: true,
* // value: // Error('Threw') object
* // }
*
* function sumArgs(a, b) {
* return a + b;
* }
*
* attempt(sumArgs, 1, 2);
* // {
* // threw: false,
* // value: 3
* // }
*
* var thisArg = [];
* function pusher(a, b) {
* return this.push(a, b);
* }
*
* attempt.call(thisArg, pusher, 1, 2);
* // {
* // threw: false,
* // value: 2
* // }
* // thisArg => [1, 2];
*/
module.exports = function attempt(fn) {
try {
return {
threw: false,
value: fn.apply(this, getArgs(arguments))
};
} catch (e) {
return {
threw: true,
value: e
};
}
};
},{}],40:[function(require,module,exports){
(function (global){
"use strict";
require("core-js/shim");
require("regenerator-runtime/runtime");
require("core-js/fn/regexp/escape");
if (global._babelPolyfill) {
throw new Error("only one instance of babel-polyfill is allowed");
}
global._babelPolyfill = true;
var DEFINE_PROPERTY = "defineProperty";
function define(O, key, value) {
O[key] || Object[DEFINE_PROPERTY](O, key, {
writable: true,
configurable: true,
value: value
});
}
define(String.prototype, "padLeft", "".padStart);
define(String.prototype, "padRight", "".padEnd);
"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) {
[][key] && define(Array, key, Function.call.bind([][key]));
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"core-js/fn/regexp/escape":64,"core-js/shim":480,"regenerator-runtime/runtime":41}],41:[function(require,module,exports){
(function (global){
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
!(function(global) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime;
if (runtime) {
if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime.
module.exports = runtime;
}
// Don't bother evaluating the rest of this file if the runtime was
// already defined globally.
return;
}
// Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
runtime.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
runtime.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
runtime.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return Promise.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
resolve(result);
}, reject);
}
}
if (typeof global.process === "object" && global.process.domain) {
invoke = global.process.domain.bind(invoke);
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new Promise(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
runtime.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
runtime.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
if (delegate.iterator.return) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator";
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
runtime.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
runtime.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
})(
// Among the various tricks for obtaining a reference to the global
// object, this seems to be the most reliable technique that does not
// use indirect eval (which violates Content Security Policy).
typeof global === "object" ? global :
typeof window === "object" ? window :
typeof self === "object" ? self : this
);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],42:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/array/from"), __esModule: true };
},{"core-js/library/fn/array/from":65}],43:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true };
},{"core-js/library/fn/object/create":66}],44:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/define-property"), __esModule: true };
},{"core-js/library/fn/object/define-property":67}],45:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true };
},{"core-js/library/fn/object/set-prototype-of":68}],46:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/promise"), __esModule: true };
},{"core-js/library/fn/promise":69}],47:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true };
},{"core-js/library/fn/symbol":70}],48:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true };
},{"core-js/library/fn/symbol/iterator":71}],49:[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":46}],50:[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");
}
};
},{}],51:[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":44}],52:[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 (obj, key, value) {
if (key in obj) {
(0, _defineProperty2.default)(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
},{"../core-js/object/define-property":44}],53:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var _setPrototypeOf = require("../core-js/object/set-prototype-of");
var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);
var _create = require("../core-js/object/create");
var _create2 = _interopRequireDefault(_create);
var _typeof2 = require("../helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
}
subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};
},{"../core-js/object/create":43,"../core-js/object/set-prototype-of":45,"../helpers/typeof":56}],54:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var _typeof2 = require("../helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};
},{"../helpers/typeof":56}],55:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var _from = require("../core-js/array/from");
var _from2 = _interopRequireDefault(_from);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return (0, _from2.default)(arr);
}
};
},{"../core-js/array/from":42}],56:[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":47,"../core-js/symbol/iterator":48}],57:[function(require,module,exports){
module.exports = require("regenerator-runtime");
},{"regenerator-runtime":626}],58:[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, 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; i < l; i += 4) {
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('')
}
},{}],59:[function(require,module,exports){
},{}],60:[function(require,module,exports){
(function (Buffer){
var isArrayBuffer = require('is-array-buffer-x')
var isModern = (
typeof Buffer.alloc === 'function' &&
typeof Buffer.allocUnsafe === 'function' &&
typeof Buffer.from === 'function'
)
function fromArrayBuffer (obj, byteOffset, length) {
byteOffset >>>= 0
var maxLength = obj.byteLength - byteOffset
if (maxLength < 0) {
throw new RangeError("'offset' is out of bounds")
}
if (length === undefined) {
length = maxLength
} else {
length >>>= 0
if (length > maxLength) {
throw new RangeError("'length' is out of bounds")
}
}
return isModern
? Buffer.from(obj.slice(byteOffset, byteOffset + length))
: new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
return isModern
? Buffer.from(string, encoding)
: new Buffer(string, encoding)
}
function bufferFrom (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (isArrayBuffer(value)) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return isModern
? Buffer.from(value)
: new Buffer(value)
}
module.exports = bufferFrom
}).call(this,require("buffer").Buffer)
},{"buffer":61,"is-array-buffer-x":521}],61:[function(require,module,exports){
/*!
* 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')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an 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+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42
} catch (e) {
return false
}
}
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* 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) {
// 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(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (isArrayBuffer(value)) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return fromObject(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(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
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 (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(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(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (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
var buf = createBuffer(length)
var actual = buf.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')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
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')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(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 < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.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 === true
}
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 (!Array.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 (isArrayBufferView(string) || isArrayBuffer(string)) {
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
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
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
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 (numberIsNaN(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 (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 (numberIsNaN(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
}
} 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 = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
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) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
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)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
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)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
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)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
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 (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)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
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)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
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)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
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
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
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) {
value = +value
offset = offset >>> 0
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) {
value = +value
offset = offset >>> 0
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) {
// 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
: new Buffer(val, encoding)
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 = str.trim().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 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
}
// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
function isArrayBuffer (obj) {
return obj instanceof ArrayBuffer ||
(obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
typeof obj.byteLength === 'number')
}
// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
function isArrayBufferView (obj) {
return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
}
function numberIsNaN (obj) {
return obj !== obj // eslint-disable-line no-self-compare
}
},{"base64-js":58,"ieee754":517}],62:[function(require,module,exports){
/**
* @file Constructors cached from literals.
* @version 1.0.0
* @author Xotic750
* @copyright Xotic750
* @license {@link MIT}
* @module cached-constructors-x
*/
'use strict';
/**
* Constructors cached from literals.
*
* @type Object
* @example
* var constructors = require('cached-constructors-x');
*/
module.exports = {
Array: [].constructor,
Boolean: true.constructor,
Number: (0).constructor,
Object: {}.constructor,
RegExp: (/(?:)/).constructor,
String: ''.constructor
};
},{}],63:[function(require,module,exports){
(function (Buffer){
var clone = (function() {
'use strict';
function _instanceof(obj, type) {
return type != null && obj instanceof type;
}
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 (_instanceof(parent, nativeMap)) {
child = new nativeMap();
} else if (_instanceof(parent, nativeSet)) {
child = new nativeSet();
} else if (_instanceof(parent, 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 (_instanceof(parent, 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 (_instanceof(parent, nativeMap)) {
parent.forEach(function(value, key) {
var keyChild = _clone(key, depth - 1);
var valueChild = _clone(value, depth - 1);
child.set(keyChild, valueChild);
});
}
if (_instanceof(parent, nativeSet)) {
parent.forEach(function(value) {
var entryChild = _clone(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":61}],64:[function(require,module,exports){
require('../../modules/core.regexp.escape');
module.exports = require('../../modules/_core').RegExp.escape;
},{"../../modules/_core":179,"../../modules/core.regexp.escape":283}],65:[function(require,module,exports){
require('../../modules/es6.string.iterator');
require('../../modules/es6.array.from');
module.exports = require('../../modules/_core').Array.from;
},{"../../modules/_core":79,"../../modules/es6.array.from":145,"../../modules/es6.string.iterator":152}],66:[function(require,module,exports){
require('../../modules/es6.object.create');
var $Object = require('../../modules/_core').Object;
module.exports = function create(P, D) {
return $Object.create(P, D);
};
},{"../../modules/_core":79,"../../modules/es6.object.create":147}],67:[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":79,"../../modules/es6.object.define-property":148}],68:[function(require,module,exports){
require('../../modules/es6.object.set-prototype-of');
module.exports = require('../../modules/_core').Object.setPrototypeOf;
},{"../../modules/_core":79,"../../modules/es6.object.set-prototype-of":149}],69:[function(require,module,exports){
require('../modules/es6.object.to-string');
require('../modules/es6.string.iterator');
require('../modules/web.dom.iterable');
require('../modules/es6.promise');
require('../modules/es7.promise.finally');
require('../modules/es7.promise.try');
module.exports = require('../modules/_core').Promise;
},{"../modules/_core":79,"../modules/es6.object.to-string":150,"../modules/es6.promise":151,"../modules/es6.string.iterator":152,"../modules/es7.promise.finally":154,"../modules/es7.promise.try":155,"../modules/web.dom.iterable":158}],70:[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":79,"../../modules/es6.object.to-string":150,"../../modules/es6.symbol":153,"../../modules/es7.symbol.async-iterator":156,"../../modules/es7.symbol.observable":157}],71:[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":142,"../../modules/es6.string.iterator":152,"../../modules/web.dom.iterable":158}],72:[function(require,module,exports){
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
},{}],73:[function(require,module,exports){
module.exports = function () { /* empty */ };
},{}],74:[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;
};
},{}],75:[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":99}],76:[function(require,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = require('./_to-iobject');
var toLength = require('./_to-length');
var toAbsoluteIndex = require('./_to-absolute-index');
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf 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-absolute-index":134,"./_to-iobject":136,"./_to-length":137}],77:[function(require,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./_cof');
var TAG = require('./_wks')('toStringTag');
// ES3 wrong here
var 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":78,"./_wks":143}],78:[function(require,module,exports){
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
},{}],79:[function(require,module,exports){
var core = module.exports = { version: '2.5.1' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
},{}],80:[function(require,module,exports){
'use strict';
var $defineProperty = require('./_object-dp');
var createDesc = require('./_property-desc');
module.exports = function (object, index, value) {
if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
},{"./_object-dp":111,"./_property-desc":123}],81:[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":72}],82:[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;
};
},{}],83:[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":88}],84:[function(require,module,exports){
var isObject = require('./_is-object');
var document = require('./_global').document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
},{"./_global":90,"./_is-object":99}],85:[function(require,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],86:[function(require,module,exports){
// all enumerable object keys, includes symbols
var getKeys = require('./_object-keys');
var gOPS = require('./_object-gops');
var pIE = require('./_object-pie');
module.exports = function (it) {
var result = getKeys(it);
var getSymbols = gOPS.f;
if (getSymbols) {
var symbols = getSymbols(it);
var isEnum = pIE.f;
var i = 0;
var key;
while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
} return result;
};
},{"./_object-gops":116,"./_object-keys":119,"./_object-pie":120}],87:[function(require,module,exports){
var global = require('./_global');
var core = require('./_core');
var ctx = require('./_ctx');
var hide = require('./_hide');
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var IS_WRAP = type & $export.W;
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE];
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
var 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":79,"./_ctx":81,"./_global":90,"./_hide":92}],88:[function(require,module,exports){
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
},{}],89:[function(require,module,exports){
var ctx = require('./_ctx');
var call = require('./_iter-call');
var isArrayIter = require('./_is-array-iter');
var anObject = require('./_an-object');
var toLength = require('./_to-length');
var getIterFn = require('./core.get-iterator-method');
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
var f = ctx(fn, that, entries ? 2 : 1);
var index = 0;
var 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":75,"./_ctx":81,"./_is-array-iter":97,"./_iter-call":100,"./_to-length":137,"./core.get-iterator-method":144}],90:[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
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
},{}],91:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
},{}],92:[function(require,module,exports){
var dP = require('./_object-dp');
var 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":83,"./_object-dp":111,"./_property-desc":123}],93:[function(require,module,exports){
var document = require('./_global').document;
module.exports = document && document.documentElement;
},{"./_global":90}],94:[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":83,"./_dom-create":84,"./_fails":88}],95:[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);
};
},{}],96:[function(require,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./_cof');
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./_cof":78}],97:[function(require,module,exports){
// check on default Array iterator
var Iterators = require('./_iterators');
var ITERATOR = require('./_wks')('iterator');
var ArrayProto = Array.prototype;
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"./_iterators":105,"./_wks":143}],98:[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":78}],99:[function(require,module,exports){
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],100:[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":75}],101:[function(require,module,exports){
'use strict';
var create = require('./_object-create');
var descriptor = require('./_property-desc');
var setToStringTag = require('./_set-to-string-tag');
var 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":92,"./_object-create":110,"./_property-desc":123,"./_set-to-string-tag":128,"./_wks":143}],102:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library');
var $export = require('./_export');
var redefine = require('./_redefine');
var hide = require('./_hide');
var has = require('./_has');
var Iterators = require('./_iterators');
var $iterCreate = require('./_iter-create');
var setToStringTag = require('./_set-to-string-tag');
var getPrototypeOf = require('./_object-gpo');
var ITERATOR = require('./_wks')('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var 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';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// 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":87,"./_has":91,"./_hide":92,"./_iter-create":101,"./_iterators":105,"./_library":106,"./_object-gpo":117,"./_redefine":125,"./_set-to-string-tag":128,"./_wks":143}],103:[function(require,module,exports){
var ITERATOR = require('./_wks')('iterator');
var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function () { SAFE_CLOSING = true; };
// eslint-disable-next-line no-throw-literal
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];
var iter = arr[ITERATOR]();
iter.next = function () { return { done: safe = true }; };
arr[ITERATOR] = function () { return iter; };
exec(arr);
} catch (e) { /* empty */ }
return safe;
};
},{"./_wks":143}],104:[function(require,module,exports){
module.exports = function (done, value) {
return { value: value, done: !!done };
};
},{}],105:[function(require,module,exports){
module.exports = {};
},{}],106:[function(require,module,exports){
module.exports = true;
},{}],107:[function(require,module,exports){
var META = require('./_uid')('meta');
var isObject = require('./_is-object');
var has = require('./_has');
var setDesc = require('./_object-dp').f;
var 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":88,"./_has":91,"./_is-object":99,"./_object-dp":111,"./_uid":140}],108:[function(require,module,exports){
var global = require('./_global');
var macrotask = require('./_task').set;
var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var 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;
var 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":78,"./_global":90,"./_task":133}],109:[function(require,module,exports){
'use strict';
// 25.4.1.5 NewPromiseCapability(C)
var aFunction = require('./_a-function');
function PromiseCapability(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);
}
module.exports.f = function (C) {
return new PromiseCapability(C);
};
},{"./_a-function":72}],110:[function(require,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = require('./_an-object');
var dPs = require('./_object-dps');
var enumBugKeys = require('./_enum-bug-keys');
var IE_PROTO = require('./_shared-key')('IE_PROTO');
var Empty = function () { /* empty */ };
var 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');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var 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":75,"./_dom-create":84,"./_enum-bug-keys":85,"./_html":93,"./_object-dps":112,"./_shared-key":129}],111:[function(require,module,exports){
var anObject = require('./_an-object');
var IE8_DOM_DEFINE = require('./_ie8-dom-define');
var toPrimitive = require('./_to-primitive');
var 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":75,"./_descriptors":83,"./_ie8-dom-define":94,"./_to-primitive":139}],112:[function(require,module,exports){
var dP = require('./_object-dp');
var anObject = require('./_an-object');
var getKeys = require('./_object-keys');
module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = getKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"./_an-object":75,"./_descriptors":83,"./_object-dp":111,"./_object-keys":119}],113:[function(require,module,exports){
var pIE = require('./_object-pie');
var createDesc = require('./_property-desc');
var toIObject = require('./_to-iobject');
var toPrimitive = require('./_to-primitive');
var has = require('./_has');
var IE8_DOM_DEFINE = require('./_ie8-dom-define');
var 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":83,"./_has":91,"./_ie8-dom-define":94,"./_object-pie":120,"./_property-desc":123,"./_to-iobject":136,"./_to-primitive":139}],114:[function(require,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = require('./_to-iobject');
var gOPN = require('./_object-gopn').f;
var 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":115,"./_to-iobject":136}],115:[function(require,module,exports){
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = require('./_object-keys-internal');
var hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
},{"./_enum-bug-keys":85,"./_object-keys-internal":118}],116:[function(require,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],117:[function(require,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = require('./_has');
var toObject = require('./_to-object');
var IE_PROTO = require('./_shared-key')('IE_PROTO');
var 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":91,"./_shared-key":129,"./_to-object":138}],118:[function(require,module,exports){
var has = require('./_has');
var toIObject = require('./_to-iobject');
var arrayIndexOf = require('./_array-includes')(false);
var IE_PROTO = require('./_shared-key')('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var 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":76,"./_has":91,"./_shared-key":129,"./_to-iobject":136}],119:[function(require,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = require('./_object-keys-internal');
var enumBugKeys = require('./_enum-bug-keys');
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
},{"./_enum-bug-keys":85,"./_object-keys-internal":118}],120:[function(require,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],121:[function(require,module,exports){
module.exports = function (exec) {
try {
return { e: false, v: exec() };
} catch (e) {
return { e: true, v: e };
}
};
},{}],122:[function(require,module,exports){
var anObject = require('./_an-object');
var isObject = require('./_is-object');
var newPromiseCapability = require('./_new-promise-capability');
module.exports = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
},{"./_an-object":75,"./_is-object":99,"./_new-promise-capability":109}],123:[function(require,module,exports){
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
},{}],124:[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":92}],125:[function(require,module,exports){
module.exports = require('./_hide');
},{"./_hide":92}],126:[function(require,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = require('./_is-object');
var anObject = require('./_an-object');
var check = function (O, proto) {
anObject(O);
if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function (test, buggy, set) {
try {
set = require('./_ctx')(Function.call, require('./_object-gopd').f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch (e) { buggy = true; }
return function setPrototypeOf(O, proto) {
check(O, proto);
if (buggy) O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
},{"./_an-object":75,"./_ctx":81,"./_is-object":99,"./_object-gopd":113}],127:[function(require,module,exports){
'use strict';
var global = require('./_global');
var core = require('./_core');
var dP = require('./_object-dp');
var DESCRIPTORS = require('./_descriptors');
var 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":79,"./_descriptors":83,"./_global":90,"./_object-dp":111,"./_wks":143}],128:[function(require,module,exports){
var def = require('./_object-dp').f;
var has = require('./_has');
var 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":91,"./_object-dp":111,"./_wks":143}],129:[function(require,module,exports){
var shared = require('./_shared')('keys');
var uid = require('./_uid');
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
},{"./_shared":130,"./_uid":140}],130:[function(require,module,exports){
var global = require('./_global');
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
module.exports = function (key) {
return store[key] || (store[key] = {});
};
},{"./_global":90}],131:[function(require,module,exports){
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = require('./_an-object');
var aFunction = require('./_a-function');
var SPECIES = require('./_wks')('species');
module.exports = function (O, D) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
},{"./_a-function":72,"./_an-object":75,"./_wks":143}],132:[function(require,module,exports){
var toInteger = require('./_to-integer');
var defined = require('./_defined');
// true -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
return function (that, pos) {
var s = String(defined(that));
var i = toInteger(pos);
var l = s.length;
var 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":82,"./_to-integer":135}],133:[function(require,module,exports){
var ctx = require('./_ctx');
var invoke = require('./_invoke');
var html = require('./_html');
var cel = require('./_dom-create');
var global = require('./_global');
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
var id = +this;
// eslint-disable-next-line no-prototype-builtins
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 = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func
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));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(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":78,"./_ctx":81,"./_dom-create":84,"./_global":90,"./_html":93,"./_invoke":95}],134:[function(require,module,exports){
var toInteger = require('./_to-integer');
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./_to-integer":135}],135:[function(require,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],136:[function(require,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject');
var defined = require('./_defined');
module.exports = function (it) {
return IObject(defined(it));
};
},{"./_defined":82,"./_iobject":96}],137:[function(require,module,exports){
// 7.1.15 ToLength
var toInteger = require('./_to-integer');
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./_to-integer":135}],138:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./_defined');
module.exports = function (it) {
return Object(defined(it));
};
},{"./_defined":82}],139:[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":99}],140:[function(require,module,exports){
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],141:[function(require,module,exports){
var global = require('./_global');
var core = require('./_core');
var LIBRARY = require('./_library');
var wksExt = require('./_wks-ext');
var 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":79,"./_global":90,"./_library":106,"./_object-dp":111,"./_wks-ext":142}],142:[function(require,module,exports){
exports.f = require('./_wks');
},{"./_wks":143}],143:[function(require,module,exports){
var store = require('./_shared')('wks');
var uid = require('./_uid');
var Symbol = require('./_global').Symbol;
var 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":90,"./_shared":130,"./_uid":140}],144:[function(require,module,exports){
var classof = require('./_classof');
var ITERATOR = require('./_wks')('iterator');
var Iterators = require('./_iterators');
module.exports = require('./_core').getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"./_classof":77,"./_core":79,"./_iterators":105,"./_wks":143}],145:[function(require,module,exports){
'use strict';
var ctx = require('./_ctx');
var $export = require('./_export');
var toObject = require('./_to-object');
var call = require('./_iter-call');
var isArrayIter = require('./_is-array-iter');
var toLength = require('./_to-length');
var createProperty = require('./_create-property');
var getIterFn = require('./core.get-iterator-method');
$export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var index = 0;
var iterFn = getIterFn(O);
var length, result, step, iterator;
if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
},{"./_create-property":80,"./_ctx":81,"./_export":87,"./_is-array-iter":97,"./_iter-call":100,"./_iter-detect":103,"./_to-length":137,"./_to-object":138,"./core.get-iterator-method":144}],146:[function(require,module,exports){
'use strict';
var addToUnscopables = require('./_add-to-unscopables');
var step = require('./_iter-step');
var Iterators = require('./_iterators');
var 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;
var kind = this._k;
var 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":73,"./_iter-define":102,"./_iter-step":104,"./_iterators":105,"./_to-iobject":136}],147:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: require('./_object-create') });
},{"./_export":87,"./_object-create":110}],148:[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":83,"./_export":87,"./_object-dp":111}],149:[function(require,module,exports){
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = require('./_export');
$export($export.S, 'Object', { setPrototypeOf: require('./_set-proto').set });
},{"./_export":87,"./_set-proto":126}],150:[function(require,module,exports){
arguments[4][59][0].apply(exports,arguments)
},{"dup":59}],151:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library');
var global = require('./_global');
var ctx = require('./_ctx');
var classof = require('./_classof');
var $export = require('./_export');
var isObject = require('./_is-object');
var aFunction = require('./_a-function');
var anInstance = require('./_an-instance');
var forOf = require('./_for-of');
var speciesConstructor = require('./_species-constructor');
var task = require('./_task').set;
var microtask = require('./_microtask')();
var newPromiseCapabilityModule = require('./_new-promise-capability');
var perform = require('./_perform');
var promiseResolve = require('./_promise-resolve');
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
var USE_NATIVE = !!function () {
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1);
var 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 isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
if (promise._n) return;
promise._n = true;
var chain = promise._c;
microtask(function () {
var value = promise._v;
var ok = promise._s == 1;
var i = 0;
var run = function (reaction) {
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var 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;
var unhandled = isUnhandled(promise);
var result, handler, console;
if (unhandled) {
result = 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 (unhandled && result.e) throw result.v;
});
};
var isUnhandled = function (promise) {
if (promise._h == 1) return false;
var chain = promise._a || promise._c;
var i = 0;
var 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;
var 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);
}
};
// eslint-disable-next-line no-unused-vars
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);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === $Promise || C === Wrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
}
$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);
var $$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) {
return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
}
});
$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;
var capability = newPromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var values = [];
var index = 0;
var remaining = 1;
forOf(iterable, false, function (promise) {
var $index = index++;
var 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 (result.e) reject(result.v);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var reject = capability.reject;
var result = perform(function () {
forOf(iterable, false, function (promise) {
C.resolve(promise).then(capability.resolve, reject);
});
});
if (result.e) reject(result.v);
return capability.promise;
}
});
},{"./_a-function":72,"./_an-instance":74,"./_classof":77,"./_core":79,"./_ctx":81,"./_export":87,"./_for-of":89,"./_global":90,"./_is-object":99,"./_iter-detect":103,"./_library":106,"./_microtask":108,"./_new-promise-capability":109,"./_perform":121,"./_promise-resolve":122,"./_redefine-all":124,"./_set-species":127,"./_set-to-string-tag":128,"./_species-constructor":131,"./_task":133,"./_wks":143}],152:[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;
var index = this._i;
var 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":102,"./_string-at":132}],153:[function(require,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var global = require('./_global');
var has = require('./_has');
var DESCRIPTORS = require('./_descriptors');
var $export = require('./_export');
var redefine = require('./_redefine');
var META = require('./_meta').KEY;
var $fails = require('./_fails');
var shared = require('./_shared');
var setToStringTag = require('./_set-to-string-tag');
var uid = require('./_uid');
var wks = require('./_wks');
var wksExt = require('./_wks-ext');
var wksDefine = require('./_wks-define');
var enumKeys = require('./_enum-keys');
var isArray = require('./_is-array');
var anObject = require('./_an-object');
var toIObject = require('./_to-iobject');
var toPrimitive = require('./_to-primitive');
var createDesc = require('./_property-desc');
var _create = require('./_object-create');
var gOPNExt = require('./_object-gopn-ext');
var $GOPD = require('./_object-gopd');
var $DP = require('./_object-dp');
var $keys = require('./_object-keys');
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function';
var 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));
var i = 0;
var l = keys.length;
var 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));
var result = [];
var i = 0;
var 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;
var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
var result = [];
var i = 0;
var 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 es6Symbols = (
// 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(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
$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(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
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];
var i = 1;
var 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":75,"./_descriptors":83,"./_enum-keys":86,"./_export":87,"./_fails":88,"./_global":90,"./_has":91,"./_hide":92,"./_is-array":98,"./_library":106,"./_meta":107,"./_object-create":110,"./_object-dp":111,"./_object-gopd":113,"./_object-gopn":115,"./_object-gopn-ext":114,"./_object-gops":116,"./_object-keys":119,"./_object-pie":120,"./_property-desc":123,"./_redefine":125,"./_set-to-string-tag":128,"./_shared":130,"./_to-iobject":136,"./_to-primitive":139,"./_uid":140,"./_wks":143,"./_wks-define":141,"./_wks-ext":142}],154:[function(require,module,exports){
// https://github.com/tc39/proposal-promise-finally
'use strict';
var $export = require('./_export');
var core = require('./_core');
var global = require('./_global');
var speciesConstructor = require('./_species-constructor');
var promiseResolve = require('./_promise-resolve');
$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {
var C = speciesConstructor(this, core.Promise || global.Promise);
var isFunction = typeof onFinally == 'function';
return this.then(
isFunction ? function (x) {
return promiseResolve(C, onFinally()).then(function () { return x; });
} : onFinally,
isFunction ? function (e) {
return promiseResolve(C, onFinally()).then(function () { throw e; });
} : onFinally
);
} });
},{"./_core":79,"./_export":87,"./_global":90,"./_promise-resolve":122,"./_species-constructor":131}],155:[function(require,module,exports){
'use strict';
// https://github.com/tc39/proposal-promise-try
var $export = require('./_export');
var newPromiseCapability = require('./_new-promise-capability');
var perform = require('./_perform');
$export($export.S, 'Promise', { 'try': function (callbackfn) {
var promiseCapability = newPromiseCapability.f(this);
var result = perform(callbackfn);
(result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
return promiseCapability.promise;
} });
},{"./_export":87,"./_new-promise-capability":109,"./_perform":121}],156:[function(require,module,exports){
require('./_wks-define')('asyncIterator');
},{"./_wks-define":141}],157:[function(require,module,exports){
require('./_wks-define')('observable');
},{"./_wks-define":141}],158:[function(require,module,exports){
require('./es6.array.iterator');
var global = require('./_global');
var hide = require('./_hide');
var Iterators = require('./_iterators');
var TO_STRING_TAG = require('./_wks')('toStringTag');
var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
'TextTrackList,TouchList').split(',');
for (var i = 0; i < DOMIterables.length; i++) {
var NAME = DOMIterables[i];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
},{"./_global":90,"./_hide":92,"./_iterators":105,"./_wks":143,"./es6.array.iterator":146}],159:[function(require,module,exports){
arguments[4][72][0].apply(exports,arguments)
},{"dup":72}],160:[function(require,module,exports){
var cof = require('./_cof');
module.exports = function (it, msg) {
if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg);
return +it;
};
},{"./_cof":174}],161:[function(require,module,exports){
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = require('./_wks')('unscopables');
var ArrayProto = Array.prototype;
if (ArrayProto[UNSCOPABLES] == undefined) require('./_hide')(ArrayProto, UNSCOPABLES, {});
module.exports = function (key) {
ArrayProto[UNSCOPABLES][key] = true;
};
},{"./_hide":198,"./_wks":281}],162:[function(require,module,exports){
arguments[4][74][0].apply(exports,arguments)
},{"dup":74}],163:[function(require,module,exports){
arguments[4][75][0].apply(exports,arguments)
},{"./_is-object":207,"dup":75}],164:[function(require,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = require('./_to-object');
var toAbsoluteIndex = require('./_to-absolute-index');
var toLength = require('./_to-length');
module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
var O = toObject(this);
var len = toLength(O.length);
var to = toAbsoluteIndex(target, len);
var from = toAbsoluteIndex(start, len);
var end = arguments.length > 2 ? arguments[2] : undefined;
var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
var inc = 1;
if (from < to && to < from + count) {
inc = -1;
from += count - 1;
to += count - 1;
}
while (count-- > 0) {
if (from in O) O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
},{"./_to-absolute-index":267,"./_to-length":271,"./_to-object":272}],165:[function(require,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = require('./_to-object');
var toAbsoluteIndex = require('./_to-absolute-index');
var toLength = require('./_to-length');
module.exports = function fill(value /* , start = 0, end = @length */) {
var O = toObject(this);
var length = toLength(O.length);
var aLen = arguments.length;
var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length);
var end = aLen > 2 ? arguments[2] : undefined;
var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
while (endPos > index) O[index++] = value;
return O;
};
},{"./_to-absolute-index":267,"./_to-length":271,"./_to-object":272}],166:[function(require,module,exports){
var forOf = require('./_for-of');
module.exports = function (iter, ITERATOR) {
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
},{"./_for-of":195}],167:[function(require,module,exports){
arguments[4][76][0].apply(exports,arguments)
},{"./_to-absolute-index":267,"./_to-iobject":270,"./_to-length":271,"dup":76}],168:[function(require,module,exports){
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = require('./_ctx');
var IObject = require('./_iobject');
var toObject = require('./_to-object');
var toLength = require('./_to-length');
var asc = require('./_array-species-create');
module.exports = function (TYPE, $create) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
var create = $create || asc;
return function ($this, callbackfn, that) {
var O = toObject($this);
var self = IObject(O);
var f = ctx(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var val, res;
for (;length > index; index++) if (NO_HOLES || index in self) {
val = self[index];
res = f(val, index, O);
if (TYPE) {
if (IS_MAP) result[index] = res; // map
else if (res) switch (TYPE) {
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
},{"./_array-species-create":171,"./_ctx":181,"./_iobject":203,"./_to-length":271,"./_to-object":272}],169:[function(require,module,exports){
var aFunction = require('./_a-function');
var toObject = require('./_to-object');
var IObject = require('./_iobject');
var toLength = require('./_to-length');
module.exports = function (that, callbackfn, aLen, memo, isRight) {
aFunction(callbackfn);
var O = toObject(that);
var self = IObject(O);
var length = toLength(O.length);
var index = isRight ? length - 1 : 0;
var i = isRight ? -1 : 1;
if (aLen < 2) for (;;) {
if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
if (isRight ? index < 0 : length <= index) {
throw TypeError('Reduce of empty array with no initial value');
}
}
for (;isRight ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
},{"./_a-function":159,"./_iobject":203,"./_to-length":271,"./_to-object":272}],170:[function(require,module,exports){
var isObject = require('./_is-object');
var isArray = require('./_is-array');
var SPECIES = require('./_wks')('species');
module.exports = function (original) {
var C;
if (isArray(original)) {
C = original.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return C === undefined ? Array : C;
};
},{"./_is-array":205,"./_is-object":207,"./_wks":281}],171:[function(require,module,exports){
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = require('./_array-species-constructor');
module.exports = function (original, length) {
return new (speciesConstructor(original))(length);
};
},{"./_array-species-constructor":170}],172:[function(require,module,exports){
'use strict';
var aFunction = require('./_a-function');
var isObject = require('./_is-object');
var invoke = require('./_invoke');
var arraySlice = [].slice;
var factories = {};
var construct = function (F, len, args) {
if (!(len in factories)) {
for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']';
// eslint-disable-next-line no-new-func
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /* , ...args */) {
var fn = aFunction(this);
var partArgs = arraySlice.call(arguments, 1);
var bound = function (/* args... */) {
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if (isObject(fn.prototype)) bound.prototype = fn.prototype;
return bound;
};
},{"./_a-function":159,"./_invoke":202,"./_is-object":207}],173:[function(require,module,exports){
arguments[4][77][0].apply(exports,arguments)
},{"./_cof":174,"./_wks":281,"dup":77}],174:[function(require,module,exports){
arguments[4][78][0].apply(exports,arguments)
},{"dup":78}],175:[function(require,module,exports){
'use strict';
var dP = require('./_object-dp').f;
var create = require('./_object-create');
var redefineAll = require('./_redefine-all');
var ctx = require('./_ctx');
var anInstance = require('./_an-instance');
var forOf = require('./_for-of');
var $iterDefine = require('./_iter-define');
var step = require('./_iter-step');
var setSpecies = require('./_set-species');
var DESCRIPTORS = require('./_descriptors');
var fastKey = require('./_meta').fastKey;
var validate = require('./_validate-collection');
var SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function (that, key) {
// fast case
var index = fastKey(key);
var entry;
if (index !== 'F') return that._i[index];
// frozen object case
for (entry = that._f; entry; entry = entry.n) {
if (entry.k == key) return entry;
}
};
module.exports = {
getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear() {
for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
entry.r = true;
if (entry.p) entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function (key) {
var that = validate(this, NAME);
var entry = getEntry(that, key);
if (entry) {
var next = entry.n;
var prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if (prev) prev.n = next;
if (next) next.p = prev;
if (that._f == entry) that._f = next;
if (that._l == entry) that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /* , that = undefined */) {
validate(this, NAME);
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
var entry;
while (entry = entry ? entry.n : this._f) {
f(entry.v, entry.k, this);
// revert to the last existing entry
while (entry && entry.r) entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key) {
return !!getEntry(validate(this, NAME), key);
}
});
if (DESCRIPTORS) dP(C.prototype, 'size', {
get: function () {
return validate(this, NAME)[SIZE];
}
});
return C;
},
def: function (that, key, value) {
var entry = getEntry(that, key);
var prev, index;
// change existing entry
if (entry) {
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if (!that._f) that._f = entry;
if (prev) prev.n = entry;
that[SIZE]++;
// add to index
if (index !== 'F') that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function (C, NAME, IS_MAP) {
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function (iterated, kind) {
this._t = validate(iterated, NAME); // target
this._k = kind; // kind
this._l = undefined; // previous
}, function () {
var that = this;
var kind = that._k;
var entry = that._l;
// revert to the last existing entry
while (entry && entry.r) entry = entry.p;
// get next entry
if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if (kind == 'keys') return step(0, entry.k);
if (kind == 'values') return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
},{"./_an-instance":162,"./_ctx":181,"./_descriptors":185,"./_for-of":195,"./_iter-define":211,"./_iter-step":213,"./_meta":221,"./_object-create":226,"./_object-dp":227,"./_redefine-all":246,"./_set-species":253,"./_validate-collection":278}],176:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = require('./_classof');
var from = require('./_array-from-iterable');
module.exports = function (NAME) {
return function toJSON() {
if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
},{"./_array-from-iterable":166,"./_classof":173}],177:[function(require,module,exports){
'use strict';
var redefineAll = require('./_redefine-all');
var getWeak = require('./_meta').getWeak;
var anObject = require('./_an-object');
var isObject = require('./_is-object');
var anInstance = require('./_an-instance');
var forOf = require('./_for-of');
var createArrayMethod = require('./_array-methods');
var $has = require('./_has');
var validate = require('./_validate-collection');
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function (that) {
return that._l || (that._l = new UncaughtFrozenStore());
};
var UncaughtFrozenStore = function () {
this.a = [];
};
var findUncaughtFrozen = function (store, key) {
return arrayFind(store.a, function (it) {
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function (key) {
var entry = findUncaughtFrozen(this, key);
if (entry) return entry[1];
},
has: function (key) {
return !!findUncaughtFrozen(this, key);
},
set: function (key, value) {
var entry = findUncaughtFrozen(this, key);
if (entry) entry[1] = value;
else this.a.push([key, value]);
},
'delete': function (key) {
var index = arrayFindIndex(this.a, function (it) {
return it[0] === key;
});
if (~index) this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function (key) {
if (!isObject(key)) return false;
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key) {
if (!isObject(key)) return false;
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function (that, key, value) {
var data = getWeak(anObject(key), true);
if (data === true) uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
},{"./_an-instance":162,"./_an-object":163,"./_array-methods":168,"./_for-of":195,"./_has":197,"./_is-object":207,"./_meta":221,"./_redefine-all":246,"./_validate-collection":278}],178:[function(require,module,exports){
'use strict';
var global = require('./_global');
var $export = require('./_export');
var redefine = require('./_redefine');
var redefineAll = require('./_redefine-all');
var meta = require('./_meta');
var forOf = require('./_for-of');
var anInstance = require('./_an-instance');
var isObject = require('./_is-object');
var fails = require('./_fails');
var $iterDetect = require('./_iter-detect');
var setToStringTag = require('./_set-to-string-tag');
var inheritIfRequired = require('./_inherit-if-required');
module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
var Base = global[NAME];
var C = Base;
var ADDER = IS_MAP ? 'set' : 'add';
var proto = C && C.prototype;
var O = {};
var fixMethod = function (KEY) {
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function (a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a) {
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
new C().entries().next();
}))) {
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C();
// early implementations not supports chaining
var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });
// most early implementations doesn't supports iterables, most modern - not close it correctly
var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
var BUGGY_ZERO = !IS_WEAK && fails(function () {
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C();
var index = 5;
while (index--) $instance[ADDER](index, index);
return !$instance.has(-0);
});
if (!ACCEPT_ITERABLES) {
C = wrapper(function (target, iterable) {
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base(), target, C);
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
// weak collections should not contains .clear method
if (IS_WEAK && proto.clear) delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
return C;
};
},{"./_an-instance":162,"./_export":189,"./_fails":191,"./_for-of":195,"./_global":196,"./_inherit-if-required":201,"./_is-object":207,"./_iter-detect":212,"./_meta":221,"./_redefine":247,"./_redefine-all":246,"./_set-to-string-tag":254}],179:[function(require,module,exports){
arguments[4][79][0].apply(exports,arguments)
},{"dup":79}],180:[function(require,module,exports){
arguments[4][80][0].apply(exports,arguments)
},{"./_object-dp":227,"./_property-desc":245,"dup":80}],181:[function(require,module,exports){
arguments[4][81][0].apply(exports,arguments)
},{"./_a-function":159,"dup":81}],182:[function(require,module,exports){
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var fails = require('./_fails');
var getTime = Date.prototype.getTime;
var $toISOString = Date.prototype.toISOString;
var lz = function (num) {
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
module.exports = (fails(function () {
return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
}) || !fails(function () {
$toISOString.call(new Date(NaN));
})) ? function toISOString() {
if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value');
var d = this;
var y = d.getUTCFullYear();
var m = d.getUTCMilliseconds();
var s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
} : $toISOString;
},{"./_fails":191}],183:[function(require,module,exports){
'use strict';
var anObject = require('./_an-object');
var toPrimitive = require('./_to-primitive');
var NUMBER = 'number';
module.exports = function (hint) {
if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
},{"./_an-object":163,"./_to-primitive":273}],184:[function(require,module,exports){
arguments[4][82][0].apply(exports,arguments)
},{"dup":82}],185:[function(require,module,exports){
arguments[4][83][0].apply(exports,arguments)
},{"./_fails":191,"dup":83}],186:[function(require,module,exports){
arguments[4][84][0].apply(exports,arguments)
},{"./_global":196,"./_is-object":207,"dup":84}],187:[function(require,module,exports){
arguments[4][85][0].apply(exports,arguments)
},{"dup":85}],188:[function(require,module,exports){
arguments[4][86][0].apply(exports,arguments)
},{"./_object-gops":233,"./_object-keys":236,"./_object-pie":237,"dup":86}],189:[function(require,module,exports){
var global = require('./_global');
var core = require('./_core');
var hide = require('./_hide');
var redefine = require('./_redefine');
var ctx = require('./_ctx');
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
var key, own, out, exp;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if (target) redefine(target, key, out, type & $export.U);
// export
if (exports[key] != out) hide(exports, key, exp);
if (IS_PROTO && expProto[key] != out) expProto[key] = out;
}
};
global.core = core;
// 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":179,"./_ctx":181,"./_global":196,"./_hide":198,"./_redefine":247}],190:[function(require,module,exports){
var MATCH = require('./_wks')('match');
module.exports = function (KEY) {
var re = /./;
try {
'/./'[KEY](re);
} catch (e) {
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch (f) { /* empty */ }
} return true;
};
},{"./_wks":281}],191:[function(require,module,exports){
arguments[4][88][0].apply(exports,arguments)
},{"dup":88}],192:[function(require,module,exports){
'use strict';
var hide = require('./_hide');
var redefine = require('./_redefine');
var fails = require('./_fails');
var defined = require('./_defined');
var wks = require('./_wks');
module.exports = function (KEY, length, exec) {
var SYMBOL = wks(KEY);
var fns = exec(defined, SYMBOL, ''[KEY]);
var strfn = fns[0];
var rxfn = fns[1];
if (fails(function () {
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
})) {
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function (string, arg) { return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function (string) { return rxfn.call(string, this); }
);
}
};
},{"./_defined":184,"./_fails":191,"./_hide":198,"./_redefine":247,"./_wks":281}],193:[function(require,module,exports){
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = require('./_an-object');
module.exports = function () {
var that = anObject(this);
var result = '';
if (that.global) result += 'g';
if (that.ignoreCase) result += 'i';
if (that.multiline) result += 'm';
if (that.unicode) result += 'u';
if (that.sticky) result += 'y';
return result;
};
},{"./_an-object":163}],194:[function(require,module,exports){
'use strict';
// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
var isArray = require('./_is-array');
var isObject = require('./_is-object');
var toLength = require('./_to-length');
var ctx = require('./_ctx');
var IS_CONCAT_SPREADABLE = require('./_wks')('isConcatSpreadable');
function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) {
var targetIndex = start;
var sourceIndex = 0;
var mapFn = mapper ? ctx(mapper, thisArg, 3) : false;
var element, spreadable;
while (sourceIndex < sourceLen) {
if (sourceIndex in source) {
element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
spreadable = false;
if (isObject(element)) {
spreadable = element[IS_CONCAT_SPREADABLE];
spreadable = spreadable !== undefined ? !!spreadable : isArray(element);
}
if (spreadable && depth > 0) {
targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1;
} else {
if (targetIndex >= 0x1fffffffffffff) throw TypeError();
target[targetIndex] = element;
}
targetIndex++;
}
sourceIndex++;
}
return targetIndex;
}
module.exports = flattenIntoArray;
},{"./_ctx":181,"./_is-array":205,"./_is-object":207,"./_to-length":271,"./_wks":281}],195:[function(require,module,exports){
arguments[4][89][0].apply(exports,arguments)
},{"./_an-object":163,"./_ctx":181,"./_is-array-iter":204,"./_iter-call":209,"./_to-length":271,"./core.get-iterator-method":282,"dup":89}],196:[function(require,module,exports){
arguments[4][90][0].apply(exports,arguments)
},{"dup":90}],197:[function(require,module,exports){
arguments[4][91][0].apply(exports,arguments)
},{"dup":91}],198:[function(require,module,exports){
arguments[4][92][0].apply(exports,arguments)
},{"./_descriptors":185,"./_object-dp":227,"./_property-desc":245,"dup":92}],199:[function(require,module,exports){
arguments[4][93][0].apply(exports,arguments)
},{"./_global":196,"dup":93}],200:[function(require,module,exports){
arguments[4][94][0].apply(exports,arguments)
},{"./_descriptors":185,"./_dom-create":186,"./_fails":191,"dup":94}],201:[function(require,module,exports){
var isObject = require('./_is-object');
var setPrototypeOf = require('./_set-proto').set;
module.exports = function (that, target, C) {
var S = target.constructor;
var P;
if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) {
setPrototypeOf(that, P);
} return that;
};
},{"./_is-object":207,"./_set-proto":252}],202:[function(require,module,exports){
arguments[4][95][0].apply(exports,arguments)
},{"dup":95}],203:[function(require,module,exports){
arguments[4][96][0].apply(exports,arguments)
},{"./_cof":174,"dup":96}],204:[function(require,module,exports){
arguments[4][97][0].apply(exports,arguments)
},{"./_iterators":214,"./_wks":281,"dup":97}],205:[function(require,module,exports){
arguments[4][98][0].apply(exports,arguments)
},{"./_cof":174,"dup":98}],206:[function(require,module,exports){
// 20.1.2.3 Number.isInteger(number)
var isObject = require('./_is-object');
var floor = Math.floor;
module.exports = function isInteger(it) {
return !isObject(it) && isFinite(it) && floor(it) === it;
};
},{"./_is-object":207}],207:[function(require,module,exports){
arguments[4][99][0].apply(exports,arguments)
},{"dup":99}],208:[function(require,module,exports){
// 7.2.8 IsRegExp(argument)
var isObject = require('./_is-object');
var cof = require('./_cof');
var MATCH = require('./_wks')('match');
module.exports = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
},{"./_cof":174,"./_is-object":207,"./_wks":281}],209:[function(require,module,exports){
arguments[4][100][0].apply(exports,arguments)
},{"./_an-object":163,"dup":100}],210:[function(require,module,exports){
arguments[4][101][0].apply(exports,arguments)
},{"./_hide":198,"./_object-create":226,"./_property-desc":245,"./_set-to-string-tag":254,"./_wks":281,"dup":101}],211:[function(require,module,exports){
arguments[4][102][0].apply(exports,arguments)
},{"./_export":189,"./_has":197,"./_hide":198,"./_iter-create":210,"./_iterators":214,"./_library":215,"./_object-gpo":234,"./_redefine":247,"./_set-to-string-tag":254,"./_wks":281,"dup":102}],212:[function(require,module,exports){
arguments[4][103][0].apply(exports,arguments)
},{"./_wks":281,"dup":103}],213:[function(require,module,exports){
arguments[4][104][0].apply(exports,arguments)
},{"dup":104}],214:[function(require,module,exports){
arguments[4][105][0].apply(exports,arguments)
},{"dup":105}],215:[function(require,module,exports){
module.exports = false;
},{}],216:[function(require,module,exports){
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x) {
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
},{}],217:[function(require,module,exports){
// 20.2.2.16 Math.fround(x)
var sign = require('./_math-sign');
var pow = Math.pow;
var EPSILON = pow(2, -52);
var EPSILON32 = pow(2, -23);
var MAX32 = pow(2, 127) * (2 - EPSILON32);
var MIN32 = pow(2, -126);
var roundTiesToEven = function (n) {
return n + 1 / EPSILON - 1 / EPSILON;
};
module.exports = Math.fround || function fround(x) {
var $abs = Math.abs(x);
var $sign = sign(x);
var a, result;
if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
// eslint-disable-next-line no-self-compare
if (result > MAX32 || result != result) return $sign * Infinity;
return $sign * result;
};
},{"./_math-sign":220}],218:[function(require,module,exports){
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x) {
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
},{}],219:[function(require,module,exports){
// https://rwaldron.github.io/proposal-math-extensions/
module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) {
if (
arguments.length === 0
// eslint-disable-next-line no-self-compare
|| x != x
// eslint-disable-next-line no-self-compare
|| inLow != inLow
// eslint-disable-next-line no-self-compare
|| inHigh != inHigh
// eslint-disable-next-line no-self-compare
|| outLow != outLow
// eslint-disable-next-line no-self-compare
|| outHigh != outHigh
) return NaN;
if (x === Infinity || x === -Infinity) return x;
return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow;
};
},{}],220:[function(require,module,exports){
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x) {
// eslint-disable-next-line no-self-compare
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
},{}],221:[function(require,module,exports){
arguments[4][107][0].apply(exports,arguments)
},{"./_fails":191,"./_has":197,"./_is-object":207,"./_object-dp":227,"./_uid":277,"dup":107}],222:[function(require,module,exports){
var Map = require('./es6.map');
var $export = require('./_export');
var shared = require('./_shared')('metadata');
var store = shared.store || (shared.store = new (require('./es6.weak-map'))());
var getOrCreateMetadataMap = function (target, targetKey, create) {
var targetMetadata = store.get(target);
if (!targetMetadata) {
if (!create) return undefined;
store.set(target, targetMetadata = new Map());
}
var keyMetadata = targetMetadata.get(targetKey);
if (!keyMetadata) {
if (!create) return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map());
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function (MetadataKey, O, P) {
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function (MetadataKey, O, P) {
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) {
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function (target, targetKey) {
var metadataMap = getOrCreateMetadataMap(target, targetKey, false);
var keys = [];
if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); });
return keys;
};
var toMetaKey = function (it) {
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function (O) {
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
},{"./_export":189,"./_shared":256,"./es6.map":313,"./es6.weak-map":419}],223:[function(require,module,exports){
arguments[4][108][0].apply(exports,arguments)
},{"./_cof":174,"./_global":196,"./_task":266,"dup":108}],224:[function(require,module,exports){
arguments[4][109][0].apply(exports,arguments)
},{"./_a-function":159,"dup":109}],225:[function(require,module,exports){
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = require('./_object-keys');
var gOPS = require('./_object-gops');
var pIE = require('./_object-pie');
var toObject = require('./_to-object');
var IObject = require('./_iobject');
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || require('./_fails')(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
} return T;
} : $assign;
},{"./_fails":191,"./_iobject":203,"./_object-gops":233,"./_object-keys":236,"./_object-pie":237,"./_to-object":272}],226:[function(require,module,exports){
arguments[4][110][0].apply(exports,arguments)
},{"./_an-object":163,"./_dom-create":186,"./_enum-bug-keys":187,"./_html":199,"./_object-dps":228,"./_shared-key":255,"dup":110}],227:[function(require,module,exports){
arguments[4][111][0].apply(exports,arguments)
},{"./_an-object":163,"./_descriptors":185,"./_ie8-dom-define":200,"./_to-primitive":273,"dup":111}],228:[function(require,module,exports){
arguments[4][112][0].apply(exports,arguments)
},{"./_an-object":163,"./_descriptors":185,"./_object-dp":227,"./_object-keys":236,"dup":112}],229:[function(require,module,exports){
'use strict';
// Forced replacement prototype accessors methods
module.exports = require('./_library') || !require('./_fails')(function () {
var K = Math.random();
// In FF throws only define methods
// eslint-disable-next-line no-undef, no-useless-call
__defineSetter__.call(null, K, function () { /* empty */ });
delete require('./_global')[K];
});
},{"./_fails":191,"./_global":196,"./_library":215}],230:[function(require,module,exports){
arguments[4][113][0].apply(exports,arguments)
},{"./_descriptors":185,"./_has":197,"./_ie8-dom-define":200,"./_object-pie":237,"./_property-desc":245,"./_to-iobject":270,"./_to-primitive":273,"dup":113}],231:[function(require,module,exports){
arguments[4][114][0].apply(exports,arguments)
},{"./_object-gopn":232,"./_to-iobject":270,"dup":114}],232:[function(require,module,exports){
arguments[4][115][0].apply(exports,arguments)
},{"./_enum-bug-keys":187,"./_object-keys-internal":235,"dup":115}],233:[function(require,module,exports){
arguments[4][116][0].apply(exports,arguments)
},{"dup":116}],234:[function(require,module,exports){
arguments[4][117][0].apply(exports,arguments)
},{"./_has":197,"./_shared-key":255,"./_to-object":272,"dup":117}],235:[function(require,module,exports){
arguments[4][118][0].apply(exports,arguments)
},{"./_array-includes":167,"./_has":197,"./_shared-key":255,"./_to-iobject":270,"dup":118}],236:[function(require,module,exports){
arguments[4][119][0].apply(exports,arguments)
},{"./_enum-bug-keys":187,"./_object-keys-internal":235,"dup":119}],237:[function(require,module,exports){
arguments[4][120][0].apply(exports,arguments)
},{"dup":120}],238:[function(require,module,exports){
// most Object methods by ES6 should accept primitives
var $export = require('./_export');
var core = require('./_core');
var fails = require('./_fails');
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
},{"./_core":179,"./_export":189,"./_fails":191}],239:[function(require,module,exports){
var getKeys = require('./_object-keys');
var toIObject = require('./_to-iobject');
var isEnum = require('./_object-pie').f;
module.exports = function (isEntries) {
return function (it) {
var O = toIObject(it);
var keys = getKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) if (isEnum.call(O, key = keys[i++])) {
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
},{"./_object-keys":236,"./_object-pie":237,"./_to-iobject":270}],240:[function(require,module,exports){
// all object keys, includes non-enumerable and symbols
var gOPN = require('./_object-gopn');
var gOPS = require('./_object-gops');
var anObject = require('./_an-object');
var Reflect = require('./_global').Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) {
var keys = gOPN.f(anObject(it));
var getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
},{"./_an-object":163,"./_global":196,"./_object-gopn":232,"./_object-gops":233}],241:[function(require,module,exports){
var $parseFloat = require('./_global').parseFloat;
var $trim = require('./_string-trim').trim;
module.exports = 1 / $parseFloat(require('./_string-ws') + '-0') !== -Infinity ? function parseFloat(str) {
var string = $trim(String(str), 3);
var result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
},{"./_global":196,"./_string-trim":264,"./_string-ws":265}],242:[function(require,module,exports){
var $parseInt = require('./_global').parseInt;
var $trim = require('./_string-trim').trim;
var ws = require('./_string-ws');
var hex = /^[-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) {
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
},{"./_global":196,"./_string-trim":264,"./_string-ws":265}],243:[function(require,module,exports){
arguments[4][121][0].apply(exports,arguments)
},{"dup":121}],244:[function(require,module,exports){
arguments[4][122][0].apply(exports,arguments)
},{"./_an-object":163,"./_is-object":207,"./_new-promise-capability":224,"dup":122}],245:[function(require,module,exports){
arguments[4][123][0].apply(exports,arguments)
},{"dup":123}],246:[function(require,module,exports){
var redefine = require('./_redefine');
module.exports = function (target, src, safe) {
for (var key in src) redefine(target, key, src[key], safe);
return target;
};
},{"./_redefine":247}],247:[function(require,module,exports){
var global = require('./_global');
var hide = require('./_hide');
var has = require('./_has');
var SRC = require('./_uid')('src');
var TO_STRING = 'toString';
var $toString = Function[TO_STRING];
var TPL = ('' + $toString).split(TO_STRING);
require('./_core').inspectSource = function (it) {
return $toString.call(it);
};
(module.exports = function (O, key, val, safe) {
var isFunction = typeof val == 'function';
if (isFunction) has(val, 'name') || hide(val, 'name', key);
if (O[key] === val) return;
if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if (O === global) {
O[key] = val;
} else if (!safe) {
delete O[key];
hide(O, key, val);
} else if (O[key]) {
O[key] = val;
} else {
hide(O, key, val);
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString() {
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
},{"./_core":179,"./_global":196,"./_has":197,"./_hide":198,"./_uid":277}],248:[function(require,module,exports){
module.exports = function (regExp, replace) {
var replacer = replace === Object(replace) ? function (part) {
return replace[part];
} : replace;
return function (it) {
return String(it).replace(regExp, replacer);
};
};
},{}],249:[function(require,module,exports){
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y) {
// eslint-disable-next-line no-self-compare
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
},{}],250:[function(require,module,exports){
'use strict';
// https://tc39.github.io/proposal-setmap-offrom/
var $export = require('./_export');
var aFunction = require('./_a-function');
var ctx = require('./_ctx');
var forOf = require('./_for-of');
module.exports = function (COLLECTION) {
$export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) {
var mapFn = arguments[1];
var mapping, A, n, cb;
aFunction(this);
mapping = mapFn !== undefined;
if (mapping) aFunction(mapFn);
if (source == undefined) return new this();
A = [];
if (mapping) {
n = 0;
cb = ctx(mapFn, arguments[2], 2);
forOf(source, false, function (nextItem) {
A.push(cb(nextItem, n++));
});
} else {
forOf(source, false, A.push, A);
}
return new this(A);
} });
};
},{"./_a-function":159,"./_ctx":181,"./_export":189,"./_for-of":195}],251:[function(require,module,exports){
'use strict';
// https://tc39.github.io/proposal-setmap-offrom/
var $export = require('./_export');
module.exports = function (COLLECTION) {
$export($export.S, COLLECTION, { of: function of() {
var length = arguments.length;
var A = Array(length);
while (length--) A[length] = arguments[length];
return new this(A);
} });
};
},{"./_export":189}],252:[function(require,module,exports){
arguments[4][126][0].apply(exports,arguments)
},{"./_an-object":163,"./_ctx":181,"./_is-object":207,"./_object-gopd":230,"dup":126}],253:[function(require,module,exports){
'use strict';
var global = require('./_global');
var dP = require('./_object-dp');
var DESCRIPTORS = require('./_descriptors');
var SPECIES = require('./_wks')('species');
module.exports = function (KEY) {
var C = global[KEY];
if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
configurable: true,
get: function () { return this; }
});
};
},{"./_descriptors":185,"./_global":196,"./_object-dp":227,"./_wks":281}],254:[function(require,module,exports){
arguments[4][128][0].apply(exports,arguments)
},{"./_has":197,"./_object-dp":227,"./_wks":281,"dup":128}],255:[function(require,module,exports){
arguments[4][129][0].apply(exports,arguments)
},{"./_shared":256,"./_uid":277,"dup":129}],256:[function(require,module,exports){
arguments[4][130][0].apply(exports,arguments)
},{"./_global":196,"dup":130}],257:[function(require,module,exports){
arguments[4][131][0].apply(exports,arguments)
},{"./_a-function":159,"./_an-object":163,"./_wks":281,"dup":131}],258:[function(require,module,exports){
'use strict';
var fails = require('./_fails');
module.exports = function (method, arg) {
return !!method && fails(function () {
// eslint-disable-next-line no-useless-call
arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null);
});
};
},{"./_fails":191}],259:[function(require,module,exports){
arguments[4][132][0].apply(exports,arguments)
},{"./_defined":184,"./_to-integer":269,"dup":132}],260:[function(require,module,exports){
// helper for String#{startsWith, endsWith, includes}
var isRegExp = require('./_is-regexp');
var defined = require('./_defined');
module.exports = function (that, searchString, NAME) {
if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
},{"./_defined":184,"./_is-regexp":208}],261:[function(require,module,exports){
var $export = require('./_export');
var fails = require('./_fails');
var defined = require('./_defined');
var quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function (string, tag, attribute, value) {
var S = String(defined(string));
var p1 = '<' + tag;
if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '' + tag + '>';
};
module.exports = function (NAME, exec) {
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function () {
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
},{"./_defined":184,"./_export":189,"./_fails":191}],262:[function(require,module,exports){
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = require('./_to-length');
var repeat = require('./_string-repeat');
var defined = require('./_defined');
module.exports = function (that, maxLength, fillString, left) {
var S = String(defined(that));
var stringLength = S.length;
var fillStr = fillString === undefined ? ' ' : String(fillString);
var intMaxLength = toLength(maxLength);
if (intMaxLength <= stringLength || fillStr == '') return S;
var fillLen = intMaxLength - stringLength;
var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
},{"./_defined":184,"./_string-repeat":263,"./_to-length":271}],263:[function(require,module,exports){
'use strict';
var toInteger = require('./_to-integer');
var defined = require('./_defined');
module.exports = function repeat(count) {
var str = String(defined(this));
var res = '';
var n = toInteger(count);
if (n < 0 || n == Infinity) throw RangeError("Count can't be negative");
for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str;
return res;
};
},{"./_defined":184,"./_to-integer":269}],264:[function(require,module,exports){
var $export = require('./_export');
var defined = require('./_defined');
var fails = require('./_fails');
var spaces = require('./_string-ws');
var space = '[' + spaces + ']';
var non = '\u200b\u0085';
var ltrim = RegExp('^' + space + space + '*');
var rtrim = RegExp(space + space + '*$');
var exporter = function (KEY, exec, ALIAS) {
var exp = {};
var FORCE = fails(function () {
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if (ALIAS) exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function (string, TYPE) {
string = String(defined(string));
if (TYPE & 1) string = string.replace(ltrim, '');
if (TYPE & 2) string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
},{"./_defined":184,"./_export":189,"./_fails":191,"./_string-ws":265}],265:[function(require,module,exports){
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
},{}],266:[function(require,module,exports){
arguments[4][133][0].apply(exports,arguments)
},{"./_cof":174,"./_ctx":181,"./_dom-create":186,"./_global":196,"./_html":199,"./_invoke":202,"dup":133}],267:[function(require,module,exports){
arguments[4][134][0].apply(exports,arguments)
},{"./_to-integer":269,"dup":134}],268:[function(require,module,exports){
// https://tc39.github.io/ecma262/#sec-toindex
var toInteger = require('./_to-integer');
var toLength = require('./_to-length');
module.exports = function (it) {
if (it === undefined) return 0;
var number = toInteger(it);
var length = toLength(number);
if (number !== length) throw RangeError('Wrong length!');
return length;
};
},{"./_to-integer":269,"./_to-length":271}],269:[function(require,module,exports){
arguments[4][135][0].apply(exports,arguments)
},{"dup":135}],270:[function(require,module,exports){
arguments[4][136][0].apply(exports,arguments)
},{"./_defined":184,"./_iobject":203,"dup":136}],271:[function(require,module,exports){
arguments[4][137][0].apply(exports,arguments)
},{"./_to-integer":269,"dup":137}],272:[function(require,module,exports){
arguments[4][138][0].apply(exports,arguments)
},{"./_defined":184,"dup":138}],273:[function(require,module,exports){
arguments[4][139][0].apply(exports,arguments)
},{"./_is-object":207,"dup":139}],274:[function(require,module,exports){
'use strict';
if (require('./_descriptors')) {
var LIBRARY = require('./_library');
var global = require('./_global');
var fails = require('./_fails');
var $export = require('./_export');
var $typed = require('./_typed');
var $buffer = require('./_typed-buffer');
var ctx = require('./_ctx');
var anInstance = require('./_an-instance');
var propertyDesc = require('./_property-desc');
var hide = require('./_hide');
var redefineAll = require('./_redefine-all');
var toInteger = require('./_to-integer');
var toLength = require('./_to-length');
var toIndex = require('./_to-index');
var toAbsoluteIndex = require('./_to-absolute-index');
var toPrimitive = require('./_to-primitive');
var has = require('./_has');
var classof = require('./_classof');
var isObject = require('./_is-object');
var toObject = require('./_to-object');
var isArrayIter = require('./_is-array-iter');
var create = require('./_object-create');
var getPrototypeOf = require('./_object-gpo');
var gOPN = require('./_object-gopn').f;
var getIterFn = require('./core.get-iterator-method');
var uid = require('./_uid');
var wks = require('./_wks');
var createArrayMethod = require('./_array-methods');
var createArrayIncludes = require('./_array-includes');
var speciesConstructor = require('./_species-constructor');
var ArrayIterators = require('./es6.array.iterator');
var Iterators = require('./_iterators');
var $iterDetect = require('./_iter-detect');
var setSpecies = require('./_set-species');
var arrayFill = require('./_array-fill');
var arrayCopyWithin = require('./_array-copy-within');
var $DP = require('./_object-dp');
var $GOPD = require('./_object-gopd');
var dP = $DP.f;
var gOPD = $GOPD.f;
var RangeError = global.RangeError;
var TypeError = global.TypeError;
var Uint8Array = global.Uint8Array;
var ARRAY_BUFFER = 'ArrayBuffer';
var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER;
var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
var PROTOTYPE = 'prototype';
var ArrayProto = Array[PROTOTYPE];
var $ArrayBuffer = $buffer.ArrayBuffer;
var $DataView = $buffer.DataView;
var arrayForEach = createArrayMethod(0);
var arrayFilter = createArrayMethod(2);
var arraySome = createArrayMethod(3);
var arrayEvery = createArrayMethod(4);
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var arrayIncludes = createArrayIncludes(true);
var arrayIndexOf = createArrayIncludes(false);
var arrayValues = ArrayIterators.values;
var arrayKeys = ArrayIterators.keys;
var arrayEntries = ArrayIterators.entries;
var arrayLastIndexOf = ArrayProto.lastIndexOf;
var arrayReduce = ArrayProto.reduce;
var arrayReduceRight = ArrayProto.reduceRight;
var arrayJoin = ArrayProto.join;
var arraySort = ArrayProto.sort;
var arraySlice = ArrayProto.slice;
var arrayToString = ArrayProto.toString;
var arrayToLocaleString = ArrayProto.toLocaleString;
var ITERATOR = wks('iterator');
var TAG = wks('toStringTag');
var TYPED_CONSTRUCTOR = uid('typed_constructor');
var DEF_CONSTRUCTOR = uid('def_constructor');
var ALL_CONSTRUCTORS = $typed.CONSTR;
var TYPED_ARRAY = $typed.TYPED;
var VIEW = $typed.VIEW;
var WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function (O, length) {
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function () {
// eslint-disable-next-line no-undef
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () {
new Uint8Array(1).set({});
});
var toOffset = function (it, BYTES) {
var offset = toInteger(it);
if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!');
return offset;
};
var validate = function (it) {
if (isObject(it) && TYPED_ARRAY in it) return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function (C, length) {
if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) {
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function (O, list) {
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function (C, list) {
var index = 0;
var length = list.length;
var result = allocate(C, length);
while (length > index) result[index] = list[index++];
return result;
};
var addGetter = function (it, key, internal) {
dP(it, key, { get: function () { return this._d[internal]; } });
};
var $from = function from(source /* , mapfn, thisArg */) {
var O = toObject(source);
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var iterFn = getIterFn(O);
var i, length, values, result, step, iterator;
if (iterFn != undefined && !isArrayIter(iterFn)) {
for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) {
values.push(step.value);
} O = values;
}
if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2);
for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) {
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/* ...items */) {
var index = 0;
var length = arguments.length;
var result = allocate(this, length);
while (length > index) result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString() {
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /* , end */) {
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /* , thisArg */) {
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /* , thisArg */) {
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /* , thisArg */) {
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /* , thisArg */) {
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /* , thisArg */) {
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /* , fromIndex */) {
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /* , fromIndex */) {
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator) { // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /* , thisArg */) {
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse() {
var that = this;
var length = validate(that).length;
var middle = Math.floor(length / 2);
var index = 0;
var value;
while (index < middle) {
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /* , thisArg */) {
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn) {
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end) {
var O = validate(this);
var length = O.length;
var $begin = toAbsoluteIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end) {
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /* , offset */) {
validate(this);
var offset = toOffset(arguments[1], 1);
var length = this.length;
var src = toObject(arrayLike);
var len = toLength(src.length);
var index = 0;
if (len + offset > length) throw RangeError(WRONG_LENGTH);
while (index < len) this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries() {
return arrayEntries.call(validate(this));
},
keys: function keys() {
return arrayKeys.call(validate(this));
},
values: function values() {
return arrayValues.call(validate(this));
}
};
var isTAIndex = function (target, key) {
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key) {
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc) {
if (isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
) {
target[key] = desc.value;
return target;
} return dP(target, key, desc);
};
if (!ALL_CONSTRUCTORS) {
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if (fails(function () { arrayToString.call({}); })) {
arrayToString = arrayToLocaleString = function toString() {
return arrayJoin.call(this);
};
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function () { /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function () { return this[TYPED_ARRAY]; }
});
// eslint-disable-next-line max-statements
module.exports = function (KEY, BYTES, wrapper, CLAMPED) {
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array';
var GETTER = 'get' + KEY;
var SETTER = 'set' + KEY;
var TypedArray = global[NAME];
var Base = TypedArray || {};
var TAC = TypedArray && getPrototypeOf(TypedArray);
var FORCED = !TypedArray || !$typed.ABV;
var O = {};
var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function (that, index) {
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function (that, index, value) {
var data = that._d;
if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function (that, index) {
dP(that, index, {
get: function () {
return getter(this, index);
},
set: function (value) {
return setter(this, index, value);
},
enumerable: true
});
};
if (FORCED) {
TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME, '_d');
var index = 0;
var offset = 0;
var buffer, byteLength, length, klass;
if (!isObject(data)) {
length = toIndex(data);
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if ($length === undefined) {
if ($len % BYTES) throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if (byteLength < 0) throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if (TYPED_ARRAY in data) {
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while (index < length) addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if (!fails(function () {
TypedArray(1);
}) || !fails(function () {
new TypedArray(-1); // eslint-disable-line no-new
}) || !$iterDetect(function (iter) {
new TypedArray(); // eslint-disable-line no-new
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(1.5); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)) {
TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if (!isObject(data)) return new Base(toIndex(data));
if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if (TYPED_ARRAY in data) return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) {
if (!(key in TypedArray)) hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR];
var CORRECT_ITER_NAME = !!$nativeIterator
&& ($nativeIterator.name == 'values' || $nativeIterator.name == undefined);
var $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) {
dP(TypedArrayPrototype, TAG, {
get: function () { return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES
});
$export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, {
from: $from,
of: $of
});
if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, { set: $set });
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString;
$export($export.P + $export.F * fails(function () {
new TypedArray(1).slice();
}), NAME, { slice: $slice });
$export($export.P + $export.F * (fails(function () {
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString();
}) || !fails(function () {
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, { toLocaleString: $toLocaleString });
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function () { /* empty */ };
},{"./_an-instance":162,"./_array-copy-within":164,"./_array-fill":165,"./_array-includes":167,"./_array-methods":168,"./_classof":173,"./_ctx":181,"./_descriptors":185,"./_export":189,"./_fails":191,"./_global":196,"./_has":197,"./_hide":198,"./_is-array-iter":204,"./_is-object":207,"./_iter-detect":212,"./_iterators":214,"./_library":215,"./_object-create":226,"./_object-dp":227,"./_object-gopd":230,"./_object-gopn":232,"./_object-gpo":234,"./_property-desc":245,"./_redefine-all":246,"./_set-species":253,"./_species-constructor":257,"./_to-absolute-index":267,"./_to-index":268,"./_to-integer":269,"./_to-length":271,"./_to-object":272,"./_to-primitive":273,"./_typed":276,"./_typed-buffer":275,"./_uid":277,"./_wks":281,"./core.get-iterator-method":282,"./es6.array.iterator":294}],275:[function(require,module,exports){
'use strict';
var global = require('./_global');
var DESCRIPTORS = require('./_descriptors');
var LIBRARY = require('./_library');
var $typed = require('./_typed');
var hide = require('./_hide');
var redefineAll = require('./_redefine-all');
var fails = require('./_fails');
var anInstance = require('./_an-instance');
var toInteger = require('./_to-integer');
var toLength = require('./_to-length');
var toIndex = require('./_to-index');
var gOPN = require('./_object-gopn').f;
var dP = require('./_object-dp').f;
var arrayFill = require('./_array-fill');
var setToStringTag = require('./_set-to-string-tag');
var ARRAY_BUFFER = 'ArrayBuffer';
var DATA_VIEW = 'DataView';
var PROTOTYPE = 'prototype';
var WRONG_LENGTH = 'Wrong length!';
var WRONG_INDEX = 'Wrong index!';
var $ArrayBuffer = global[ARRAY_BUFFER];
var $DataView = global[DATA_VIEW];
var Math = global.Math;
var RangeError = global.RangeError;
// eslint-disable-next-line no-shadow-restricted-names
var Infinity = global.Infinity;
var BaseBuffer = $ArrayBuffer;
var abs = Math.abs;
var pow = Math.pow;
var floor = Math.floor;
var log = Math.log;
var LN2 = Math.LN2;
var BUFFER = 'buffer';
var BYTE_LENGTH = 'byteLength';
var BYTE_OFFSET = 'byteOffset';
var $BUFFER = DESCRIPTORS ? '_b' : BUFFER;
var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH;
var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
function packIEEE754(value, mLen, nBytes) {
var buffer = Array(nBytes);
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0;
var i = 0;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
var e, m, c;
value = abs(value);
// eslint-disable-next-line no-self-compare
if (value != value || value === Infinity) {
// eslint-disable-next-line no-self-compare
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if (value * (c = pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * 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) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
}
function unpackIEEE754(buffer, mLen, nBytes) {
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = eLen - 7;
var i = nBytes - 1;
var s = buffer[i--];
var e = s & 127;
var m;
s >>= 7;
for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
}
function unpackI32(bytes) {
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
}
function packI8(it) {
return [it & 0xff];
}
function packI16(it) {
return [it & 0xff, it >> 8 & 0xff];
}
function packI32(it) {
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
}
function packF64(it) {
return packIEEE754(it, 52, 8);
}
function packF32(it) {
return packIEEE754(it, 23, 4);
}
function addGetter(C, key, internal) {
dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } });
}
function get(view, bytes, index, isLittleEndian) {
var numIndex = +index;
var intIndex = toIndex(numIndex);
if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b;
var start = intIndex + view[$OFFSET];
var pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
}
function set(view, bytes, index, conversion, value, isLittleEndian) {
var numIndex = +index;
var intIndex = toIndex(numIndex);
if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b;
var start = intIndex + view[$OFFSET];
var pack = conversion(+value);
for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
}
if (!$typed.ABV) {
$ArrayBuffer = function ArrayBuffer(length) {
anInstance(this, $ArrayBuffer, ARRAY_BUFFER);
var byteLength = toIndex(length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength) {
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH];
var offset = toInteger(byteOffset);
if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if (DESCRIPTORS) {
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset) {
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset) {
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if (!fails(function () {
$ArrayBuffer(1);
}) || !fails(function () {
new $ArrayBuffer(-1); // eslint-disable-line no-new
}) || fails(function () {
new $ArrayBuffer(); // eslint-disable-line no-new
new $ArrayBuffer(1.5); // eslint-disable-line no-new
new $ArrayBuffer(NaN); // eslint-disable-line no-new
return $ArrayBuffer.name != ARRAY_BUFFER;
})) {
$ArrayBuffer = function ArrayBuffer(length) {
anInstance(this, $ArrayBuffer);
return new BaseBuffer(toIndex(length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) {
if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]);
}
if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2));
var $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
},{"./_an-instance":162,"./_array-fill":165,"./_descriptors":185,"./_fails":191,"./_global":196,"./_hide":198,"./_library":215,"./_object-dp":227,"./_object-gopn":232,"./_redefine-all":246,"./_set-to-string-tag":254,"./_to-index":268,"./_to-integer":269,"./_to-length":271,"./_typed":276}],276:[function(require,module,exports){
var global = require('./_global');
var hide = require('./_hide');
var uid = require('./_uid');
var TYPED = uid('typed_array');
var VIEW = uid('view');
var ABV = !!(global.ArrayBuffer && global.DataView);
var CONSTR = ABV;
var i = 0;
var l = 9;
var Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while (i < l) {
if (Typed = global[TypedArrayConstructors[i++]]) {
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
},{"./_global":196,"./_hide":198,"./_uid":277}],277:[function(require,module,exports){
arguments[4][140][0].apply(exports,arguments)
},{"dup":140}],278:[function(require,module,exports){
var isObject = require('./_is-object');
module.exports = function (it, TYPE) {
if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
return it;
};
},{"./_is-object":207}],279:[function(require,module,exports){
arguments[4][141][0].apply(exports,arguments)
},{"./_core":179,"./_global":196,"./_library":215,"./_object-dp":227,"./_wks-ext":280,"dup":141}],280:[function(require,module,exports){
arguments[4][142][0].apply(exports,arguments)
},{"./_wks":281,"dup":142}],281:[function(require,module,exports){
arguments[4][143][0].apply(exports,arguments)
},{"./_global":196,"./_shared":256,"./_uid":277,"dup":143}],282:[function(require,module,exports){
arguments[4][144][0].apply(exports,arguments)
},{"./_classof":173,"./_core":179,"./_iterators":214,"./_wks":281,"dup":144}],283:[function(require,module,exports){
// https://github.com/benjamingr/RexExp.escape
var $export = require('./_export');
var $re = require('./_replacer')(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } });
},{"./_export":189,"./_replacer":248}],284:[function(require,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = require('./_export');
$export($export.P, 'Array', { copyWithin: require('./_array-copy-within') });
require('./_add-to-unscopables')('copyWithin');
},{"./_add-to-unscopables":161,"./_array-copy-within":164,"./_export":189}],285:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $every = require('./_array-methods')(4);
$export($export.P + $export.F * !require('./_strict-method')([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":168,"./_export":189,"./_strict-method":258}],286:[function(require,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = require('./_export');
$export($export.P, 'Array', { fill: require('./_array-fill') });
require('./_add-to-unscopables')('fill');
},{"./_add-to-unscopables":161,"./_array-fill":165,"./_export":189}],287:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $filter = require('./_array-methods')(2);
$export($export.P + $export.F * !require('./_strict-method')([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":168,"./_export":189,"./_strict-method":258}],288:[function(require,module,exports){
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = require('./_export');
var $find = require('./_array-methods')(6);
var KEY = 'findIndex';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')(KEY);
},{"./_add-to-unscopables":161,"./_array-methods":168,"./_export":189}],289:[function(require,module,exports){
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = require('./_export');
var $find = require('./_array-methods')(5);
var KEY = 'find';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')(KEY);
},{"./_add-to-unscopables":161,"./_array-methods":168,"./_export":189}],290:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $forEach = require('./_array-methods')(0);
var STRICT = require('./_strict-method')([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */) {
return $forEach(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":168,"./_export":189,"./_strict-method":258}],291:[function(require,module,exports){
arguments[4][145][0].apply(exports,arguments)
},{"./_create-property":180,"./_ctx":181,"./_export":189,"./_is-array-iter":204,"./_iter-call":209,"./_iter-detect":212,"./_to-length":271,"./_to-object":272,"./core.get-iterator-method":282,"dup":145}],292:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $indexOf = require('./_array-includes')(false);
var $native = [].indexOf;
var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
},{"./_array-includes":167,"./_export":189,"./_strict-method":258}],293:[function(require,module,exports){
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = require('./_export');
$export($export.S, 'Array', { isArray: require('./_is-array') });
},{"./_export":189,"./_is-array":205}],294:[function(require,module,exports){
arguments[4][146][0].apply(exports,arguments)
},{"./_add-to-unscopables":161,"./_iter-define":211,"./_iter-step":213,"./_iterators":214,"./_to-iobject":270,"dup":146}],295:[function(require,module,exports){
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = require('./_export');
var toIObject = require('./_to-iobject');
var arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (require('./_iobject') != Object || !require('./_strict-method')(arrayJoin)), 'Array', {
join: function join(separator) {
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
},{"./_export":189,"./_iobject":203,"./_strict-method":258,"./_to-iobject":270}],296:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var toIObject = require('./_to-iobject');
var toInteger = require('./_to-integer');
var toLength = require('./_to-length');
var $native = [].lastIndexOf;
var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0;
var O = toIObject(this);
var length = toLength(O.length);
var index = length - 1;
if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1]));
if (index < 0) index = length + index;
for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0;
return -1;
}
});
},{"./_export":189,"./_strict-method":258,"./_to-integer":269,"./_to-iobject":270,"./_to-length":271}],297:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $map = require('./_array-methods')(1);
$export($export.P + $export.F * !require('./_strict-method')([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":168,"./_export":189,"./_strict-method":258}],298:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var createProperty = require('./_create-property');
// WebKit Array.of isn't generic
$export($export.S + $export.F * require('./_fails')(function () {
function F() { /* empty */ }
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */) {
var index = 0;
var aLen = arguments.length;
var result = new (typeof this == 'function' ? this : Array)(aLen);
while (aLen > index) createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
},{"./_create-property":180,"./_export":189,"./_fails":191}],299:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $reduce = require('./_array-reduce');
$export($export.P + $export.F * !require('./_strict-method')([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
},{"./_array-reduce":169,"./_export":189,"./_strict-method":258}],300:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $reduce = require('./_array-reduce');
$export($export.P + $export.F * !require('./_strict-method')([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
},{"./_array-reduce":169,"./_export":189,"./_strict-method":258}],301:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var html = require('./_html');
var cof = require('./_cof');
var toAbsoluteIndex = require('./_to-absolute-index');
var toLength = require('./_to-length');
var arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * require('./_fails')(function () {
if (html) arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end) {
var len = toLength(this.length);
var klass = cof(this);
end = end === undefined ? len : end;
if (klass == 'Array') return arraySlice.call(this, begin, end);
var start = toAbsoluteIndex(begin, len);
var upTo = toAbsoluteIndex(end, len);
var size = toLength(upTo - start);
var cloned = Array(size);
var i = 0;
for (; i < size; i++) cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
},{"./_cof":174,"./_export":189,"./_fails":191,"./_html":199,"./_to-absolute-index":267,"./_to-length":271}],302:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $some = require('./_array-methods')(3);
$export($export.P + $export.F * !require('./_strict-method')([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":168,"./_export":189,"./_strict-method":258}],303:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var aFunction = require('./_a-function');
var toObject = require('./_to-object');
var fails = require('./_fails');
var $sort = [].sort;
var test = [1, 2, 3];
$export($export.P + $export.F * (fails(function () {
// IE8-
test.sort(undefined);
}) || !fails(function () {
// V8 bug
test.sort(null);
// Old WebKit
}) || !require('./_strict-method')($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn) {
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
},{"./_a-function":159,"./_export":189,"./_fails":191,"./_strict-method":258,"./_to-object":272}],304:[function(require,module,exports){
require('./_set-species')('Array');
},{"./_set-species":253}],305:[function(require,module,exports){
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = require('./_export');
$export($export.S, 'Date', { now: function () { return new Date().getTime(); } });
},{"./_export":189}],306:[function(require,module,exports){
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = require('./_export');
var toISOString = require('./_date-to-iso-string');
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', {
toISOString: toISOString
});
},{"./_date-to-iso-string":182,"./_export":189}],307:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var toObject = require('./_to-object');
var toPrimitive = require('./_to-primitive');
$export($export.P + $export.F * require('./_fails')(function () {
return new Date(NaN).toJSON() !== null
|| Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1;
}), 'Date', {
// eslint-disable-next-line no-unused-vars
toJSON: function toJSON(key) {
var O = toObject(this);
var pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
},{"./_export":189,"./_fails":191,"./_to-object":272,"./_to-primitive":273}],308:[function(require,module,exports){
var TO_PRIMITIVE = require('./_wks')('toPrimitive');
var proto = Date.prototype;
if (!(TO_PRIMITIVE in proto)) require('./_hide')(proto, TO_PRIMITIVE, require('./_date-to-primitive'));
},{"./_date-to-primitive":183,"./_hide":198,"./_wks":281}],309:[function(require,module,exports){
var DateProto = Date.prototype;
var INVALID_DATE = 'Invalid Date';
var TO_STRING = 'toString';
var $toString = DateProto[TO_STRING];
var getTime = DateProto.getTime;
if (new Date(NaN) + '' != INVALID_DATE) {
require('./_redefine')(DateProto, TO_STRING, function toString() {
var value = getTime.call(this);
// eslint-disable-next-line no-self-compare
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
},{"./_redefine":247}],310:[function(require,module,exports){
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = require('./_export');
$export($export.P, 'Function', { bind: require('./_bind') });
},{"./_bind":172,"./_export":189}],311:[function(require,module,exports){
'use strict';
var isObject = require('./_is-object');
var getPrototypeOf = require('./_object-gpo');
var HAS_INSTANCE = require('./_wks')('hasInstance');
var FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if (!(HAS_INSTANCE in FunctionProto)) require('./_object-dp').f(FunctionProto, HAS_INSTANCE, { value: function (O) {
if (typeof this != 'function' || !isObject(O)) return false;
if (!isObject(this.prototype)) return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while (O = getPrototypeOf(O)) if (this.prototype === O) return true;
return false;
} });
},{"./_is-object":207,"./_object-dp":227,"./_object-gpo":234,"./_wks":281}],312:[function(require,module,exports){
var dP = require('./_object-dp').f;
var FProto = Function.prototype;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name';
// 19.2.4.2 name
NAME in FProto || require('./_descriptors') && dP(FProto, NAME, {
configurable: true,
get: function () {
try {
return ('' + this).match(nameRE)[1];
} catch (e) {
return '';
}
}
});
},{"./_descriptors":185,"./_object-dp":227}],313:[function(require,module,exports){
'use strict';
var strong = require('./_collection-strong');
var validate = require('./_validate-collection');
var MAP = 'Map';
// 23.1 Map Objects
module.exports = require('./_collection')(MAP, function (get) {
return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key) {
var entry = strong.getEntry(validate(this, MAP), key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value) {
return strong.def(validate(this, MAP), key === 0 ? 0 : key, value);
}
}, strong, true);
},{"./_collection":178,"./_collection-strong":175,"./_validate-collection":278}],314:[function(require,module,exports){
// 20.2.2.3 Math.acosh(x)
var $export = require('./_export');
var log1p = require('./_math-log1p');
var sqrt = Math.sqrt;
var $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x) {
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
},{"./_export":189,"./_math-log1p":218}],315:[function(require,module,exports){
// 20.2.2.5 Math.asinh(x)
var $export = require('./_export');
var $asinh = Math.asinh;
function asinh(x) {
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh });
},{"./_export":189}],316:[function(require,module,exports){
// 20.2.2.7 Math.atanh(x)
var $export = require('./_export');
var $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x) {
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
},{"./_export":189}],317:[function(require,module,exports){
// 20.2.2.9 Math.cbrt(x)
var $export = require('./_export');
var sign = require('./_math-sign');
$export($export.S, 'Math', {
cbrt: function cbrt(x) {
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
},{"./_export":189,"./_math-sign":220}],318:[function(require,module,exports){
// 20.2.2.11 Math.clz32(x)
var $export = require('./_export');
$export($export.S, 'Math', {
clz32: function clz32(x) {
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
},{"./_export":189}],319:[function(require,module,exports){
// 20.2.2.12 Math.cosh(x)
var $export = require('./_export');
var exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x) {
return (exp(x = +x) + exp(-x)) / 2;
}
});
},{"./_export":189}],320:[function(require,module,exports){
// 20.2.2.14 Math.expm1(x)
var $export = require('./_export');
var $expm1 = require('./_math-expm1');
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 });
},{"./_export":189,"./_math-expm1":216}],321:[function(require,module,exports){
// 20.2.2.16 Math.fround(x)
var $export = require('./_export');
$export($export.S, 'Math', { fround: require('./_math-fround') });
},{"./_export":189,"./_math-fround":217}],322:[function(require,module,exports){
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = require('./_export');
var abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars
var sum = 0;
var i = 0;
var aLen = arguments.length;
var larg = 0;
var arg, div;
while (i < aLen) {
arg = abs(arguments[i++]);
if (larg < arg) {
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if (arg > 0) {
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
},{"./_export":189}],323:[function(require,module,exports){
// 20.2.2.18 Math.imul(x, y)
var $export = require('./_export');
var $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * require('./_fails')(function () {
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y) {
var UINT16 = 0xffff;
var xn = +x;
var yn = +y;
var xl = UINT16 & xn;
var yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
},{"./_export":189,"./_fails":191}],324:[function(require,module,exports){
// 20.2.2.21 Math.log10(x)
var $export = require('./_export');
$export($export.S, 'Math', {
log10: function log10(x) {
return Math.log(x) * Math.LOG10E;
}
});
},{"./_export":189}],325:[function(require,module,exports){
// 20.2.2.20 Math.log1p(x)
var $export = require('./_export');
$export($export.S, 'Math', { log1p: require('./_math-log1p') });
},{"./_export":189,"./_math-log1p":218}],326:[function(require,module,exports){
// 20.2.2.22 Math.log2(x)
var $export = require('./_export');
$export($export.S, 'Math', {
log2: function log2(x) {
return Math.log(x) / Math.LN2;
}
});
},{"./_export":189}],327:[function(require,module,exports){
// 20.2.2.28 Math.sign(x)
var $export = require('./_export');
$export($export.S, 'Math', { sign: require('./_math-sign') });
},{"./_export":189,"./_math-sign":220}],328:[function(require,module,exports){
// 20.2.2.30 Math.sinh(x)
var $export = require('./_export');
var expm1 = require('./_math-expm1');
var exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * require('./_fails')(function () {
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x) {
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
},{"./_export":189,"./_fails":191,"./_math-expm1":216}],329:[function(require,module,exports){
// 20.2.2.33 Math.tanh(x)
var $export = require('./_export');
var expm1 = require('./_math-expm1');
var exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x) {
var a = expm1(x = +x);
var b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
},{"./_export":189,"./_math-expm1":216}],330:[function(require,module,exports){
// 20.2.2.34 Math.trunc(x)
var $export = require('./_export');
$export($export.S, 'Math', {
trunc: function trunc(it) {
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
},{"./_export":189}],331:[function(require,module,exports){
'use strict';
var global = require('./_global');
var has = require('./_has');
var cof = require('./_cof');
var inheritIfRequired = require('./_inherit-if-required');
var toPrimitive = require('./_to-primitive');
var fails = require('./_fails');
var gOPN = require('./_object-gopn').f;
var gOPD = require('./_object-gopd').f;
var dP = require('./_object-dp').f;
var $trim = require('./_string-trim').trim;
var NUMBER = 'Number';
var $Number = global[NUMBER];
var Base = $Number;
var proto = $Number.prototype;
// Opera ~12 has broken Object#toString
var BROKEN_COF = cof(require('./_object-create')(proto)) == NUMBER;
var TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function (argument) {
var it = toPrimitive(argument, false);
if (typeof it == 'string' && it.length > 2) {
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0);
var third, radix, maxCode;
if (first === 43 || first === 45) {
third = it.charCodeAt(2);
if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if (first === 48) {
switch (it.charCodeAt(1)) {
case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default: return +it;
}
for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) {
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if (code < 48 || code > maxCode) return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) {
$Number = function Number(value) {
var it = arguments.length < 1 ? 0 : value;
var that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for (var keys = require('./_descriptors') ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++) {
if (has(Base, key = keys[j]) && !has($Number, key)) {
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
require('./_redefine')(global, NUMBER, $Number);
}
},{"./_cof":174,"./_descriptors":185,"./_fails":191,"./_global":196,"./_has":197,"./_inherit-if-required":201,"./_object-create":226,"./_object-dp":227,"./_object-gopd":230,"./_object-gopn":232,"./_redefine":247,"./_string-trim":264,"./_to-primitive":273}],332:[function(require,module,exports){
// 20.1.2.1 Number.EPSILON
var $export = require('./_export');
$export($export.S, 'Number', { EPSILON: Math.pow(2, -52) });
},{"./_export":189}],333:[function(require,module,exports){
// 20.1.2.2 Number.isFinite(number)
var $export = require('./_export');
var _isFinite = require('./_global').isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it) {
return typeof it == 'number' && _isFinite(it);
}
});
},{"./_export":189,"./_global":196}],334:[function(require,module,exports){
// 20.1.2.3 Number.isInteger(number)
var $export = require('./_export');
$export($export.S, 'Number', { isInteger: require('./_is-integer') });
},{"./_export":189,"./_is-integer":206}],335:[function(require,module,exports){
// 20.1.2.4 Number.isNaN(number)
var $export = require('./_export');
$export($export.S, 'Number', {
isNaN: function isNaN(number) {
// eslint-disable-next-line no-self-compare
return number != number;
}
});
},{"./_export":189}],336:[function(require,module,exports){
// 20.1.2.5 Number.isSafeInteger(number)
var $export = require('./_export');
var isInteger = require('./_is-integer');
var abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number) {
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
},{"./_export":189,"./_is-integer":206}],337:[function(require,module,exports){
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = require('./_export');
$export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff });
},{"./_export":189}],338:[function(require,module,exports){
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = require('./_export');
$export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff });
},{"./_export":189}],339:[function(require,module,exports){
var $export = require('./_export');
var $parseFloat = require('./_parse-float');
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat });
},{"./_export":189,"./_parse-float":241}],340:[function(require,module,exports){
var $export = require('./_export');
var $parseInt = require('./_parse-int');
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt });
},{"./_export":189,"./_parse-int":242}],341:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var toInteger = require('./_to-integer');
var aNumberValue = require('./_a-number-value');
var repeat = require('./_string-repeat');
var $toFixed = 1.0.toFixed;
var floor = Math.floor;
var data = [0, 0, 0, 0, 0, 0];
var ERROR = 'Number.toFixed: incorrect invocation!';
var ZERO = '0';
var multiply = function (n, c) {
var i = -1;
var c2 = c;
while (++i < 6) {
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function (n) {
var i = 6;
var c = 0;
while (--i >= 0) {
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function () {
var i = 6;
var s = '';
while (--i >= 0) {
if (s !== '' || i === 0 || data[i] !== 0) {
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function (x, n, acc) {
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function (x) {
var n = 0;
var x2 = x;
while (x2 >= 4096) {
n += 12;
x2 /= 4096;
}
while (x2 >= 2) {
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128.0.toFixed(0) !== '1000000000000000128'
) || !require('./_fails')(function () {
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits) {
var x = aNumberValue(this, ERROR);
var f = toInteger(fractionDigits);
var s = '';
var m = ZERO;
var e, z, j, k;
if (f < 0 || f > 20) throw RangeError(ERROR);
// eslint-disable-next-line no-self-compare
if (x != x) return 'NaN';
if (x <= -1e21 || x >= 1e21) return String(x);
if (x < 0) {
s = '-';
x = -x;
}
if (x > 1e-21) {
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if (e > 0) {
multiply(0, z);
j = f;
while (j >= 7) {
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while (j >= 23) {
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if (f > 0) {
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
},{"./_a-number-value":160,"./_export":189,"./_fails":191,"./_string-repeat":263,"./_to-integer":269}],342:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $fails = require('./_fails');
var aNumberValue = require('./_a-number-value');
var $toPrecision = 1.0.toPrecision;
$export($export.P + $export.F * ($fails(function () {
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function () {
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision) {
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
},{"./_a-number-value":160,"./_export":189,"./_fails":191}],343:[function(require,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = require('./_export');
$export($export.S + $export.F, 'Object', { assign: require('./_object-assign') });
},{"./_export":189,"./_object-assign":225}],344:[function(require,module,exports){
arguments[4][147][0].apply(exports,arguments)
},{"./_export":189,"./_object-create":226,"dup":147}],345:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !require('./_descriptors'), 'Object', { defineProperties: require('./_object-dps') });
},{"./_descriptors":185,"./_export":189,"./_object-dps":228}],346:[function(require,module,exports){
arguments[4][148][0].apply(exports,arguments)
},{"./_descriptors":185,"./_export":189,"./_object-dp":227,"dup":148}],347:[function(require,module,exports){
// 19.1.2.5 Object.freeze(O)
var isObject = require('./_is-object');
var meta = require('./_meta').onFreeze;
require('./_object-sap')('freeze', function ($freeze) {
return function freeze(it) {
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
},{"./_is-object":207,"./_meta":221,"./_object-sap":238}],348:[function(require,module,exports){
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = require('./_to-iobject');
var $getOwnPropertyDescriptor = require('./_object-gopd').f;
require('./_object-sap')('getOwnPropertyDescriptor', function () {
return function getOwnPropertyDescriptor(it, key) {
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
},{"./_object-gopd":230,"./_object-sap":238,"./_to-iobject":270}],349:[function(require,module,exports){
// 19.1.2.7 Object.getOwnPropertyNames(O)
require('./_object-sap')('getOwnPropertyNames', function () {
return require('./_object-gopn-ext').f;
});
},{"./_object-gopn-ext":231,"./_object-sap":238}],350:[function(require,module,exports){
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = require('./_to-object');
var $getPrototypeOf = require('./_object-gpo');
require('./_object-sap')('getPrototypeOf', function () {
return function getPrototypeOf(it) {
return $getPrototypeOf(toObject(it));
};
});
},{"./_object-gpo":234,"./_object-sap":238,"./_to-object":272}],351:[function(require,module,exports){
// 19.1.2.11 Object.isExtensible(O)
var isObject = require('./_is-object');
require('./_object-sap')('isExtensible', function ($isExtensible) {
return function isExtensible(it) {
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
},{"./_is-object":207,"./_object-sap":238}],352:[function(require,module,exports){
// 19.1.2.12 Object.isFrozen(O)
var isObject = require('./_is-object');
require('./_object-sap')('isFrozen', function ($isFrozen) {
return function isFrozen(it) {
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
},{"./_is-object":207,"./_object-sap":238}],353:[function(require,module,exports){
// 19.1.2.13 Object.isSealed(O)
var isObject = require('./_is-object');
require('./_object-sap')('isSealed', function ($isSealed) {
return function isSealed(it) {
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
},{"./_is-object":207,"./_object-sap":238}],354:[function(require,module,exports){
// 19.1.3.10 Object.is(value1, value2)
var $export = require('./_export');
$export($export.S, 'Object', { is: require('./_same-value') });
},{"./_export":189,"./_same-value":249}],355:[function(require,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = require('./_to-object');
var $keys = require('./_object-keys');
require('./_object-sap')('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
},{"./_object-keys":236,"./_object-sap":238,"./_to-object":272}],356:[function(require,module,exports){
// 19.1.2.15 Object.preventExtensions(O)
var isObject = require('./_is-object');
var meta = require('./_meta').onFreeze;
require('./_object-sap')('preventExtensions', function ($preventExtensions) {
return function preventExtensions(it) {
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
},{"./_is-object":207,"./_meta":221,"./_object-sap":238}],357:[function(require,module,exports){
// 19.1.2.17 Object.seal(O)
var isObject = require('./_is-object');
var meta = require('./_meta').onFreeze;
require('./_object-sap')('seal', function ($seal) {
return function seal(it) {
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
},{"./_is-object":207,"./_meta":221,"./_object-sap":238}],358:[function(require,module,exports){
arguments[4][149][0].apply(exports,arguments)
},{"./_export":189,"./_set-proto":252,"dup":149}],359:[function(require,module,exports){
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = require('./_classof');
var test = {};
test[require('./_wks')('toStringTag')] = 'z';
if (test + '' != '[object z]') {
require('./_redefine')(Object.prototype, 'toString', function toString() {
return '[object ' + classof(this) + ']';
}, true);
}
},{"./_classof":173,"./_redefine":247,"./_wks":281}],360:[function(require,module,exports){
var $export = require('./_export');
var $parseFloat = require('./_parse-float');
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat });
},{"./_export":189,"./_parse-float":241}],361:[function(require,module,exports){
var $export = require('./_export');
var $parseInt = require('./_parse-int');
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt });
},{"./_export":189,"./_parse-int":242}],362:[function(require,module,exports){
arguments[4][151][0].apply(exports,arguments)
},{"./_a-function":159,"./_an-instance":162,"./_classof":173,"./_core":179,"./_ctx":181,"./_export":189,"./_for-of":195,"./_global":196,"./_is-object":207,"./_iter-detect":212,"./_library":215,"./_microtask":223,"./_new-promise-capability":224,"./_perform":243,"./_promise-resolve":244,"./_redefine-all":246,"./_set-species":253,"./_set-to-string-tag":254,"./_species-constructor":257,"./_task":266,"./_wks":281,"dup":151}],363:[function(require,module,exports){
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = require('./_export');
var aFunction = require('./_a-function');
var anObject = require('./_an-object');
var rApply = (require('./_global').Reflect || {}).apply;
var fApply = Function.apply;
// MS Edge argumentsList argument is optional
$export($export.S + $export.F * !require('./_fails')(function () {
rApply(function () { /* empty */ });
}), 'Reflect', {
apply: function apply(target, thisArgument, argumentsList) {
var T = aFunction(target);
var L = anObject(argumentsList);
return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L);
}
});
},{"./_a-function":159,"./_an-object":163,"./_export":189,"./_fails":191,"./_global":196}],364:[function(require,module,exports){
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = require('./_export');
var create = require('./_object-create');
var aFunction = require('./_a-function');
var anObject = require('./_an-object');
var isObject = require('./_is-object');
var fails = require('./_fails');
var bind = require('./_bind');
var rConstruct = (require('./_global').Reflect || {}).construct;
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
var NEW_TARGET_BUG = fails(function () {
function F() { /* empty */ }
return !(rConstruct(function () { /* empty */ }, [], F) instanceof F);
});
var ARGS_BUG = !fails(function () {
rConstruct(function () { /* empty */ });
});
$export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', {
construct: function construct(Target, args /* , newTarget */) {
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget);
if (Target == newTarget) {
// w/o altered newTarget, optimization for 0-4 arguments
switch (args.length) {
case 0: return new Target();
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args))();
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype;
var instance = create(isObject(proto) ? proto : Object.prototype);
var result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
},{"./_a-function":159,"./_an-object":163,"./_bind":172,"./_export":189,"./_fails":191,"./_global":196,"./_is-object":207,"./_object-create":226}],365:[function(require,module,exports){
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = require('./_object-dp');
var $export = require('./_export');
var anObject = require('./_an-object');
var toPrimitive = require('./_to-primitive');
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * require('./_fails')(function () {
// eslint-disable-next-line no-undef
Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 });
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes) {
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch (e) {
return false;
}
}
});
},{"./_an-object":163,"./_export":189,"./_fails":191,"./_object-dp":227,"./_to-primitive":273}],366:[function(require,module,exports){
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = require('./_export');
var gOPD = require('./_object-gopd').f;
var anObject = require('./_an-object');
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey) {
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
},{"./_an-object":163,"./_export":189,"./_object-gopd":230}],367:[function(require,module,exports){
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = require('./_export');
var anObject = require('./_an-object');
var Enumerate = function (iterated) {
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = []; // keys
var key;
for (key in iterated) keys.push(key);
};
require('./_iter-create')(Enumerate, 'Object', function () {
var that = this;
var keys = that._k;
var key;
do {
if (that._i >= keys.length) return { value: undefined, done: true };
} while (!((key = keys[that._i++]) in that._t));
return { value: key, done: false };
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target) {
return new Enumerate(target);
}
});
},{"./_an-object":163,"./_export":189,"./_iter-create":210}],368:[function(require,module,exports){
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = require('./_object-gopd');
var $export = require('./_export');
var anObject = require('./_an-object');
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) {
return gOPD.f(anObject(target), propertyKey);
}
});
},{"./_an-object":163,"./_export":189,"./_object-gopd":230}],369:[function(require,module,exports){
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = require('./_export');
var getProto = require('./_object-gpo');
var anObject = require('./_an-object');
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target) {
return getProto(anObject(target));
}
});
},{"./_an-object":163,"./_export":189,"./_object-gpo":234}],370:[function(require,module,exports){
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = require('./_object-gopd');
var getPrototypeOf = require('./_object-gpo');
var has = require('./_has');
var $export = require('./_export');
var isObject = require('./_is-object');
var anObject = require('./_an-object');
function get(target, propertyKey /* , receiver */) {
var receiver = arguments.length < 3 ? target : arguments[2];
var desc, proto;
if (anObject(target) === receiver) return target[propertyKey];
if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', { get: get });
},{"./_an-object":163,"./_export":189,"./_has":197,"./_is-object":207,"./_object-gopd":230,"./_object-gpo":234}],371:[function(require,module,exports){
// 26.1.9 Reflect.has(target, propertyKey)
var $export = require('./_export');
$export($export.S, 'Reflect', {
has: function has(target, propertyKey) {
return propertyKey in target;
}
});
},{"./_export":189}],372:[function(require,module,exports){
// 26.1.10 Reflect.isExtensible(target)
var $export = require('./_export');
var anObject = require('./_an-object');
var $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target) {
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
},{"./_an-object":163,"./_export":189}],373:[function(require,module,exports){
// 26.1.11 Reflect.ownKeys(target)
var $export = require('./_export');
$export($export.S, 'Reflect', { ownKeys: require('./_own-keys') });
},{"./_export":189,"./_own-keys":240}],374:[function(require,module,exports){
// 26.1.12 Reflect.preventExtensions(target)
var $export = require('./_export');
var anObject = require('./_an-object');
var $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target) {
anObject(target);
try {
if ($preventExtensions) $preventExtensions(target);
return true;
} catch (e) {
return false;
}
}
});
},{"./_an-object":163,"./_export":189}],375:[function(require,module,exports){
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = require('./_export');
var setProto = require('./_set-proto');
if (setProto) $export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto) {
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch (e) {
return false;
}
}
});
},{"./_export":189,"./_set-proto":252}],376:[function(require,module,exports){
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = require('./_object-dp');
var gOPD = require('./_object-gopd');
var getPrototypeOf = require('./_object-gpo');
var has = require('./_has');
var $export = require('./_export');
var createDesc = require('./_property-desc');
var anObject = require('./_an-object');
var isObject = require('./_is-object');
function set(target, propertyKey, V /* , receiver */) {
var receiver = arguments.length < 4 ? target : arguments[3];
var ownDesc = gOPD.f(anObject(target), propertyKey);
var existingDescriptor, proto;
if (!ownDesc) {
if (isObject(proto = getPrototypeOf(target))) {
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if (has(ownDesc, 'value')) {
if (ownDesc.writable === false || !isObject(receiver)) return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', { set: set });
},{"./_an-object":163,"./_export":189,"./_has":197,"./_is-object":207,"./_object-dp":227,"./_object-gopd":230,"./_object-gpo":234,"./_property-desc":245}],377:[function(require,module,exports){
var global = require('./_global');
var inheritIfRequired = require('./_inherit-if-required');
var dP = require('./_object-dp').f;
var gOPN = require('./_object-gopn').f;
var isRegExp = require('./_is-regexp');
var $flags = require('./_flags');
var $RegExp = global.RegExp;
var Base = $RegExp;
var proto = $RegExp.prototype;
var re1 = /a/g;
var re2 = /a/g;
// "new" creates a new object, old webkit buggy here
var CORRECT_NEW = new $RegExp(re1) !== re1;
if (require('./_descriptors') && (!CORRECT_NEW || require('./_fails')(function () {
re2[require('./_wks')('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))) {
$RegExp = function RegExp(p, f) {
var tiRE = this instanceof $RegExp;
var piRE = isRegExp(p);
var fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function (key) {
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function () { return Base[key]; },
set: function (it) { Base[key] = it; }
});
};
for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
require('./_redefine')(global, 'RegExp', $RegExp);
}
require('./_set-species')('RegExp');
},{"./_descriptors":185,"./_fails":191,"./_flags":193,"./_global":196,"./_inherit-if-required":201,"./_is-regexp":208,"./_object-dp":227,"./_object-gopn":232,"./_redefine":247,"./_set-species":253,"./_wks":281}],378:[function(require,module,exports){
// 21.2.5.3 get RegExp.prototype.flags()
if (require('./_descriptors') && /./g.flags != 'g') require('./_object-dp').f(RegExp.prototype, 'flags', {
configurable: true,
get: require('./_flags')
});
},{"./_descriptors":185,"./_flags":193,"./_object-dp":227}],379:[function(require,module,exports){
// @@match logic
require('./_fix-re-wks')('match', 1, function (defined, MATCH, $match) {
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp) {
'use strict';
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
},{"./_fix-re-wks":192}],380:[function(require,module,exports){
// @@replace logic
require('./_fix-re-wks')('replace', 2, function (defined, REPLACE, $replace) {
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue) {
'use strict';
var O = defined(this);
var fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
},{"./_fix-re-wks":192}],381:[function(require,module,exports){
// @@search logic
require('./_fix-re-wks')('search', 1, function (defined, SEARCH, $search) {
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp) {
'use strict';
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
},{"./_fix-re-wks":192}],382:[function(require,module,exports){
// @@split logic
require('./_fix-re-wks')('split', 2, function (defined, SPLIT, $split) {
'use strict';
var isRegExp = require('./_is-regexp');
var _split = $split;
var $push = [].push;
var $SPLIT = 'split';
var LENGTH = 'length';
var LAST_INDEX = 'lastIndex';
if (
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
) {
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function (separator, limit) {
var string = String(this);
if (separator === undefined && limit === 0) return [];
// If `separator` is not a regex, use native split
if (!isRegExp(separator)) return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while (match = separatorCopy.exec(string)) {
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
// eslint-disable-next-line no-loop-func
if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () {
for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined;
});
if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if (output[LENGTH] >= splitLimit) break;
}
if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if (lastLastIndex === string[LENGTH]) {
if (lastLength || !separatorCopy.test('')) output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if ('0'[$SPLIT](undefined, 0)[LENGTH]) {
$split = function (separator, limit) {
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit) {
var O = defined(this);
var fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
},{"./_fix-re-wks":192,"./_is-regexp":208}],383:[function(require,module,exports){
'use strict';
require('./es6.regexp.flags');
var anObject = require('./_an-object');
var $flags = require('./_flags');
var DESCRIPTORS = require('./_descriptors');
var TO_STRING = 'toString';
var $toString = /./[TO_STRING];
var define = function (fn) {
require('./_redefine')(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if (require('./_fails')(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) {
define(function toString() {
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if ($toString.name != TO_STRING) {
define(function toString() {
return $toString.call(this);
});
}
},{"./_an-object":163,"./_descriptors":185,"./_fails":191,"./_flags":193,"./_redefine":247,"./es6.regexp.flags":378}],384:[function(require,module,exports){
'use strict';
var strong = require('./_collection-strong');
var validate = require('./_validate-collection');
var SET = 'Set';
// 23.2 Set Objects
module.exports = require('./_collection')(SET, function (get) {
return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value) {
return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
}
}, strong);
},{"./_collection":178,"./_collection-strong":175,"./_validate-collection":278}],385:[function(require,module,exports){
'use strict';
// B.2.3.2 String.prototype.anchor(name)
require('./_string-html')('anchor', function (createHTML) {
return function anchor(name) {
return createHTML(this, 'a', 'name', name);
};
});
},{"./_string-html":261}],386:[function(require,module,exports){
'use strict';
// B.2.3.3 String.prototype.big()
require('./_string-html')('big', function (createHTML) {
return function big() {
return createHTML(this, 'big', '', '');
};
});
},{"./_string-html":261}],387:[function(require,module,exports){
'use strict';
// B.2.3.4 String.prototype.blink()
require('./_string-html')('blink', function (createHTML) {
return function blink() {
return createHTML(this, 'blink', '', '');
};
});
},{"./_string-html":261}],388:[function(require,module,exports){
'use strict';
// B.2.3.5 String.prototype.bold()
require('./_string-html')('bold', function (createHTML) {
return function bold() {
return createHTML(this, 'b', '', '');
};
});
},{"./_string-html":261}],389:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $at = require('./_string-at')(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos) {
return $at(this, pos);
}
});
},{"./_export":189,"./_string-at":259}],390:[function(require,module,exports){
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = require('./_export');
var toLength = require('./_to-length');
var context = require('./_string-context');
var ENDS_WITH = 'endsWith';
var $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * require('./_fails-is-regexp')(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /* , endPosition = @length */) {
var that = context(this, searchString, ENDS_WITH);
var endPosition = arguments.length > 1 ? arguments[1] : undefined;
var len = toLength(that.length);
var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);
var search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
},{"./_export":189,"./_fails-is-regexp":190,"./_string-context":260,"./_to-length":271}],391:[function(require,module,exports){
'use strict';
// B.2.3.6 String.prototype.fixed()
require('./_string-html')('fixed', function (createHTML) {
return function fixed() {
return createHTML(this, 'tt', '', '');
};
});
},{"./_string-html":261}],392:[function(require,module,exports){
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
require('./_string-html')('fontcolor', function (createHTML) {
return function fontcolor(color) {
return createHTML(this, 'font', 'color', color);
};
});
},{"./_string-html":261}],393:[function(require,module,exports){
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
require('./_string-html')('fontsize', function (createHTML) {
return function fontsize(size) {
return createHTML(this, 'font', 'size', size);
};
});
},{"./_string-html":261}],394:[function(require,module,exports){
var $export = require('./_export');
var toAbsoluteIndex = require('./_to-absolute-index');
var fromCharCode = String.fromCharCode;
var $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars
var res = [];
var aLen = arguments.length;
var i = 0;
var code;
while (aLen > i) {
code = +arguments[i++];
if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
},{"./_export":189,"./_to-absolute-index":267}],395:[function(require,module,exports){
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = require('./_export');
var context = require('./_string-context');
var INCLUDES = 'includes';
$export($export.P + $export.F * require('./_fails-is-regexp')(INCLUDES), 'String', {
includes: function includes(searchString /* , position = 0 */) {
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"./_export":189,"./_fails-is-regexp":190,"./_string-context":260}],396:[function(require,module,exports){
'use strict';
// B.2.3.9 String.prototype.italics()
require('./_string-html')('italics', function (createHTML) {
return function italics() {
return createHTML(this, 'i', '', '');
};
});
},{"./_string-html":261}],397:[function(require,module,exports){
arguments[4][152][0].apply(exports,arguments)
},{"./_iter-define":211,"./_string-at":259,"dup":152}],398:[function(require,module,exports){
'use strict';
// B.2.3.10 String.prototype.link(url)
require('./_string-html')('link', function (createHTML) {
return function link(url) {
return createHTML(this, 'a', 'href', url);
};
});
},{"./_string-html":261}],399:[function(require,module,exports){
var $export = require('./_export');
var toIObject = require('./_to-iobject');
var toLength = require('./_to-length');
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite) {
var tpl = toIObject(callSite.raw);
var len = toLength(tpl.length);
var aLen = arguments.length;
var res = [];
var i = 0;
while (len > i) {
res.push(String(tpl[i++]));
if (i < aLen) res.push(String(arguments[i]));
} return res.join('');
}
});
},{"./_export":189,"./_to-iobject":270,"./_to-length":271}],400:[function(require,module,exports){
var $export = require('./_export');
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: require('./_string-repeat')
});
},{"./_export":189,"./_string-repeat":263}],401:[function(require,module,exports){
'use strict';
// B.2.3.11 String.prototype.small()
require('./_string-html')('small', function (createHTML) {
return function small() {
return createHTML(this, 'small', '', '');
};
});
},{"./_string-html":261}],402:[function(require,module,exports){
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = require('./_export');
var toLength = require('./_to-length');
var context = require('./_string-context');
var STARTS_WITH = 'startsWith';
var $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * require('./_fails-is-regexp')(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = context(this, searchString, STARTS_WITH);
var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
},{"./_export":189,"./_fails-is-regexp":190,"./_string-context":260,"./_to-length":271}],403:[function(require,module,exports){
'use strict';
// B.2.3.12 String.prototype.strike()
require('./_string-html')('strike', function (createHTML) {
return function strike() {
return createHTML(this, 'strike', '', '');
};
});
},{"./_string-html":261}],404:[function(require,module,exports){
'use strict';
// B.2.3.13 String.prototype.sub()
require('./_string-html')('sub', function (createHTML) {
return function sub() {
return createHTML(this, 'sub', '', '');
};
});
},{"./_string-html":261}],405:[function(require,module,exports){
'use strict';
// B.2.3.14 String.prototype.sup()
require('./_string-html')('sup', function (createHTML) {
return function sup() {
return createHTML(this, 'sup', '', '');
};
});
},{"./_string-html":261}],406:[function(require,module,exports){
'use strict';
// 21.1.3.25 String.prototype.trim()
require('./_string-trim')('trim', function ($trim) {
return function trim() {
return $trim(this, 3);
};
});
},{"./_string-trim":264}],407:[function(require,module,exports){
arguments[4][153][0].apply(exports,arguments)
},{"./_an-object":163,"./_descriptors":185,"./_enum-keys":188,"./_export":189,"./_fails":191,"./_global":196,"./_has":197,"./_hide":198,"./_is-array":205,"./_library":215,"./_meta":221,"./_object-create":226,"./_object-dp":227,"./_object-gopd":230,"./_object-gopn":232,"./_object-gopn-ext":231,"./_object-gops":233,"./_object-keys":236,"./_object-pie":237,"./_property-desc":245,"./_redefine":247,"./_set-to-string-tag":254,"./_shared":256,"./_to-iobject":270,"./_to-primitive":273,"./_uid":277,"./_wks":281,"./_wks-define":279,"./_wks-ext":280,"dup":153}],408:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $typed = require('./_typed');
var buffer = require('./_typed-buffer');
var anObject = require('./_an-object');
var toAbsoluteIndex = require('./_to-absolute-index');
var toLength = require('./_to-length');
var isObject = require('./_is-object');
var ArrayBuffer = require('./_global').ArrayBuffer;
var speciesConstructor = require('./_species-constructor');
var $ArrayBuffer = buffer.ArrayBuffer;
var $DataView = buffer.DataView;
var $isView = $typed.ABV && ArrayBuffer.isView;
var $slice = $ArrayBuffer.prototype.slice;
var VIEW = $typed.VIEW;
var ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer });
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it) {
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * require('./_fails')(function () {
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end) {
if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength;
var first = toAbsoluteIndex(start, len);
var final = toAbsoluteIndex(end === undefined ? len : end, len);
var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first));
var viewS = new $DataView(this);
var viewT = new $DataView(result);
var index = 0;
while (first < final) {
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
require('./_set-species')(ARRAY_BUFFER);
},{"./_an-object":163,"./_export":189,"./_fails":191,"./_global":196,"./_is-object":207,"./_set-species":253,"./_species-constructor":257,"./_to-absolute-index":267,"./_to-length":271,"./_typed":276,"./_typed-buffer":275}],409:[function(require,module,exports){
var $export = require('./_export');
$export($export.G + $export.W + $export.F * !require('./_typed').ABV, {
DataView: require('./_typed-buffer').DataView
});
},{"./_export":189,"./_typed":276,"./_typed-buffer":275}],410:[function(require,module,exports){
require('./_typed-array')('Float32', 4, function (init) {
return function Float32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":274}],411:[function(require,module,exports){
require('./_typed-array')('Float64', 8, function (init) {
return function Float64Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":274}],412:[function(require,module,exports){
require('./_typed-array')('Int16', 2, function (init) {
return function Int16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":274}],413:[function(require,module,exports){
require('./_typed-array')('Int32', 4, function (init) {
return function Int32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":274}],414:[function(require,module,exports){
require('./_typed-array')('Int8', 1, function (init) {
return function Int8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":274}],415:[function(require,module,exports){
require('./_typed-array')('Uint16', 2, function (init) {
return function Uint16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":274}],416:[function(require,module,exports){
require('./_typed-array')('Uint32', 4, function (init) {
return function Uint32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":274}],417:[function(require,module,exports){
require('./_typed-array')('Uint8', 1, function (init) {
return function Uint8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":274}],418:[function(require,module,exports){
require('./_typed-array')('Uint8', 1, function (init) {
return function Uint8ClampedArray(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
}, true);
},{"./_typed-array":274}],419:[function(require,module,exports){
'use strict';
var each = require('./_array-methods')(0);
var redefine = require('./_redefine');
var meta = require('./_meta');
var assign = require('./_object-assign');
var weak = require('./_collection-weak');
var isObject = require('./_is-object');
var fails = require('./_fails');
var validate = require('./_validate-collection');
var WEAK_MAP = 'WeakMap';
var getWeak = meta.getWeak;
var isExtensible = Object.isExtensible;
var uncaughtFrozenStore = weak.ufstore;
var tmp = {};
var InternalMap;
var wrapper = function (get) {
return function WeakMap() {
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key) {
if (isObject(key)) {
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value) {
return weak.def(validate(this, WEAK_MAP), key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = require('./_collection')(WEAK_MAP, wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) {
InternalMap = weak.getConstructor(wrapper, WEAK_MAP);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function (key) {
var proto = $WeakMap.prototype;
var method = proto[key];
redefine(proto, key, function (a, b) {
// store frozen objects on internal weakmap shim
if (isObject(a) && !isExtensible(a)) {
if (!this._f) this._f = new InternalMap();
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
},{"./_array-methods":168,"./_collection":178,"./_collection-weak":177,"./_fails":191,"./_is-object":207,"./_meta":221,"./_object-assign":225,"./_redefine":247,"./_validate-collection":278}],420:[function(require,module,exports){
'use strict';
var weak = require('./_collection-weak');
var validate = require('./_validate-collection');
var WEAK_SET = 'WeakSet';
// 23.4 WeakSet Objects
require('./_collection')(WEAK_SET, function (get) {
return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value) {
return weak.def(validate(this, WEAK_SET), value, true);
}
}, weak, false, true);
},{"./_collection":178,"./_collection-weak":177,"./_validate-collection":278}],421:[function(require,module,exports){
'use strict';
// https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap
var $export = require('./_export');
var flattenIntoArray = require('./_flatten-into-array');
var toObject = require('./_to-object');
var toLength = require('./_to-length');
var aFunction = require('./_a-function');
var arraySpeciesCreate = require('./_array-species-create');
$export($export.P, 'Array', {
flatMap: function flatMap(callbackfn /* , thisArg */) {
var O = toObject(this);
var sourceLen, A;
aFunction(callbackfn);
sourceLen = toLength(O.length);
A = arraySpeciesCreate(O, 0);
flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]);
return A;
}
});
require('./_add-to-unscopables')('flatMap');
},{"./_a-function":159,"./_add-to-unscopables":161,"./_array-species-create":171,"./_export":189,"./_flatten-into-array":194,"./_to-length":271,"./_to-object":272}],422:[function(require,module,exports){
'use strict';
// https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten
var $export = require('./_export');
var flattenIntoArray = require('./_flatten-into-array');
var toObject = require('./_to-object');
var toLength = require('./_to-length');
var toInteger = require('./_to-integer');
var arraySpeciesCreate = require('./_array-species-create');
$export($export.P, 'Array', {
flatten: function flatten(/* depthArg = 1 */) {
var depthArg = arguments[0];
var O = toObject(this);
var sourceLen = toLength(O.length);
var A = arraySpeciesCreate(O, 0);
flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg));
return A;
}
});
require('./_add-to-unscopables')('flatten');
},{"./_add-to-unscopables":161,"./_array-species-create":171,"./_export":189,"./_flatten-into-array":194,"./_to-integer":269,"./_to-length":271,"./_to-object":272}],423:[function(require,module,exports){
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = require('./_export');
var $includes = require('./_array-includes')(true);
$export($export.P, 'Array', {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')('includes');
},{"./_add-to-unscopables":161,"./_array-includes":167,"./_export":189}],424:[function(require,module,exports){
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = require('./_export');
var microtask = require('./_microtask')();
var process = require('./_global').process;
var isNode = require('./_cof')(process) == 'process';
$export($export.G, {
asap: function asap(fn) {
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
},{"./_cof":174,"./_export":189,"./_global":196,"./_microtask":223}],425:[function(require,module,exports){
// https://github.com/ljharb/proposal-is-error
var $export = require('./_export');
var cof = require('./_cof');
$export($export.S, 'Error', {
isError: function isError(it) {
return cof(it) === 'Error';
}
});
},{"./_cof":174,"./_export":189}],426:[function(require,module,exports){
// https://github.com/tc39/proposal-global
var $export = require('./_export');
$export($export.G, { global: require('./_global') });
},{"./_export":189,"./_global":196}],427:[function(require,module,exports){
// https://tc39.github.io/proposal-setmap-offrom/#sec-map.from
require('./_set-collection-from')('Map');
},{"./_set-collection-from":250}],428:[function(require,module,exports){
// https://tc39.github.io/proposal-setmap-offrom/#sec-map.of
require('./_set-collection-of')('Map');
},{"./_set-collection-of":251}],429:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = require('./_export');
$export($export.P + $export.R, 'Map', { toJSON: require('./_collection-to-json')('Map') });
},{"./_collection-to-json":176,"./_export":189}],430:[function(require,module,exports){
// https://rwaldron.github.io/proposal-math-extensions/
var $export = require('./_export');
$export($export.S, 'Math', {
clamp: function clamp(x, lower, upper) {
return Math.min(upper, Math.max(lower, x));
}
});
},{"./_export":189}],431:[function(require,module,exports){
// https://rwaldron.github.io/proposal-math-extensions/
var $export = require('./_export');
$export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 });
},{"./_export":189}],432:[function(require,module,exports){
// https://rwaldron.github.io/proposal-math-extensions/
var $export = require('./_export');
var RAD_PER_DEG = 180 / Math.PI;
$export($export.S, 'Math', {
degrees: function degrees(radians) {
return radians * RAD_PER_DEG;
}
});
},{"./_export":189}],433:[function(require,module,exports){
// https://rwaldron.github.io/proposal-math-extensions/
var $export = require('./_export');
var scale = require('./_math-scale');
var fround = require('./_math-fround');
$export($export.S, 'Math', {
fscale: function fscale(x, inLow, inHigh, outLow, outHigh) {
return fround(scale(x, inLow, inHigh, outLow, outHigh));
}
});
},{"./_export":189,"./_math-fround":217,"./_math-scale":219}],434:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1) {
var $x0 = x0 >>> 0;
var $x1 = x1 >>> 0;
var $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
},{"./_export":189}],435:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
imulh: function imulh(u, v) {
var UINT16 = 0xffff;
var $u = +u;
var $v = +v;
var u0 = $u & UINT16;
var v0 = $v & UINT16;
var u1 = $u >> 16;
var v1 = $v >> 16;
var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
},{"./_export":189}],436:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1) {
var $x0 = x0 >>> 0;
var $x1 = x1 >>> 0;
var $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
},{"./_export":189}],437:[function(require,module,exports){
// https://rwaldron.github.io/proposal-math-extensions/
var $export = require('./_export');
$export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI });
},{"./_export":189}],438:[function(require,module,exports){
// https://rwaldron.github.io/proposal-math-extensions/
var $export = require('./_export');
var DEG_PER_RAD = Math.PI / 180;
$export($export.S, 'Math', {
radians: function radians(degrees) {
return degrees * DEG_PER_RAD;
}
});
},{"./_export":189}],439:[function(require,module,exports){
// https://rwaldron.github.io/proposal-math-extensions/
var $export = require('./_export');
$export($export.S, 'Math', { scale: require('./_math-scale') });
},{"./_export":189,"./_math-scale":219}],440:[function(require,module,exports){
// http://jfbastien.github.io/papers/Math.signbit.html
var $export = require('./_export');
$export($export.S, 'Math', { signbit: function signbit(x) {
// eslint-disable-next-line no-self-compare
return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0;
} });
},{"./_export":189}],441:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
umulh: function umulh(u, v) {
var UINT16 = 0xffff;
var $u = +u;
var $v = +v;
var u0 = $u & UINT16;
var v0 = $v & UINT16;
var u1 = $u >>> 16;
var v1 = $v >>> 16;
var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
},{"./_export":189}],442:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var toObject = require('./_to-object');
var aFunction = require('./_a-function');
var $defineProperty = require('./_object-dp');
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__defineGetter__: function __defineGetter__(P, getter) {
$defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true });
}
});
},{"./_a-function":159,"./_descriptors":185,"./_export":189,"./_object-dp":227,"./_object-forced-pam":229,"./_to-object":272}],443:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var toObject = require('./_to-object');
var aFunction = require('./_a-function');
var $defineProperty = require('./_object-dp');
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__defineSetter__: function __defineSetter__(P, setter) {
$defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true });
}
});
},{"./_a-function":159,"./_descriptors":185,"./_export":189,"./_object-dp":227,"./_object-forced-pam":229,"./_to-object":272}],444:[function(require,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = require('./_export');
var $entries = require('./_object-to-array')(true);
$export($export.S, 'Object', {
entries: function entries(it) {
return $entries(it);
}
});
},{"./_export":189,"./_object-to-array":239}],445:[function(require,module,exports){
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = require('./_export');
var ownKeys = require('./_own-keys');
var toIObject = require('./_to-iobject');
var gOPD = require('./_object-gopd');
var createProperty = require('./_create-property');
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
var O = toIObject(object);
var getDesc = gOPD.f;
var keys = ownKeys(O);
var result = {};
var i = 0;
var key, desc;
while (keys.length > i) {
desc = getDesc(O, key = keys[i++]);
if (desc !== undefined) createProperty(result, key, desc);
}
return result;
}
});
},{"./_create-property":180,"./_export":189,"./_object-gopd":230,"./_own-keys":240,"./_to-iobject":270}],446:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var toObject = require('./_to-object');
var toPrimitive = require('./_to-primitive');
var getPrototypeOf = require('./_object-gpo');
var getOwnPropertyDescriptor = require('./_object-gopd').f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__lookupGetter__: function __lookupGetter__(P) {
var O = toObject(this);
var K = toPrimitive(P, true);
var D;
do {
if (D = getOwnPropertyDescriptor(O, K)) return D.get;
} while (O = getPrototypeOf(O));
}
});
},{"./_descriptors":185,"./_export":189,"./_object-forced-pam":229,"./_object-gopd":230,"./_object-gpo":234,"./_to-object":272,"./_to-primitive":273}],447:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var toObject = require('./_to-object');
var toPrimitive = require('./_to-primitive');
var getPrototypeOf = require('./_object-gpo');
var getOwnPropertyDescriptor = require('./_object-gopd').f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__lookupSetter__: function __lookupSetter__(P) {
var O = toObject(this);
var K = toPrimitive(P, true);
var D;
do {
if (D = getOwnPropertyDescriptor(O, K)) return D.set;
} while (O = getPrototypeOf(O));
}
});
},{"./_descriptors":185,"./_export":189,"./_object-forced-pam":229,"./_object-gopd":230,"./_object-gpo":234,"./_to-object":272,"./_to-primitive":273}],448:[function(require,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = require('./_export');
var $values = require('./_object-to-array')(false);
$export($export.S, 'Object', {
values: function values(it) {
return $values(it);
}
});
},{"./_export":189,"./_object-to-array":239}],449:[function(require,module,exports){
'use strict';
// https://github.com/zenparsing/es-observable
var $export = require('./_export');
var global = require('./_global');
var core = require('./_core');
var microtask = require('./_microtask')();
var OBSERVABLE = require('./_wks')('observable');
var aFunction = require('./_a-function');
var anObject = require('./_an-object');
var anInstance = require('./_an-instance');
var redefineAll = require('./_redefine-all');
var hide = require('./_hide');
var forOf = require('./_for-of');
var RETURN = forOf.RETURN;
var getMethod = function (fn) {
return fn == null ? undefined : aFunction(fn);
};
var cleanupSubscription = function (subscription) {
var cleanup = subscription._c;
if (cleanup) {
subscription._c = undefined;
cleanup();
}
};
var subscriptionClosed = function (subscription) {
return subscription._o === undefined;
};
var closeSubscription = function (subscription) {
if (!subscriptionClosed(subscription)) {
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
var Subscription = function (observer, subscriber) {
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
var cleanup = subscriber(observer);
var subscription = cleanup;
if (cleanup != null) {
if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
} catch (e) {
observer.error(e);
return;
} if (subscriptionClosed(this)) cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
unsubscribe: function unsubscribe() { closeSubscription(this); }
});
var SubscriptionObserver = function (subscription) {
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
next: function next(value) {
var subscription = this._s;
if (!subscriptionClosed(subscription)) {
var observer = subscription._o;
try {
var m = getMethod(observer.next);
if (m) return m.call(observer, value);
} catch (e) {
try {
closeSubscription(subscription);
} finally {
throw e;
}
}
}
},
error: function error(value) {
var subscription = this._s;
if (subscriptionClosed(subscription)) throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
if (!m) throw value;
value = m.call(observer, value);
} catch (e) {
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
},
complete: function complete(value) {
var subscription = this._s;
if (!subscriptionClosed(subscription)) {
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
} catch (e) {
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
}
}
});
var $Observable = function Observable(subscriber) {
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
subscribe: function subscribe(observer) {
return new Subscription(observer, this._f);
},
forEach: function forEach(fn) {
var that = this;
return new (core.Promise || global.Promise)(function (resolve, reject) {
aFunction(fn);
var subscription = that.subscribe({
next: function (value) {
try {
return fn(value);
} catch (e) {
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
}
});
redefineAll($Observable, {
from: function from(x) {
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
if (method) {
var observable = anObject(method.call(x));
return observable.constructor === C ? observable : new C(function (observer) {
return observable.subscribe(observer);
});
}
return new C(function (observer) {
var done = false;
microtask(function () {
if (!done) {
try {
if (forOf(x, false, function (it) {
observer.next(it);
if (done) return RETURN;
}) === RETURN) return;
} catch (e) {
if (done) throw e;
observer.error(e);
return;
} observer.complete();
}
});
return function () { done = true; };
});
},
of: function of() {
for (var i = 0, l = arguments.length, items = Array(l); i < l;) items[i] = arguments[i++];
return new (typeof this === 'function' ? this : $Observable)(function (observer) {
var done = false;
microtask(function () {
if (!done) {
for (var j = 0; j < items.length; ++j) {
observer.next(items[j]);
if (done) return;
} observer.complete();
}
});
return function () { done = true; };
});
}
});
hide($Observable.prototype, OBSERVABLE, function () { return this; });
$export($export.G, { Observable: $Observable });
require('./_set-species')('Observable');
},{"./_a-function":159,"./_an-instance":162,"./_an-object":163,"./_core":179,"./_export":189,"./_for-of":195,"./_global":196,"./_hide":198,"./_microtask":223,"./_redefine-all":246,"./_set-species":253,"./_wks":281}],450:[function(require,module,exports){
arguments[4][154][0].apply(exports,arguments)
},{"./_core":179,"./_export":189,"./_global":196,"./_promise-resolve":244,"./_species-constructor":257,"dup":154}],451:[function(require,module,exports){
arguments[4][155][0].apply(exports,arguments)
},{"./_export":189,"./_new-promise-capability":224,"./_perform":243,"dup":155}],452:[function(require,module,exports){
var metadata = require('./_metadata');
var anObject = require('./_an-object');
var toMetaKey = metadata.key;
var ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) {
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
} });
},{"./_an-object":163,"./_metadata":222}],453:[function(require,module,exports){
var metadata = require('./_metadata');
var anObject = require('./_an-object');
var toMetaKey = metadata.key;
var getOrCreateMetadataMap = metadata.map;
var store = metadata.store;
metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) {
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]);
var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false;
if (metadataMap.size) return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
} });
},{"./_an-object":163,"./_metadata":222}],454:[function(require,module,exports){
var Set = require('./es6.set');
var from = require('./_array-from-iterable');
var metadata = require('./_metadata');
var anObject = require('./_an-object');
var getPrototypeOf = require('./_object-gpo');
var ordinaryOwnMetadataKeys = metadata.keys;
var toMetaKey = metadata.key;
var ordinaryMetadataKeys = function (O, P) {
var oKeys = ordinaryOwnMetadataKeys(O, P);
var parent = getPrototypeOf(O);
if (parent === null) return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) {
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
} });
},{"./_an-object":163,"./_array-from-iterable":166,"./_metadata":222,"./_object-gpo":234,"./es6.set":384}],455:[function(require,module,exports){
var metadata = require('./_metadata');
var anObject = require('./_an-object');
var getPrototypeOf = require('./_object-gpo');
var ordinaryHasOwnMetadata = metadata.has;
var ordinaryGetOwnMetadata = metadata.get;
var toMetaKey = metadata.key;
var ordinaryGetMetadata = function (MetadataKey, O, P) {
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) {
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
},{"./_an-object":163,"./_metadata":222,"./_object-gpo":234}],456:[function(require,module,exports){
var metadata = require('./_metadata');
var anObject = require('./_an-object');
var ordinaryOwnMetadataKeys = metadata.keys;
var toMetaKey = metadata.key;
metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) {
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
} });
},{"./_an-object":163,"./_metadata":222}],457:[function(require,module,exports){
var metadata = require('./_metadata');
var anObject = require('./_an-object');
var ordinaryGetOwnMetadata = metadata.get;
var toMetaKey = metadata.key;
metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) {
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
},{"./_an-object":163,"./_metadata":222}],458:[function(require,module,exports){
var metadata = require('./_metadata');
var anObject = require('./_an-object');
var getPrototypeOf = require('./_object-gpo');
var ordinaryHasOwnMetadata = metadata.has;
var toMetaKey = metadata.key;
var ordinaryHasMetadata = function (MetadataKey, O, P) {
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn) return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) {
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
},{"./_an-object":163,"./_metadata":222,"./_object-gpo":234}],459:[function(require,module,exports){
var metadata = require('./_metadata');
var anObject = require('./_an-object');
var ordinaryHasOwnMetadata = metadata.has;
var toMetaKey = metadata.key;
metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) {
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
},{"./_an-object":163,"./_metadata":222}],460:[function(require,module,exports){
var $metadata = require('./_metadata');
var anObject = require('./_an-object');
var aFunction = require('./_a-function');
var toMetaKey = $metadata.key;
var ordinaryDefineOwnMetadata = $metadata.set;
$metadata.exp({ metadata: function metadata(metadataKey, metadataValue) {
return function decorator(target, targetKey) {
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
} });
},{"./_a-function":159,"./_an-object":163,"./_metadata":222}],461:[function(require,module,exports){
// https://tc39.github.io/proposal-setmap-offrom/#sec-set.from
require('./_set-collection-from')('Set');
},{"./_set-collection-from":250}],462:[function(require,module,exports){
// https://tc39.github.io/proposal-setmap-offrom/#sec-set.of
require('./_set-collection-of')('Set');
},{"./_set-collection-of":251}],463:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = require('./_export');
$export($export.P + $export.R, 'Set', { toJSON: require('./_collection-to-json')('Set') });
},{"./_collection-to-json":176,"./_export":189}],464:[function(require,module,exports){
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = require('./_export');
var $at = require('./_string-at')(true);
$export($export.P, 'String', {
at: function at(pos) {
return $at(this, pos);
}
});
},{"./_export":189,"./_string-at":259}],465:[function(require,module,exports){
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = require('./_export');
var defined = require('./_defined');
var toLength = require('./_to-length');
var isRegExp = require('./_is-regexp');
var getFlags = require('./_flags');
var RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function (regexp, string) {
this._r = regexp;
this._s = string;
};
require('./_iter-create')($RegExpStringIterator, 'RegExp String', function next() {
var match = this._r.exec(this._s);
return { value: match, done: match === null };
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp) {
defined(this);
if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!');
var S = String(this);
var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp);
var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
},{"./_defined":184,"./_export":189,"./_flags":193,"./_is-regexp":208,"./_iter-create":210,"./_to-length":271}],466:[function(require,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = require('./_export');
var $pad = require('./_string-pad');
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
},{"./_export":189,"./_string-pad":262}],467:[function(require,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = require('./_export');
var $pad = require('./_string-pad');
$export($export.P, 'String', {
padStart: function padStart(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
},{"./_export":189,"./_string-pad":262}],468:[function(require,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./_string-trim')('trimLeft', function ($trim) {
return function trimLeft() {
return $trim(this, 1);
};
}, 'trimStart');
},{"./_string-trim":264}],469:[function(require,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./_string-trim')('trimRight', function ($trim) {
return function trimRight() {
return $trim(this, 2);
};
}, 'trimEnd');
},{"./_string-trim":264}],470:[function(require,module,exports){
arguments[4][156][0].apply(exports,arguments)
},{"./_wks-define":279,"dup":156}],471:[function(require,module,exports){
arguments[4][157][0].apply(exports,arguments)
},{"./_wks-define":279,"dup":157}],472:[function(require,module,exports){
// https://github.com/tc39/proposal-global
var $export = require('./_export');
$export($export.S, 'System', { global: require('./_global') });
},{"./_export":189,"./_global":196}],473:[function(require,module,exports){
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from
require('./_set-collection-from')('WeakMap');
},{"./_set-collection-from":250}],474:[function(require,module,exports){
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of
require('./_set-collection-of')('WeakMap');
},{"./_set-collection-of":251}],475:[function(require,module,exports){
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from
require('./_set-collection-from')('WeakSet');
},{"./_set-collection-from":250}],476:[function(require,module,exports){
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of
require('./_set-collection-of')('WeakSet');
},{"./_set-collection-of":251}],477:[function(require,module,exports){
var $iterators = require('./es6.array.iterator');
var getKeys = require('./_object-keys');
var redefine = require('./_redefine');
var global = require('./_global');
var hide = require('./_hide');
var Iterators = require('./_iterators');
var wks = require('./_wks');
var ITERATOR = wks('iterator');
var TO_STRING_TAG = wks('toStringTag');
var ArrayValues = Iterators.Array;
var DOMIterables = {
CSSRuleList: true, // TODO: Not spec compliant, should be false.
CSSStyleDeclaration: false,
CSSValueList: false,
ClientRectList: false,
DOMRectList: false,
DOMStringList: false,
DOMTokenList: true,
DataTransferItemList: false,
FileList: false,
HTMLAllCollection: false,
HTMLCollection: false,
HTMLFormElement: false,
HTMLSelectElement: false,
MediaList: true, // TODO: Not spec compliant, should be false.
MimeTypeArray: false,
NamedNodeMap: false,
NodeList: true,
PaintRequestList: false,
Plugin: false,
PluginArray: false,
SVGLengthList: false,
SVGNumberList: false,
SVGPathSegList: false,
SVGPointList: false,
SVGStringList: false,
SVGTransformList: false,
SourceBufferList: false,
StyleSheetList: true, // TODO: Not spec compliant, should be false.
TextTrackCueList: false,
TextTrackList: false,
TouchList: false
};
for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {
var NAME = collections[i];
var explicit = DOMIterables[NAME];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
var key;
if (proto) {
if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);
if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true);
}
}
},{"./_global":196,"./_hide":198,"./_iterators":214,"./_object-keys":236,"./_redefine":247,"./_wks":281,"./es6.array.iterator":294}],478:[function(require,module,exports){
var $export = require('./_export');
var $task = require('./_task');
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
},{"./_export":189,"./_task":266}],479:[function(require,module,exports){
// ie9- setTimeout & setInterval additional parameters fix
var global = require('./_global');
var $export = require('./_export');
var navigator = global.navigator;
var slice = [].slice;
var MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function (set) {
return function (fn, time /* , ...args */) {
var boundArgs = arguments.length > 2;
var args = boundArgs ? slice.call(arguments, 2) : false;
return set(boundArgs ? function () {
// eslint-disable-next-line no-new-func
(typeof fn == 'function' ? fn : Function(fn)).apply(this, args);
} : fn, time);
};
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
},{"./_export":189,"./_global":196}],480:[function(require,module,exports){
require('./modules/es6.symbol');
require('./modules/es6.object.create');
require('./modules/es6.object.define-property');
require('./modules/es6.object.define-properties');
require('./modules/es6.object.get-own-property-descriptor');
require('./modules/es6.object.get-prototype-of');
require('./modules/es6.object.keys');
require('./modules/es6.object.get-own-property-names');
require('./modules/es6.object.freeze');
require('./modules/es6.object.seal');
require('./modules/es6.object.prevent-extensions');
require('./modules/es6.object.is-frozen');
require('./modules/es6.object.is-sealed');
require('./modules/es6.object.is-extensible');
require('./modules/es6.object.assign');
require('./modules/es6.object.is');
require('./modules/es6.object.set-prototype-of');
require('./modules/es6.object.to-string');
require('./modules/es6.function.bind');
require('./modules/es6.function.name');
require('./modules/es6.function.has-instance');
require('./modules/es6.parse-int');
require('./modules/es6.parse-float');
require('./modules/es6.number.constructor');
require('./modules/es6.number.to-fixed');
require('./modules/es6.number.to-precision');
require('./modules/es6.number.epsilon');
require('./modules/es6.number.is-finite');
require('./modules/es6.number.is-integer');
require('./modules/es6.number.is-nan');
require('./modules/es6.number.is-safe-integer');
require('./modules/es6.number.max-safe-integer');
require('./modules/es6.number.min-safe-integer');
require('./modules/es6.number.parse-float');
require('./modules/es6.number.parse-int');
require('./modules/es6.math.acosh');
require('./modules/es6.math.asinh');
require('./modules/es6.math.atanh');
require('./modules/es6.math.cbrt');
require('./modules/es6.math.clz32');
require('./modules/es6.math.cosh');
require('./modules/es6.math.expm1');
require('./modules/es6.math.fround');
require('./modules/es6.math.hypot');
require('./modules/es6.math.imul');
require('./modules/es6.math.log10');
require('./modules/es6.math.log1p');
require('./modules/es6.math.log2');
require('./modules/es6.math.sign');
require('./modules/es6.math.sinh');
require('./modules/es6.math.tanh');
require('./modules/es6.math.trunc');
require('./modules/es6.string.from-code-point');
require('./modules/es6.string.raw');
require('./modules/es6.string.trim');
require('./modules/es6.string.iterator');
require('./modules/es6.string.code-point-at');
require('./modules/es6.string.ends-with');
require('./modules/es6.string.includes');
require('./modules/es6.string.repeat');
require('./modules/es6.string.starts-with');
require('./modules/es6.string.anchor');
require('./modules/es6.string.big');
require('./modules/es6.string.blink');
require('./modules/es6.string.bold');
require('./modules/es6.string.fixed');
require('./modules/es6.string.fontcolor');
require('./modules/es6.string.fontsize');
require('./modules/es6.string.italics');
require('./modules/es6.string.link');
require('./modules/es6.string.small');
require('./modules/es6.string.strike');
require('./modules/es6.string.sub');
require('./modules/es6.string.sup');
require('./modules/es6.date.now');
require('./modules/es6.date.to-json');
require('./modules/es6.date.to-iso-string');
require('./modules/es6.date.to-string');
require('./modules/es6.date.to-primitive');
require('./modules/es6.array.is-array');
require('./modules/es6.array.from');
require('./modules/es6.array.of');
require('./modules/es6.array.join');
require('./modules/es6.array.slice');
require('./modules/es6.array.sort');
require('./modules/es6.array.for-each');
require('./modules/es6.array.map');
require('./modules/es6.array.filter');
require('./modules/es6.array.some');
require('./modules/es6.array.every');
require('./modules/es6.array.reduce');
require('./modules/es6.array.reduce-right');
require('./modules/es6.array.index-of');
require('./modules/es6.array.last-index-of');
require('./modules/es6.array.copy-within');
require('./modules/es6.array.fill');
require('./modules/es6.array.find');
require('./modules/es6.array.find-index');
require('./modules/es6.array.species');
require('./modules/es6.array.iterator');
require('./modules/es6.regexp.constructor');
require('./modules/es6.regexp.to-string');
require('./modules/es6.regexp.flags');
require('./modules/es6.regexp.match');
require('./modules/es6.regexp.replace');
require('./modules/es6.regexp.search');
require('./modules/es6.regexp.split');
require('./modules/es6.promise');
require('./modules/es6.map');
require('./modules/es6.set');
require('./modules/es6.weak-map');
require('./modules/es6.weak-set');
require('./modules/es6.typed.array-buffer');
require('./modules/es6.typed.data-view');
require('./modules/es6.typed.int8-array');
require('./modules/es6.typed.uint8-array');
require('./modules/es6.typed.uint8-clamped-array');
require('./modules/es6.typed.int16-array');
require('./modules/es6.typed.uint16-array');
require('./modules/es6.typed.int32-array');
require('./modules/es6.typed.uint32-array');
require('./modules/es6.typed.float32-array');
require('./modules/es6.typed.float64-array');
require('./modules/es6.reflect.apply');
require('./modules/es6.reflect.construct');
require('./modules/es6.reflect.define-property');
require('./modules/es6.reflect.delete-property');
require('./modules/es6.reflect.enumerate');
require('./modules/es6.reflect.get');
require('./modules/es6.reflect.get-own-property-descriptor');
require('./modules/es6.reflect.get-prototype-of');
require('./modules/es6.reflect.has');
require('./modules/es6.reflect.is-extensible');
require('./modules/es6.reflect.own-keys');
require('./modules/es6.reflect.prevent-extensions');
require('./modules/es6.reflect.set');
require('./modules/es6.reflect.set-prototype-of');
require('./modules/es7.array.includes');
require('./modules/es7.array.flat-map');
require('./modules/es7.array.flatten');
require('./modules/es7.string.at');
require('./modules/es7.string.pad-start');
require('./modules/es7.string.pad-end');
require('./modules/es7.string.trim-left');
require('./modules/es7.string.trim-right');
require('./modules/es7.string.match-all');
require('./modules/es7.symbol.async-iterator');
require('./modules/es7.symbol.observable');
require('./modules/es7.object.get-own-property-descriptors');
require('./modules/es7.object.values');
require('./modules/es7.object.entries');
require('./modules/es7.object.define-getter');
require('./modules/es7.object.define-setter');
require('./modules/es7.object.lookup-getter');
require('./modules/es7.object.lookup-setter');
require('./modules/es7.map.to-json');
require('./modules/es7.set.to-json');
require('./modules/es7.map.of');
require('./modules/es7.set.of');
require('./modules/es7.weak-map.of');
require('./modules/es7.weak-set.of');
require('./modules/es7.map.from');
require('./modules/es7.set.from');
require('./modules/es7.weak-map.from');
require('./modules/es7.weak-set.from');
require('./modules/es7.global');
require('./modules/es7.system.global');
require('./modules/es7.error.is-error');
require('./modules/es7.math.clamp');
require('./modules/es7.math.deg-per-rad');
require('./modules/es7.math.degrees');
require('./modules/es7.math.fscale');
require('./modules/es7.math.iaddh');
require('./modules/es7.math.isubh');
require('./modules/es7.math.imulh');
require('./modules/es7.math.rad-per-deg');
require('./modules/es7.math.radians');
require('./modules/es7.math.scale');
require('./modules/es7.math.umulh');
require('./modules/es7.math.signbit');
require('./modules/es7.promise.finally');
require('./modules/es7.promise.try');
require('./modules/es7.reflect.define-metadata');
require('./modules/es7.reflect.delete-metadata');
require('./modules/es7.reflect.get-metadata');
require('./modules/es7.reflect.get-metadata-keys');
require('./modules/es7.reflect.get-own-metadata');
require('./modules/es7.reflect.get-own-metadata-keys');
require('./modules/es7.reflect.has-metadata');
require('./modules/es7.reflect.has-own-metadata');
require('./modules/es7.reflect.metadata');
require('./modules/es7.asap');
require('./modules/es7.observable');
require('./modules/web.timers');
require('./modules/web.immediate');
require('./modules/web.dom.iterable');
module.exports = require('./modules/_core');
},{"./modules/_core":179,"./modules/es6.array.copy-within":284,"./modules/es6.array.every":285,"./modules/es6.array.fill":286,"./modules/es6.array.filter":287,"./modules/es6.array.find":289,"./modules/es6.array.find-index":288,"./modules/es6.array.for-each":290,"./modules/es6.array.from":291,"./modules/es6.array.index-of":292,"./modules/es6.array.is-array":293,"./modules/es6.array.iterator":294,"./modules/es6.array.join":295,"./modules/es6.array.last-index-of":296,"./modules/es6.array.map":297,"./modules/es6.array.of":298,"./modules/es6.array.reduce":300,"./modules/es6.array.reduce-right":299,"./modules/es6.array.slice":301,"./modules/es6.array.some":302,"./modules/es6.array.sort":303,"./modules/es6.array.species":304,"./modules/es6.date.now":305,"./modules/es6.date.to-iso-string":306,"./modules/es6.date.to-json":307,"./modules/es6.date.to-primitive":308,"./modules/es6.date.to-string":309,"./modules/es6.function.bind":310,"./modules/es6.function.has-instance":311,"./modules/es6.function.name":312,"./modules/es6.map":313,"./modules/es6.math.acosh":314,"./modules/es6.math.asinh":315,"./modules/es6.math.atanh":316,"./modules/es6.math.cbrt":317,"./modules/es6.math.clz32":318,"./modules/es6.math.cosh":319,"./modules/es6.math.expm1":320,"./modules/es6.math.fround":321,"./modules/es6.math.hypot":322,"./modules/es6.math.imul":323,"./modules/es6.math.log10":324,"./modules/es6.math.log1p":325,"./modules/es6.math.log2":326,"./modules/es6.math.sign":327,"./modules/es6.math.sinh":328,"./modules/es6.math.tanh":329,"./modules/es6.math.trunc":330,"./modules/es6.number.constructor":331,"./modules/es6.number.epsilon":332,"./modules/es6.number.is-finite":333,"./modules/es6.number.is-integer":334,"./modules/es6.number.is-nan":335,"./modules/es6.number.is-safe-integer":336,"./modules/es6.number.max-safe-integer":337,"./modules/es6.number.min-safe-integer":338,"./modules/es6.number.parse-float":339,"./modules/es6.number.parse-int":340,"./modules/es6.number.to-fixed":341,"./modules/es6.number.to-precision":342,"./modules/es6.object.assign":343,"./modules/es6.object.create":344,"./modules/es6.object.define-properties":345,"./modules/es6.object.define-property":346,"./modules/es6.object.freeze":347,"./modules/es6.object.get-own-property-descriptor":348,"./modules/es6.object.get-own-property-names":349,"./modules/es6.object.get-prototype-of":350,"./modules/es6.object.is":354,"./modules/es6.object.is-extensible":351,"./modules/es6.object.is-frozen":352,"./modules/es6.object.is-sealed":353,"./modules/es6.object.keys":355,"./modules/es6.object.prevent-extensions":356,"./modules/es6.object.seal":357,"./modules/es6.object.set-prototype-of":358,"./modules/es6.object.to-string":359,"./modules/es6.parse-float":360,"./modules/es6.parse-int":361,"./modules/es6.promise":362,"./modules/es6.reflect.apply":363,"./modules/es6.reflect.construct":364,"./modules/es6.reflect.define-property":365,"./modules/es6.reflect.delete-property":366,"./modules/es6.reflect.enumerate":367,"./modules/es6.reflect.get":370,"./modules/es6.reflect.get-own-property-descriptor":368,"./modules/es6.reflect.get-prototype-of":369,"./modules/es6.reflect.has":371,"./modules/es6.reflect.is-extensible":372,"./modules/es6.reflect.own-keys":373,"./modules/es6.reflect.prevent-extensions":374,"./modules/es6.reflect.set":376,"./modules/es6.reflect.set-prototype-of":375,"./modules/es6.regexp.constructor":377,"./modules/es6.regexp.flags":378,"./modules/es6.regexp.match":379,"./modules/es6.regexp.replace":380,"./modules/es6.regexp.search":381,"./modules/es6.regexp.split":382,"./modules/es6.regexp.to-string":383,"./modules/es6.set":384,"./modules/es6.string.anchor":385,"./modules/es6.string.big":386,"./modules/es6.string.blink":387,"./modules/es6.string.bold":388,"./modules/es6.string.code-point-at":389,"./modules/es6.string.ends-with":390,"./modules/es6.string.fixed":391,"./modules/es6.string.fontcolor":392,"./modules/es6.string.fontsize":393,"./modules/es6.string.from-code-point":394,"./modules/es6.string.includes":395,"./modules/es6.string.italics":396,"./modules/es6.string.iterator":397,"./modules/es6.string.link":398,"./modules/es6.string.raw":399,"./modules/es6.string.repeat":400,"./modules/es6.string.small":401,"./modules/es6.string.starts-with":402,"./modules/es6.string.strike":403,"./modules/es6.string.sub":404,"./modules/es6.string.sup":405,"./modules/es6.string.trim":406,"./modules/es6.symbol":407,"./modules/es6.typed.array-buffer":408,"./modules/es6.typed.data-view":409,"./modules/es6.typed.float32-array":410,"./modules/es6.typed.float64-array":411,"./modules/es6.typed.int16-array":412,"./modules/es6.typed.int32-array":413,"./modules/es6.typed.int8-array":414,"./modules/es6.typed.uint16-array":415,"./modules/es6.typed.uint32-array":416,"./modules/es6.typed.uint8-array":417,"./modules/es6.typed.uint8-clamped-array":418,"./modules/es6.weak-map":419,"./modules/es6.weak-set":420,"./modules/es7.array.flat-map":421,"./modules/es7.array.flatten":422,"./modules/es7.array.includes":423,"./modules/es7.asap":424,"./modules/es7.error.is-error":425,"./modules/es7.global":426,"./modules/es7.map.from":427,"./modules/es7.map.of":428,"./modules/es7.map.to-json":429,"./modules/es7.math.clamp":430,"./modules/es7.math.deg-per-rad":431,"./modules/es7.math.degrees":432,"./modules/es7.math.fscale":433,"./modules/es7.math.iaddh":434,"./modules/es7.math.imulh":435,"./modules/es7.math.isubh":436,"./modules/es7.math.rad-per-deg":437,"./modules/es7.math.radians":438,"./modules/es7.math.scale":439,"./modules/es7.math.signbit":440,"./modules/es7.math.umulh":441,"./modules/es7.object.define-getter":442,"./modules/es7.object.define-setter":443,"./modules/es7.object.entries":444,"./modules/es7.object.get-own-property-descriptors":445,"./modules/es7.object.lookup-getter":446,"./modules/es7.object.lookup-setter":447,"./modules/es7.object.values":448,"./modules/es7.observable":449,"./modules/es7.promise.finally":450,"./modules/es7.promise.try":451,"./modules/es7.reflect.define-metadata":452,"./modules/es7.reflect.delete-metadata":453,"./modules/es7.reflect.get-metadata":455,"./modules/es7.reflect.get-metadata-keys":454,"./modules/es7.reflect.get-own-metadata":457,"./modules/es7.reflect.get-own-metadata-keys":456,"./modules/es7.reflect.has-metadata":458,"./modules/es7.reflect.has-own-metadata":459,"./modules/es7.reflect.metadata":460,"./modules/es7.set.from":461,"./modules/es7.set.of":462,"./modules/es7.set.to-json":463,"./modules/es7.string.at":464,"./modules/es7.string.match-all":465,"./modules/es7.string.pad-end":466,"./modules/es7.string.pad-start":467,"./modules/es7.string.trim-left":468,"./modules/es7.string.trim-right":469,"./modules/es7.symbol.async-iterator":470,"./modules/es7.symbol.observable":471,"./modules/es7.system.global":472,"./modules/es7.weak-map.from":473,"./modules/es7.weak-map.of":474,"./modules/es7.weak-set.from":475,"./modules/es7.weak-set.of":476,"./modules/web.dom.iterable":477,"./modules/web.immediate":478,"./modules/web.timers":479}],481:[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":522}],482:[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":483,"./core":484,"./enc-base64":485,"./evpkdf":487,"./md5":489}],483:[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":484}],484:[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;
}));
},{}],485:[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":484}],486:[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":484}],487:[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":484,"./hmac":488,"./sha1":490}],488:[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":484}],489:[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":484}],490:[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":484}],491:[function(require,module,exports){
'use strict';
/**
* this queue tracks the currently running database-interactions
* so we know when the database is in idle-state and can call
* requestIdlePromise for semi-important actions
*/
var util = require('./util');
var PROMISE_RESOLVE_MAP = new Map();
var PROMISE_TIMEOUT_MAP = new Map();
/**
* Creates a new Idle-Queue
* @constructor
* @param {number} [parallels=1] amount of parrallel runs of the limited-ressource
*/
var IdleQueue = function IdleQueue() {
var parallels = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
this._parallels = parallels || 1;
/**
* each lock() increased this number
* each unlock() decreases this number
* If _queueCounter==0, the state is in idle
* @type {Number}
*/
this._queueCounter = 0;
/**
* contains all promises that where added via requestIdlePromise()
* and not have been resolved
* @type {Array} _idleCalls with oldest promise last
*/
this._idleCalls = [];
this._lastHandleNumber = 0;
/**
* Contains the handleNumber on the left
* And the assigned promise on the right.
* This is stored so you can use cancelIdleCallback(handleNumber)
* to stop executing the callback.
* @type {Map}
*/
this._handlePromiseMap = new Map();
this._promiseHandleMap = new Map();
};
// STATICS
IdleQueue.prototype = {
isIdle: function isIdle() {
return this._queueCounter < this._parallels;
},
_newHandleNumber: function _newHandleNumber() {
this._lastHandleNumber++;
return this._lastHandleNumber;
},
/**
* creates a lock in the queue
* and returns an unlock-function to remove the lock from the queue
* @return {function} unlock function than must be called afterwards
*/
lock: function lock() {
var _this = this;
this._queueCounter++;
var unlock = function () {
return _this._unLock();
}.bind(this);
return unlock;
},
_unLock: function _unLock() {
this._queueCounter--;
this._tryIdleCall();
},
/**
* wraps a function with lock/unlock and runs it
* @param {function} fun
* @return {Promise}
*/
wrapCall: function wrapCall(fun) {
var unlock = this.lock();
var maybePromise = void 0;
try {
maybePromise = fun();
} catch (err) {
unlock();
throw err;
}
return Promise.resolve(maybePromise).then(function (ret) {
// sucessfull -> unlock before return
unlock();
return ret;
})['catch'](function (err) {
// not sucessfull -> unlock before throwing
unlock();
throw err;
});
},
/**
* does the same as requestIdleCallback() but uses promises instead of the callback
* @param {{timeout?: number}} options like timeout
* @return {Promise} promise that resolves when the database is in idle-mode
*/
requestIdlePromise: function requestIdlePromise(options) {
var _this2 = this;
options = options || {};
var resolve = void 0;
var prom = new Promise(function (res) {
return resolve = res;
});
var resolveFromOutside = function resolveFromOutside() {
_this2._removeIdlePromise(prom);
resolve();
};
PROMISE_RESOLVE_MAP.set(prom, resolveFromOutside);
if (options.timeout) {
// if timeout has passed, resolve promise even if not idle
var timeoutObj = setTimeout(function () {
PROMISE_RESOLVE_MAP.get(prom)();
}, options.timeout);
PROMISE_TIMEOUT_MAP.set(prom, timeoutObj);
}
this._idleCalls.unshift(prom);
this._tryIdleCall();
return prom;
},
/**
* remove the promise so it will never be resolved
* @param {Promise} promise from requestIdlePromise()
* @return {void}
*/
cancelIdlePromise: function cancelIdlePromise(promise) {
this._removeIdlePromise(promise);
this._removeIdlePromise(promise);
},
/**
* removes the promis from the queue and maps and also its corresponding handle-number
* @param {Promise} promise from requestIdlePromise()
* @return {void}
*/
_removeIdlePromise: function _removeIdlePromise(promise) {
// remove resolve-function
PROMISE_RESOLVE_MAP['delete'](promise);
// remove timeout if exists
var timeoutObj = PROMISE_TIMEOUT_MAP.get(promise);
if (timeoutObj) {
clearTimeout(timeoutObj);
PROMISE_TIMEOUT_MAP['delete'](promise);
}
// remove handle-nr if exists
var handle = this._promiseHandleMap.get(promise);
this._handlePromiseMap['delete'](handle);
this._promiseHandleMap['delete'](promise);
// remove from queue
var index = this._idleCalls.indexOf(promise);
this._idleCalls.splice(index, 1);
},
/**
* api equal to
* @link https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
* @param {Function} callback
* @param {options} options [description]
* @return {number} handle which can be used with cancelIdleCallback()
*/
requestIdleCallback: function requestIdleCallback(callback, options) {
var handle = this._newHandleNumber();
var promise = this.requestIdlePromise(options);
this._handlePromiseMap.set(handle, promise);
this._promiseHandleMap.set(promise, handle);
promise.then(function () {
return callback();
});
return handle;
},
/**
* API equal to
* @link https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelIdleCallback
* @param {number} handle returned from requestIdleCallback()
* @return {void}
*/
cancelIdleCallback: function cancelIdleCallback(handle) {
var promise = this._handlePromiseMap.get(handle);
this.cancelIdlePromise(promise);
},
/**
* resolves the last entry of this._idleCalls
* but only if the queue is empty
* @return {Promise}
*/
_tryIdleCall: function _tryIdleCall() {
var _this3 = this;
// ensure this does not run in parallel
if (this._tryIdleCallRunning || this._idleCalls.length === 0) return;
this._tryIdleCallRunning = true;
// w8 one tick
return util.nextTick().then(function () {
// check if queue empty
if (!_this3.isIdle()) {
_this3._tryIdleCallRunning = false;
return;
};
/**
* wait 1 tick here
* because many functions do IO->CPU->IO
* which means the queue is empty for a short time
* but the ressource is not idle
*/
return util.nextTick().then(function () {
// check if queue still empty
if (!_this3.isIdle()) {
_this3._tryIdleCallRunning = false;
return;
}
// ressource is idle
_this3._resolveOneIdleCall();
_this3._tryIdleCallRunning = false;
});
});
},
/**
* processes the oldest call of the idleCalls-queue
* @return {Promise}
*/
_resolveOneIdleCall: function _resolveOneIdleCall() {
var _this4 = this;
if (this._idleCalls.length === 0) return;
var oldestPromise = this._idleCalls[this._idleCalls.length - 1];
var resolveFun = PROMISE_RESOLVE_MAP.get(oldestPromise);
resolveFun();
// try to call the next tick
return util.nextTick().then(function () {
return _this4._tryIdleCall();
});
},
/**
* clears and resets everything
* @return {void}
*/
clear: function clear() {
var _this5 = this;
// remove all non-cleared
this._idleCalls.forEach(function (promise) {
return _this5._removeIdlePromise(promise);
});
this._queueCounter = 0;
this._idleCalls = [];
this._handlePromiseMap = new Map();
this._promiseHandleMap = new Map();
}
};
module.exports = IdleQueue;
},{"./util":493}],492:[function(require,module,exports){
'use strict';
var IdleQueue = require('./idle-queue');
module.exports = IdleQueue;
},{"./idle-queue":491}],493:[function(require,module,exports){
"use strict";
module.exports = function () {
var exports = {};
/**
* returns a promise that resolves on the next tick
* @return {Promise}
*/
exports.nextTick = function () {
return new Promise(function (res) {
return setTimeout(res, 0);
});
};
return exports;
}();
},{}],494:[function(require,module,exports){
(function (process){
/**
* 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() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// 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-zA-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);
}
/**
* 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) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
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) {}
}
}).call(this,require('_process'))
},{"./debug":495,"_process":609}],495:[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 = createDebug.debug = createDebug['default'] = createDebug;
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, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-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;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* 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);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? 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":563}],496:[function(require,module,exports){
var pSlice = Array.prototype.slice;
var objectKeys = require('./lib/keys.js');
var isArguments = require('./lib/is_arguments.js');
var deepEqual = module.exports = function (actual, expected, opts) {
if (!opts) opts = {};
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') {
return opts.strict ? actual === expected : actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, opts);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer (x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') return false;
return true;
}
function objEquiv(a, b, opts) {
var i, key;
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return deepEqual(a, b, opts);
}
if (isBuffer(a)) {
if (!isBuffer(b)) {
return false;
}
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
try {
var ka = objectKeys(a),
kb = objectKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) return false;
}
return typeof a === typeof b;
}
},{"./lib/is_arguments.js":497,"./lib/keys.js":498}],497:[function(require,module,exports){
var supportsArgumentsClass = (function(){
return Object.prototype.toString.call(arguments)
})() == '[object Arguments]';
exports = module.exports = supportsArgumentsClass ? supported : unsupported;
exports.supported = supported;
function supported(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
exports.unsupported = unsupported;
function unsupported(object){
return object &&
typeof object == 'object' &&
typeof object.length == 'number' &&
Object.prototype.hasOwnProperty.call(object, 'callee') &&
!Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
false;
};
},{}],498:[function(require,module,exports){
exports = module.exports = typeof Object.keys === 'function'
? Object.keys : shim;
exports.shim = shim;
function shim (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
},{}],499:[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":504,"util":774}],500:[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":522,"./deferred-iterator":499,"_process":609,"abstract-leveldown":504,"util":774}],501:[function(require,module,exports){
(function (process){
/* Copyright (c) 2017 Rod Vagg, MIT License */
function AbstractChainedBatch (db) {
this._db = db
this._operations = []
this._written = false
}
AbstractChainedBatch.prototype._serializeKey = function (key) {
return this._db._serializeKey(key)
}
AbstractChainedBatch.prototype._serializeValue = function (value) {
return this._db._serializeValue(value)
}
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
key = this._serializeKey(key)
value = this._serializeValue(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
key = this._serializeKey(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":609}],502:[function(require,module,exports){
(function (process){
/* Copyright (c) 2017 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":609}],503:[function(require,module,exports){
(function (Buffer,process){
/* Copyright (c) 2017 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'))
return callback(err)
key = this._serializeKey(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'))
return callback(err)
key = this._serializeKey(key)
value = this._serializeValue(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'))
return callback(err)
key = this._serializeKey(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'))
return callback(err)
if (err = this._checkKey(e.key, 'key'))
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')
start = this._serializeKey(start)
end = this._serializeKey(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._serializeKey = function (key) {
return this._isBuffer(key)
? key
: String(key)
}
AbstractLevelDOWN.prototype._serializeValue = function (value) {
if (value == null) return ''
return this._isBuffer(value) || process.browser ? value : String(value)
}
AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
if (obj === null || obj === undefined)
return new Error(type + ' cannot be `null` or `undefined`')
if (this._isBuffer(obj) && 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":522,"./abstract-chained-batch":501,"./abstract-iterator":502,"_process":609,"xtend":783}],504:[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":501,"./abstract-iterator":502,"./abstract-leveldown":503,"./is-leveldown":505}],505:[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":503}],506:[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;
},{}],507:[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":509}],508:[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":507}],509:[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
})
},{}],510:[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;
}
},{}],511:[function(require,module,exports){
"use strict"
module.exports = createRBTree
var RED = 0
var BLACK = 1
function RBNode(color, key, value, left, right, count) {
this._color = color
this.key = key
this.value = value
this.left = left
this.right = right
this._count = count
}
function cloneNode(node) {
return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
}
function repaint(color, node) {
return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
}
function recount(node) {
node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
}
function RedBlackTree(compare, root) {
this._compare = compare
this.root = root
}
var proto = RedBlackTree.prototype
Object.defineProperty(proto, "keys", {
get: function() {
var result = []
this.forEach(function(k,v) {
result.push(k)
})
return result
}
})
Object.defineProperty(proto, "values", {
get: function() {
var result = []
this.forEach(function(k,v) {
result.push(v)
})
return result
}
})
//Returns the number of nodes in the tree
Object.defineProperty(proto, "length", {
get: function() {
if(this.root) {
return this.root._count
}
return 0
}
})
//Insert a new item into the tree
proto.insert = function(key, value) {
var cmp = this._compare
//Find point to insert new node at
var n = this.root
var n_stack = []
var d_stack = []
while(n) {
var d = cmp(key, n.key)
n_stack.push(n)
d_stack.push(d)
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
//Rebuild path to leaf node
n_stack.push(new RBNode(RED, key, value, null, null, 1))
for(var s=n_stack.length-2; s>=0; --s) {
var n = n_stack[s]
if(d_stack[s] <= 0) {
n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
} else {
n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
}
}
//Rebalance tree using rotations
//console.log("start insert", key, d_stack)
for(var s=n_stack.length-1; s>1; --s) {
var p = n_stack[s-1]
var n = n_stack[s]
if(p._color === BLACK || n._color === BLACK) {
break
}
var pp = n_stack[s-2]
if(pp.left === p) {
if(p.left === n) {
var y = pp.right
if(y && y._color === RED) {
//console.log("LLr")
p._color = BLACK
pp.right = repaint(BLACK, y)
pp._color = RED
s -= 1
} else {
//console.log("LLb")
pp._color = RED
pp.left = p.right
p._color = BLACK
p.right = pp
n_stack[s-2] = p
n_stack[s-1] = n
recount(pp)
recount(p)
if(s >= 3) {
var ppp = n_stack[s-3]
if(ppp.left === pp) {
ppp.left = p
} else {
ppp.right = p
}
}
break
}
} else {
var y = pp.right
if(y && y._color === RED) {
//console.log("LRr")
p._color = BLACK
pp.right = repaint(BLACK, y)
pp._color = RED
s -= 1
} else {
//console.log("LRb")
p.right = n.left
pp._color = RED
pp.left = n.right
n._color = BLACK
n.left = p
n.right = pp
n_stack[s-2] = n
n_stack[s-1] = p
recount(pp)
recount(p)
recount(n)
if(s >= 3) {
var ppp = n_stack[s-3]
if(ppp.left === pp) {
ppp.left = n
} else {
ppp.right = n
}
}
break
}
}
} else {
if(p.right === n) {
var y = pp.left
if(y && y._color === RED) {
//console.log("RRr", y.key)
p._color = BLACK
pp.left = repaint(BLACK, y)
pp._color = RED
s -= 1
} else {
//console.log("RRb")
pp._color = RED
pp.right = p.left
p._color = BLACK
p.left = pp
n_stack[s-2] = p
n_stack[s-1] = n
recount(pp)
recount(p)
if(s >= 3) {
var ppp = n_stack[s-3]
if(ppp.right === pp) {
ppp.right = p
} else {
ppp.left = p
}
}
break
}
} else {
var y = pp.left
if(y && y._color === RED) {
//console.log("RLr")
p._color = BLACK
pp.left = repaint(BLACK, y)
pp._color = RED
s -= 1
} else {
//console.log("RLb")
p.left = n.right
pp._color = RED
pp.right = n.left
n._color = BLACK
n.right = p
n.left = pp
n_stack[s-2] = n
n_stack[s-1] = p
recount(pp)
recount(p)
recount(n)
if(s >= 3) {
var ppp = n_stack[s-3]
if(ppp.right === pp) {
ppp.right = n
} else {
ppp.left = n
}
}
break
}
}
}
}
//Return new tree
n_stack[0]._color = BLACK
return new RedBlackTree(cmp, n_stack[0])
}
//Visit all nodes inorder
function doVisitFull(visit, node) {
if(node.left) {
var v = doVisitFull(visit, node.left)
if(v) { return v }
}
var v = visit(node.key, node.value)
if(v) { return v }
if(node.right) {
return doVisitFull(visit, node.right)
}
}
//Visit half nodes in order
function doVisitHalf(lo, compare, visit, node) {
var l = compare(lo, node.key)
if(l <= 0) {
if(node.left) {
var v = doVisitHalf(lo, compare, visit, node.left)
if(v) { return v }
}
var v = visit(node.key, node.value)
if(v) { return v }
}
if(node.right) {
return doVisitHalf(lo, compare, visit, node.right)
}
}
//Visit all nodes within a range
function doVisit(lo, hi, compare, visit, node) {
var l = compare(lo, node.key)
var h = compare(hi, node.key)
var v
if(l <= 0) {
if(node.left) {
v = doVisit(lo, hi, compare, visit, node.left)
if(v) { return v }
}
if(h > 0) {
v = visit(node.key, node.value)
if(v) { return v }
}
}
if(h > 0 && node.right) {
return doVisit(lo, hi, compare, visit, node.right)
}
}
proto.forEach = function rbTreeForEach(visit, lo, hi) {
if(!this.root) {
return
}
switch(arguments.length) {
case 1:
return doVisitFull(visit, this.root)
break
case 2:
return doVisitHalf(lo, this._compare, visit, this.root)
break
case 3:
if(this._compare(lo, hi) >= 0) {
return
}
return doVisit(lo, hi, this._compare, visit, this.root)
break
}
}
//First item in list
Object.defineProperty(proto, "begin", {
get: function() {
var stack = []
var n = this.root
while(n) {
stack.push(n)
n = n.left
}
return new RedBlackTreeIterator(this, stack)
}
})
//Last item in list
Object.defineProperty(proto, "end", {
get: function() {
var stack = []
var n = this.root
while(n) {
stack.push(n)
n = n.right
}
return new RedBlackTreeIterator(this, stack)
}
})
//Find the ith item in the tree
proto.at = function(idx) {
if(idx < 0) {
return new RedBlackTreeIterator(this, [])
}
var n = this.root
var stack = []
while(true) {
stack.push(n)
if(n.left) {
if(idx < n.left._count) {
n = n.left
continue
}
idx -= n.left._count
}
if(!idx) {
return new RedBlackTreeIterator(this, stack)
}
idx -= 1
if(n.right) {
if(idx >= n.right._count) {
break
}
n = n.right
} else {
break
}
}
return new RedBlackTreeIterator(this, [])
}
proto.ge = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
var last_ptr = 0
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d <= 0) {
last_ptr = stack.length
}
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
stack.length = last_ptr
return new RedBlackTreeIterator(this, stack)
}
proto.gt = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
var last_ptr = 0
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d < 0) {
last_ptr = stack.length
}
if(d < 0) {
n = n.left
} else {
n = n.right
}
}
stack.length = last_ptr
return new RedBlackTreeIterator(this, stack)
}
proto.lt = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
var last_ptr = 0
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d > 0) {
last_ptr = stack.length
}
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
stack.length = last_ptr
return new RedBlackTreeIterator(this, stack)
}
proto.le = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
var last_ptr = 0
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d >= 0) {
last_ptr = stack.length
}
if(d < 0) {
n = n.left
} else {
n = n.right
}
}
stack.length = last_ptr
return new RedBlackTreeIterator(this, stack)
}
//Finds the item with key if it exists
proto.find = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d === 0) {
return new RedBlackTreeIterator(this, stack)
}
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
return new RedBlackTreeIterator(this, [])
}
//Removes item with key from tree
proto.remove = function(key) {
var iter = this.find(key)
if(iter) {
return iter.remove()
}
return this
}
//Returns the item at `key`
proto.get = function(key) {
var cmp = this._compare
var n = this.root
while(n) {
var d = cmp(key, n.key)
if(d === 0) {
return n.value
}
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
return
}
//Iterator for red black tree
function RedBlackTreeIterator(tree, stack) {
this.tree = tree
this._stack = stack
}
var iproto = RedBlackTreeIterator.prototype
//Test if iterator is valid
Object.defineProperty(iproto, "valid", {
get: function() {
return this._stack.length > 0
}
})
//Node of the iterator
Object.defineProperty(iproto, "node", {
get: function() {
if(this._stack.length > 0) {
return this._stack[this._stack.length-1]
}
return null
},
enumerable: true
})
//Makes a copy of an iterator
iproto.clone = function() {
return new RedBlackTreeIterator(this.tree, this._stack.slice())
}
//Swaps two nodes
function swapNode(n, v) {
n.key = v.key
n.value = v.value
n.left = v.left
n.right = v.right
n._color = v._color
n._count = v._count
}
//Fix up a double black node in a tree
function fixDoubleBlack(stack) {
var n, p, s, z
for(var i=stack.length-1; i>=0; --i) {
n = stack[i]
if(i === 0) {
n._color = BLACK
return
}
//console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
p = stack[i-1]
if(p.left === n) {
//console.log("left child")
s = p.right
if(s.right && s.right._color === RED) {
//console.log("case 1: right sibling child red")
s = p.right = cloneNode(s)
z = s.right = cloneNode(s.right)
p.right = s.left
s.left = p
s.right = z
s._color = p._color
n._color = BLACK
p._color = BLACK
z._color = BLACK
recount(p)
recount(s)
if(i > 1) {
var pp = stack[i-2]
if(pp.left === p) {
pp.left = s
} else {
pp.right = s
}
}
stack[i-1] = s
return
} else if(s.left && s.left._color === RED) {
//console.log("case 1: left sibling child red")
s = p.right = cloneNode(s)
z = s.left = cloneNode(s.left)
p.right = z.left
s.left = z.right
z.left = p
z.right = s
z._color = p._color
p._color = BLACK
s._color = BLACK
n._color = BLACK
recount(p)
recount(s)
recount(z)
if(i > 1) {
var pp = stack[i-2]
if(pp.left === p) {
pp.left = z
} else {
pp.right = z
}
}
stack[i-1] = z
return
}
if(s._color === BLACK) {
if(p._color === RED) {
//console.log("case 2: black sibling, red parent", p.right.value)
p._color = BLACK
p.right = repaint(RED, s)
return
} else {
//console.log("case 2: black sibling, black parent", p.right.value)
p.right = repaint(RED, s)
continue
}
} else {
//console.log("case 3: red sibling")
s = cloneNode(s)
p.right = s.left
s.left = p
s._color = p._color
p._color = RED
recount(p)
recount(s)
if(i > 1) {
var pp = stack[i-2]
if(pp.left === p) {
pp.left = s
} else {
pp.right = s
}
}
stack[i-1] = s
stack[i] = p
if(i+1 < stack.length) {
stack[i+1] = n
} else {
stack.push(n)
}
i = i+2
}
} else {
//console.log("right child")
s = p.left
if(s.left && s.left._color === RED) {
//console.log("case 1: left sibling child red", p.value, p._color)
s = p.left = cloneNode(s)
z = s.left = cloneNode(s.left)
p.left = s.right
s.right = p
s.left = z
s._color = p._color
n._color = BLACK
p._color = BLACK
z._color = BLACK
recount(p)
recount(s)
if(i > 1) {
var pp = stack[i-2]
if(pp.right === p) {
pp.right = s
} else {
pp.left = s
}
}
stack[i-1] = s
return
} else if(s.right && s.right._color === RED) {
//console.log("case 1: right sibling child red")
s = p.left = cloneNode(s)
z = s.right = cloneNode(s.right)
p.left = z.right
s.right = z.left
z.right = p
z.left = s
z._color = p._color
p._color = BLACK
s._color = BLACK
n._color = BLACK
recount(p)
recount(s)
recount(z)
if(i > 1) {
var pp = stack[i-2]
if(pp.right === p) {
pp.right = z
} else {
pp.left = z
}
}
stack[i-1] = z
return
}
if(s._color === BLACK) {
if(p._color === RED) {
//console.log("case 2: black sibling, red parent")
p._color = BLACK
p.left = repaint(RED, s)
return
} else {
//console.log("case 2: black sibling, black parent")
p.left = repaint(RED, s)
continue
}
} else {
//console.log("case 3: red sibling")
s = cloneNode(s)
p.left = s.right
s.right = p
s._color = p._color
p._color = RED
recount(p)
recount(s)
if(i > 1) {
var pp = stack[i-2]
if(pp.right === p) {
pp.right = s
} else {
pp.left = s
}
}
stack[i-1] = s
stack[i] = p
if(i+1 < stack.length) {
stack[i+1] = n
} else {
stack.push(n)
}
i = i+2
}
}
}
}
//Removes item at iterator from tree
iproto.remove = function() {
var stack = this._stack
if(stack.length === 0) {
return this.tree
}
//First copy path to node
var cstack = new Array(stack.length)
var n = stack[stack.length-1]
cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
for(var i=stack.length-2; i>=0; --i) {
var n = stack[i]
if(n.left === stack[i+1]) {
cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
} else {
cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
}
}
//Get node
n = cstack[cstack.length-1]
//console.log("start remove: ", n.value)
//If not leaf, then swap with previous node
if(n.left && n.right) {
//console.log("moving to leaf")
//First walk to previous leaf
var split = cstack.length
n = n.left
while(n.right) {
cstack.push(n)
n = n.right
}
//Copy path to leaf
var v = cstack[split-1]
cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
cstack[split-1].key = n.key
cstack[split-1].value = n.value
//Fix up stack
for(var i=cstack.length-2; i>=split; --i) {
n = cstack[i]
cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
}
cstack[split-1].left = cstack[split]
}
//console.log("stack=", cstack.map(function(v) { return v.value }))
//Remove leaf node
n = cstack[cstack.length-1]
if(n._color === RED) {
//Easy case: removing red leaf
//console.log("RED leaf")
var p = cstack[cstack.length-2]
if(p.left === n) {
p.left = null
} else if(p.right === n) {
p.right = null
}
cstack.pop()
for(var i=0; i 0) {
return this._stack[this._stack.length-1].key
}
return
},
enumerable: true
})
//Returns value
Object.defineProperty(iproto, "value", {
get: function() {
if(this._stack.length > 0) {
return this._stack[this._stack.length-1].value
}
return
},
enumerable: true
})
//Returns the position of this iterator in the sorted list
Object.defineProperty(iproto, "index", {
get: function() {
var idx = 0
var stack = this._stack
if(stack.length === 0) {
var r = this.tree.root
if(r) {
return r._count
}
return 0
} else if(stack[stack.length-1].left) {
idx = stack[stack.length-1].left._count
}
for(var s=stack.length-2; s>=0; --s) {
if(stack[s+1] === stack[s].right) {
++idx
if(stack[s].left) {
idx += stack[s].left._count
}
}
}
return idx
},
enumerable: true
})
//Advances iterator to next element in list
iproto.next = function() {
var stack = this._stack
if(stack.length === 0) {
return
}
var n = stack[stack.length-1]
if(n.right) {
n = n.right
while(n) {
stack.push(n)
n = n.left
}
} else {
stack.pop()
while(stack.length > 0 && stack[stack.length-1].right === n) {
n = stack[stack.length-1]
stack.pop()
}
}
}
//Checks if iterator is at end of tree
Object.defineProperty(iproto, "hasNext", {
get: function() {
var stack = this._stack
if(stack.length === 0) {
return false
}
if(stack[stack.length-1].right) {
return true
}
for(var s=stack.length-1; s>0; --s) {
if(stack[s-1].left === stack[s]) {
return true
}
}
return false
}
})
//Update value
iproto.update = function(value) {
var stack = this._stack
if(stack.length === 0) {
throw new Error("Can't update empty node!")
}
var cstack = new Array(stack.length)
var n = stack[stack.length-1]
cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
for(var i=stack.length-2; i>=0; --i) {
n = stack[i]
if(n.left === stack[i+1]) {
cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
} else {
cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
}
}
return new RedBlackTree(this.tree._compare, cstack[0])
}
//Moves iterator backward one element
iproto.prev = function() {
var stack = this._stack
if(stack.length === 0) {
return
}
var n = stack[stack.length-1]
if(n.left) {
n = n.left
while(n) {
stack.push(n)
n = n.right
}
} else {
stack.pop()
while(stack.length > 0 && stack[stack.length-1].left === n) {
n = stack[stack.length-1]
stack.pop()
}
}
}
//Checks if iterator is at start of tree
Object.defineProperty(iproto, "hasPrev", {
get: function() {
var stack = this._stack
if(stack.length === 0) {
return false
}
if(stack[stack.length-1].left) {
return true
}
for(var s=stack.length-1; s>0; --s) {
if(stack[s-1].right === stack[s]) {
return true
}
}
return false
}
})
//Default comparison function
function defaultCompare(a, b) {
if(a < b) {
return -1
}
if(a > b) {
return 1
}
return 0
}
//Build a tree
function createRBTree(compare) {
return new RedBlackTree(compare || defaultCompare, null)
}
},{}],512:[function(require,module,exports){
var util = require('util')
var INDENT_START = /[\{\[]/
var INDENT_END = /[\}\]]/
module.exports = function() {
var lines = []
var indent = 0
var push = function(str) {
var spaces = ''
while (spaces.length < indent*2) spaces += ' '
lines.push(spaces+str)
}
var line = function(fmt) {
if (!fmt) return line
if (INDENT_END.test(fmt.trim()[0]) && INDENT_START.test(fmt[fmt.length-1])) {
indent--
push(util.format.apply(util, arguments))
indent++
return line
}
if (INDENT_START.test(fmt[fmt.length-1])) {
push(util.format.apply(util, arguments))
indent++
return line
}
if (INDENT_END.test(fmt.trim()[0])) {
indent--
push(util.format.apply(util, arguments))
return line
}
push(util.format.apply(util, arguments))
return line
}
line.toString = function() {
return lines.join('\n')
}
line.toFunction = function(scope) {
var src = 'return ('+line.toString()+')'
var keys = Object.keys(scope || {}).map(function(key) {
return key
})
var vals = keys.map(function(key) {
return scope[key]
})
return Function.apply(null, keys.concat(src)).apply(null, vals)
}
if (arguments.length) line.apply(null, arguments)
return line
}
},{"util":774}],513:[function(require,module,exports){
var isProperty = require('is-property')
var gen = function(obj, prop) {
return isProperty(prop) ? obj+'.'+prop : obj+'['+JSON.stringify(prop)+']'
}
gen.valid = isProperty
gen.property = function (prop) {
return isProperty(prop) ? prop : JSON.stringify(prop)
}
module.exports = gen
},{"is-property":534}],514:[function(require,module,exports){
/**
* @file Used to determine whether an object has an own property with the specified property key.
* @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-hasownproperty|7.3.11 HasOwnProperty (O, P)}
* @version 3.1.1
* @author Xotic750
* @copyright Xotic750
* @license {@link MIT}
* @module has-own-property-x
*/
'use strict';
var toObject = require('to-object-x');
var toPropertyKey = require('to-property-key-x');
var hop = Object.prototype.hasOwnProperty;
/**
* The `hasOwnProperty` method returns a boolean indicating whether
* the `object` has the specified `property`. Does not attempt to fix known
* issues in older browsers, but does ES6ify the method.
*
* @param {!Object} object - The object to test.
* @throws {TypeError} If object is null or undefined.
* @param {string|Symbol} property - The name or Symbol of the property to test.
* @returns {boolean} `true` if the property is set on `object`, else `false`.
* @example
* var hasOwnProperty = require('has-own-property-x');
* var o = {
* foo: 'bar'
* };
*
*
* hasOwnProperty(o, 'bar'); // false
* hasOwnProperty(o, 'foo'); // true
* hasOwnProperty(undefined, 'foo');
* // TypeError: Cannot convert undefined or null to object
*/
module.exports = function hasOwnProperty(object, property) {
return hop.call(toObject(object), toPropertyKey(property));
};
},{"to-object-x":759,"to-property-key-x":761}],515:[function(require,module,exports){
/**
* @file Tests if ES6 Symbol is supported.
* @version 1.4.1
* @author Xotic750
* @copyright Xotic750
* @license {@link MIT}
* @module has-symbol-support-x
*/
'use strict';
/**
* Indicates if `Symbol`exists and creates the correct type.
* `true`, if it exists and creates the correct type, otherwise `false`.
*
* @type boolean
*/
module.exports = typeof Symbol === 'function' && typeof Symbol('') === 'symbol';
},{}],516:[function(require,module,exports){
/**
* @file Tests if ES6 @@toStringTag is supported.
* @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-@@tostringtag|26.3.1 @@toStringTag}
* @version 1.4.1
* @author Xotic750
* @copyright Xotic750
* @license {@link MIT}
* @module has-to-string-tag-x
*/
'use strict';
/**
* Indicates if `Symbol.toStringTag`exists and is the correct type.
* `true`, if it exists and is the correct type, otherwise `false`.
*
* @type boolean
*/
module.exports = require('has-symbol-support-x') && typeof Symbol.toStringTag === 'symbol';
},{"has-symbol-support-x":515}],517:[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
}
},{}],518:[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