path
stringlengths 5
304
| repo_name
stringlengths 6
79
| content
stringlengths 27
1.05M
|
---|---|---|
ajax/libs/forerunnerdb/1.3.717/fdb-core+views.js | Piicksarn/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('./core'),
View = _dereq_('../lib/View');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":8,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],6:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
'*': function (data) {
return this.$main.call(this, data, {});
},
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback.call(this, resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],7:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {String=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Remove old data
this._data.remove(chainPacket.data.oldData);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":6,"./Shared":31}],8:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],9:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":5,"./Collection.js":6,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":31}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":27}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":27}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":31}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":31}],30:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],31:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.717',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],33:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload'),
Path,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.Matching');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Path = Shared.modules.Path;
sharedPathSolver = new Path();
View.prototype.init = function (name, query, options) {
var self = this;
this.sharedPathSolver = sharedPathSolver;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._data = new Collection(this.name() + '_internal');
};
/**
* This reactor IO node is given data changes from source data and
* then acts as a firewall process between the source and view data.
* Data needs to meet the requirements this IO node imposes before
* the data is passed down the reactor chain (to the view). This
* allows us to intercept data changes from the data source and act
* on them such as applying transforms, checking the data matches
* the view's query, applying joins to the data etc before sending it
* down the reactor chain via the this.chainSend() calls.
*
* Update packets are especially complex to handle because an update
* on the underlying source data could translate into an insert,
* update or remove call on the view. Take a scenario where the view's
* query limits the data see from the source. If the source data is
* updated and the data now falls inside the view's query limitations
* the data is technically now an insert on the view, not an update.
* The same is true in reverse where the update becomes a remove. If
* the updated data already exists in the view and will still exist
* after the update operation then the update can remain an update.
* @param {Object} chainPacket The chain reactor packet representing the
* data operation that has just been processed on the source data.
* @param {View} self The reference to the view we are operating for.
* @private
*/
View.prototype._handleChainIO = function (chainPacket, self) {
var type = chainPacket.type,
hasActiveJoin,
hasActiveQuery,
hasTransformIn,
sharedData;
// NOTE: "self" in this context is the view instance.
// NOTE: "this" in this context is the ReactorIO node sitting in
// between the source (sender) and the destination (listener) and
// in this case the source is the view's "from" data source and the
// destination is the view's _data collection. This means
// that "this.chainSend()" is asking the ReactorIO node to send the
// packet on to the destination listener.
// EARLY EXIT: Check that the packet is not a CRUD operation
if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') {
// This packet is NOT a CRUD operation packet so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We only need to check packets under three conditions
// 1) We have a limiting query on the view "active query",
// 2) We have a query options with a $join clause on the view "active join"
// 3) We have a transformIn operation registered on the view.
// If none of these conditions exist we can just allow the chain
// packet to proceed as normal
hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join);
hasActiveQuery = Boolean(self._querySettings.query);
hasTransformIn = self._data._transformIn !== undefined;
// EARLY EXIT: Check for any complex operation flags and if none
// exist, send the packet on and exit early
if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) {
// We don't have any complex operation flags so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We have either an active query, active join or a transformIn
// function registered on the view
// We create a shared data object here so that the disparate method
// calls can share data with each other via this object whilst
// still remaining separate methods to keep code relatively clean.
sharedData = {
dataArr: [],
removeArr: []
};
// Check the packet type to get the data arrays to work on
if (chainPacket.type === 'insert') {
// Check if the insert data is an array
if (chainPacket.data.dataSet instanceof Array) {
// Use the insert data array
sharedData.dataArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single insert object
sharedData.dataArr = [chainPacket.data.dataSet];
}
} else if (chainPacket.type === 'update') {
// Use the dataSet array
sharedData.dataArr = chainPacket.data.dataSet;
} else if (chainPacket.type === 'remove') {
if (chainPacket.data.dataSet instanceof Array) {
// Use the remove data array
sharedData.removeArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single remove object
sharedData.removeArr = [chainPacket.data.dataSet];
}
}
// Safety check
if (!(sharedData.dataArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!');
sharedData.dataArr = [];
}
if (!(sharedData.removeArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!');
sharedData.removeArr = [];
}
// We need to operate in this order:
// 1) Check if there is an active join - active joins are operated
// against the SOURCE data. The joined data can potentially be
// utilised by any active query or transformIn so we do this step first.
// 2) Check if there is an active query - this is a query that is run
// against the SOURCE data after any active joins have been resolved
// on the source data. This allows an active query to operate on data
// that would only exist after an active join has been executed.
// If the source data does not fall inside the limiting factors of the
// active query then we add it to a removal array. If it does fall
// inside the limiting factors when we add it to an upsert array. This
// is because data that falls inside the query could end up being
// either new data or updated data after a transformIn operation.
// 3) Check if there is a transformIn function. If a transformIn function
// exist we run it against the data after doing any active join and
// active query.
if (hasActiveJoin) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
self._handleChainIO_ActiveJoin(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
}
if (hasActiveQuery) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
self._handleChainIO_ActiveQuery(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
}
if (hasTransformIn) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
self._handleChainIO_TransformIn(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
}
// Check if we still have data to operate on and exit
// if there is none left
if (!sharedData.dataArr.length && !sharedData.removeArr.length) {
// There is no more data to operate on, exit without
// sending any data down the chain reactor (return true
// will tell reactor to exit without continuing)!
return true;
}
// Grab the public data collection's primary key
sharedData.pk = self._data.primaryKey();
// We still have data left, let's work out how to handle it
// first let's loop through the removals as these are easy
if (sharedData.removeArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
self._handleChainIO_RemovePackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
}
if (sharedData.dataArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
self._handleChainIO_UpsertPackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
}
// Now return true to tell the chain reactor not to propagate
// the data itself as we have done all that work here
return true;
};
View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) {
var dataArr = sharedData.dataArr,
removeArr;
// Since we have an active join, all we need to do is operate
// the join clause on each item in the packet's data array.
removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {});
// Now that we've run our join keep in mind that joins can exclude data
// if there is no matching joined data and the require: true clause in
// the join options is enabled. This means we have to store a removal
// array that tells us which items from the original data we sent to
// join did not match the join data and were set with a require flag.
// Now that we have our array of items to remove, let's run through the
// original data and remove them from there.
this.spliceArrayByIndexList(dataArr, removeArr);
// Make sure we add any items we removed to the shared removeArr
sharedData.removeArr = sharedData.removeArr.concat(removeArr);
};
View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
i;
// Now we need to run the data against the active query to
// see if the data should be in the final data list or not,
// so we use the _match method.
// Loop backwards so we can safely splice from the array
// while we are looping
for (i = dataArr.length - 1; i >= 0; i--) {
if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
// The data didn't match the active query, add it
// to the shared removeArr
sharedData.removeArr.push(dataArr[i]);
// Now remove it from the shared dataArr
dataArr.splice(i, 1);
}
}
};
View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
removeArr = sharedData.removeArr,
dataIn = self._data._transformIn,
i;
// At this stage we take the remaining items still left in the data
// array and run our transformIn method on each one, modifying it
// from what it was to what it should be on the view. We also have
// to run this on items we want to remove too because transforms can
// affect primary keys and therefore stop us from identifying the
// correct items to run removal operations on.
// It is important that these are transformed BEFORE they are passed
// to the CRUD methods because we use the CU data to check the position
// of the item in the array and that can only happen if it is already
// pre-transformed. The removal stuff also needs pre-transformed
// because ids can be modified by a transform.
for (i = 0; i < dataArr.length; i++) {
// Assign the new value
dataArr[i] = dataIn(dataArr[i]);
}
for (i = 0; i < removeArr.length; i++) {
// Assign the new value
removeArr[i] = dataIn(removeArr[i]);
}
};
View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) {
var $or = [],
pk = sharedData.pk,
removeArr = sharedData.removeArr,
packet = {
dataSet: removeArr,
query: {
$or: $or
}
},
orObj,
i;
for (i = 0; i < removeArr.length; i++) {
orObj = {};
orObj[pk] = removeArr[i][pk];
$or.push(orObj);
}
ioObj.chainSend('remove', packet);
};
View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) {
var data = this._data,
primaryIndex = data._primaryIndex,
primaryCrc = data._primaryCrc,
pk = sharedData.pk,
dataArr = sharedData.dataArr,
arrItem,
insertArr = [],
updateArr = [],
query,
i;
// Let's work out what type of operation this data should
// generate between an insert or an update.
for (i = 0; i < dataArr.length; i++) {
arrItem = dataArr[i];
// Check if the data already exists in the data
if (primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) {
// The document exists in the data collection but data differs, update required
updateArr.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
insertArr.push(arrItem);
}
}
if (insertArr.length) {
ioObj.chainSend('insert', {
dataSet: insertArr
});
}
if (updateArr.length) {
for (i = 0; i < updateArr.length; i++) {
arrItem = updateArr[i];
query = {};
query[pk] = arrItem[pk];
ioObj.chainSend('update', {
query: query,
update: arrItem,
dataSet: [arrItem]
});
}
}
};
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this._data.findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this._data.findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._data;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
// Remove the current reference to the _from since we
// are about to replace it with a new one
delete this._from;
}
// Check if we have an existing reactor io that links the
// previous _from source to the view's internal data
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
// Check if we were passed a source name rather than a
// reference to a source object
if (typeof(source) === 'string') {
// We were passed a name, assume it is a collection and
// get the reference to the collection of that name
source = this._db.collection(source);
}
// Check if we were passed a reference to a view rather than
// a collection. Views need to be handled slightly differently
// since their data is stored in an internal data collection
// rather than actually being a direct data source themselves.
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source._data;
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
// Assign the new data source as the view's _from
this._from = source;
// Hook the new data source's drop event so we can unhook
// it as a data source if it gets dropped. This is important
// so that we don't run into problems using a dropped source
// for active data.
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's _from source and determines how they should be interpreted by
// this view. See the _handleChainIO() method which does all the chain packet
// processing for the view.
this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); });
// Set the view's internal data primary key to the same as the
// current active _from data source
this._data.primaryKey(source.primaryKey());
// Do the initial data lookup and populate the view's internal data
// since at this point we don't actually have any data in the view
// yet.
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData, {}, callback);
// If we have an active query and that query has an $orderBy clause,
// update our active bucket which allows us to keep track of where
// data should be placed in our internal data array. This is about
// ordering of data and making sure that we maintain an ordered array
// so that if we have data-binding we can place an item in the data-
// bound view at the correct location. Active buckets use quick-sort
// algorithms to quickly determine the position of an item inside an
// existing array based on a sort protocol.
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type);
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData);
// Rebuild active bucket as well
this.rebuildActiveBucket(this._querySettings.options);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Make sure we are working with an array
if (!(chainPacket.data.dataSet instanceof Array)) {
chainPacket.data.dataSet = [chainPacket.data.dataSet];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._data._insertHandle(arr[index], insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._data._data.length;
this._data._insertHandle(chainPacket.data.dataSet, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"');
}
primaryKey = this._data.primaryKey();
// Do the update
updates = this._data._handleUpdate(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._data._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"');
}
this._data.remove(chainPacket.data.query, chainPacket.options);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the dataSet and remove the objects from the ActiveBucket
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
this._activeBucket.remove(arr[index]);
}
}
break;
default:
break;
}
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._data.ensureIndex.apply(this._data, arguments);
};
/**
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._data.on.apply(this._data, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._data.off.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._data.emit.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::deferEmit()
*/
View.prototype.deferEmit = function () {
return this._data.deferEmit.apply(this._data, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._data.distinct(key, query, options);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._data.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._data) {
this._data.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._data;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
}
});
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
// TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first!
this.rebuildActiveBucket(options.$orderBy);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
return this;
}
return this._querySettings.options;
};
/**
* Clears the existing active bucket and builds a new one based
* on the passed orderBy object (if one is passed).
* @param {Object=} orderBy The orderBy object describing how to
* order any data.
*/
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._data._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._data.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
var self = this,
refreshResults,
joinArr,
i, k;
if (this._from) {
// Clear the private data collection which will propagate to the public data
// collection automatically via the chain reactor node between them
this._data.remove();
// Grab all the data from the underlying data source
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
// Insert the underlying data into the private data collection
this._data.insert(refreshResults);
// Store the current cursor data
this._data._data.$cursor = refreshResults.$cursor;
this._data._data.$cursor = refreshResults.$cursor;
}
if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) {
// Define the change handler method
self.__joinChange = self.__joinChange || function () {
self._joinChange();
};
// Check for existing join collections
if (this._joinCollections && this._joinCollections.length) {
// Loop the join collections and remove change listeners
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange);
}
}
// Now start hooking any new / existing joins
joinArr = this._querySettings.options.$join;
this._joinCollections = [];
// Loop the joined collections and hook change events
for (i = 0; i < joinArr.length; i++) {
for (k in joinArr[i]) {
if (joinArr[i].hasOwnProperty(k)) {
this._joinCollections.push(k);
}
}
}
if (this._joinCollections.length) {
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange);
}
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Handles when a change has occurred on a collection that is joined
* by query to this view.
* @param objName
* @param objType
* @private
*/
View.prototype._joinChange = function (objName, objType) {
this.emit('joinChange');
// TODO: This is a really dirty solution because it will require a complete
// TODO: rebuild of the view data. We need to implement an IO handler to
// TODO: selectively update the data of the view based on the joined
// TODO: collection data operation.
// FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call
this.refresh();
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._data.count.apply(this._data, arguments);
};
// Call underlying
View.prototype.subset = function () {
return this._data.subset.apply(this._data, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn"
* and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var currentSettings,
newSettings;
currentSettings = this._data.transform();
this._data.transform(obj);
newSettings = this._data.transform();
// Check if transforms are enabled, a dataIn method is set and these
// settings did not match the previous transform settings
if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) {
// The data in the view is now stale, refresh it
this.refresh();
}
return newSettings;
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return this._data.filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.data = function () {
return this._data;
};
/**
* @see Collection.indexOf
* @returns {*}
*/
View.prototype.indexOf = function () {
return this._data.indexOf.apply(this._data, arguments);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this._data.db(db);
// Apply the same debug settings
this.debug(db.debug());
this._data.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} name The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (name) {
var self = this;
// Handle being passed an instance
if (name instanceof View) {
return name;
}
if (this._view[name]) {
return this._view[name];
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + name);
}
this._view[name] = new View(name).db(this);
self.emit('create', self._view[name], 'view', name);
return this._view[name];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} name The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (name) {
return Boolean(this._view[name]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":3,"./Collection":6,"./CollectionGroup":7,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
|
ajax/libs/algoliasearch/3.20.1/algoliasearchLite.js | hare1039/cdnjs | /*! algoliasearch 3.20.1 | © 2014, 2015 Algolia SAS | github.com/algolia/algoliasearch-client-js */
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.algoliasearch = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (process){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require(2);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
return exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (typeof process !== 'undefined' && 'env' in process) {
return process.env.DEBUG;
}
}
/**
* 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(11))
},{"11":11,"2":2}],2:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug.debug = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require(8);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = 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 = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting
args = exports.formatArgs.apply(self, args);
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').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;
}
},{"8":8}],3:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 4.0.5
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
return typeof x === 'function' || typeof x === 'object' && x !== null;
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (!Array.isArray) {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
_isArray = Array.isArray;
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = require;
var vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
_resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
_reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
_reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
_reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return _resolve(promise, value);
}, function (reason) {
return _reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$) {
if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$ === GET_THEN_ERROR) {
_reject(promise, GET_THEN_ERROR.error);
} else if (then$$ === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$)) {
handleForeignThenable(promise, maybeThenable, then$$);
} else {
fulfill(promise, maybeThenable);
}
}
}
function _resolve(promise, value) {
if (promise === value) {
_reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function _reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
_reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
_resolve(promise, value);
} else if (failed) {
_reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
_reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
_resolve(promise, value);
}, function rejectPromise(reason) {
_reject(promise, reason);
});
} catch (e) {
_reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
_reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._enumerate = function () {
var length = this.length;
var _input = this._input;
for (var i = 0; this._state === PENDING && i < length; i++) {
this._eachEntry(_input[i], i);
}
};
Enumerator.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$ = c.resolve;
if (resolve$$ === resolve) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$) {
return resolve$$(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$(entry), i);
}
};
Enumerator.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
_reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
Promise.prototype = {
constructor: Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
function polyfill() {
var local = undefined;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise;
}
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
return Promise;
})));
}).call(this,require(11),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"11":11}],4:[function(require,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
},{}],5:[function(require,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],6:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],7:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],8:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}
},{}],9:[function(require,module,exports){
'use strict';
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = require(10);
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
},{"10":10}],10:[function(require,module,exports){
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
},{}],11:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],12:[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.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],13:[function(require,module,exports){
(function (process){
module.exports = AlgoliaSearchCore;
var errors = require(24);
var exitPromise = require(25);
var IndexCore = require(14);
var store = require(30);
// We will always put the API KEY in the JSON body in case of too long API KEY,
// to avoid query string being too long and failing in various conditions (our server limit, browser limit,
// proxies limit)
var MAX_API_KEY_LENGTH = 500;
var RESET_APP_DATA_TIMER =
process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) ||
60 * 2 * 1000; // after 2 minutes reset to first host
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = require(1)('algoliasearch');
var clone = require(21);
var isArray = require(7);
var map = require(26);
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
this.hosts = {
read: [],
write: []
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
this._timeouts = opts.timeouts || {
connect: 1 * 1000, // 500ms connect is GPRS latency
read: 2 * 1000,
write: 30 * 1000
};
// backward compat, if opts.timeout is passed, we use it to configure all timeouts like before
if (opts.timeout) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout;
}
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
this._checkAppIdData();
if (!opts.hosts) {
var defaultHosts = map(this._shuffleResult, function(hostNumber) {
return applicationID + '-' + hostNumber + '.algolianet.com';
});
// no hosts given, compute defaults
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
// when passing custom hosts, we need to have a different host index if the number
// of write/read hosts are different.
this.hosts.read = clone(opts.hosts);
this.hosts.write = clone(opts.hosts);
} else {
this.hosts.read = clone(opts.hosts.read);
this.hosts.write = clone(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.extraHeaders = [];
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders.push({
name: name.toLowerCase(), value: value
});
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
this._ua += ';' + algoliaAgent;
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
this._checkAppIdData();
var requestDebug = require(1)('algoliasearch:' + initialOpts.url);
var body;
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(false);
} else {
headers = this._computeRequestHeaders();
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
client._checkAppIdData();
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to [email protected] to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders();
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
client._setHostIndexByType(0, initialOpts.hostType);
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client._getHostByType(initialOpts.hostType);
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeouts: reqOpts.timeouts,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeouts: %d',
options.method, url, options.headers, options.timeouts);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client._incrementHostIndex(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client._incrementHostIndex(initialOpts.hostType);
client._incrementTimeoutMultipler();
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeouts: client._getTimeoutsForRequest(initialOpts.hostType)
}
);
// either we have a callback
// either we are using promises
if (initialOpts.callback) {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(withAPIKey) {
var forEach = require(4);
var requestHeaders = {
'x-algolia-agent': this._ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
if (this.extraHeaders) {
forEach(this.extraHeaders, function addToRequestHeaders(header) {
requestHeaders[header.name] = header.value;
});
}
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = require(7);
var map = require(26);
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
* @deprecated
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds;
}
};
/**
* Set the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) {
this._timeouts = timeouts;
};
/**
* Get the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.getTimeouts = function() {
return this._timeouts;
};
AlgoliaSearchCore.prototype._getAppIdData = function() {
var data = store.get(this.applicationID);
if (data !== null) this._cacheAppIdData(data);
return data;
};
AlgoliaSearchCore.prototype._setAppIdData = function(data) {
data.lastChange = (new Date()).getTime();
this._cacheAppIdData(data);
return store.set(this.applicationID, data);
};
AlgoliaSearchCore.prototype._checkAppIdData = function() {
var data = this._getAppIdData();
var now = (new Date()).getTime();
if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) {
return this._resetInitialAppIdData(data);
}
return data;
};
AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) {
var newData = data || {};
newData.hostIndexes = {read: 0, write: 0};
newData.timeoutMultiplier = 1;
newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]);
return this._setAppIdData(newData);
};
AlgoliaSearchCore.prototype._cacheAppIdData = function(data) {
this._hostIndexes = data.hostIndexes;
this._timeoutMultiplier = data.timeoutMultiplier;
this._shuffleResult = data.shuffleResult;
};
AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) {
var foreach = require(4);
var currentData = this._getAppIdData();
foreach(newData, function(value, key) {
currentData[key] = value;
});
return this._setAppIdData(currentData);
};
AlgoliaSearchCore.prototype._getHostByType = function(hostType) {
return this.hosts[hostType][this._getHostIndexByType(hostType)];
};
AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() {
return this._timeoutMultiplier;
};
AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) {
return this._hostIndexes[hostType];
};
AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) {
var clone = require(21);
var newHostIndexes = clone(this._hostIndexes);
newHostIndexes[hostType] = hostIndex;
this._partialAppIdDataUpdate({hostIndexes: newHostIndexes});
return hostIndex;
};
AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) {
return this._setHostIndexByType(
(this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType
);
};
AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() {
var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4);
return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier});
};
AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) {
return {
connect: this._timeouts.connect * this._timeoutMultiplier,
complete: this._timeouts[hostType] * this._timeoutMultiplier
};
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
}).call(this,require(11))
},{"1":1,"11":11,"14":14,"21":21,"24":24,"25":25,"26":26,"30":30,"4":4,"7":7}],14:[function(require,module,exports){
var buildSearchMethod = require(20);
var deprecate = require(22);
var deprecatedMessage = require(23);
module.exports = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the full text query
* @param args (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param callback the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the similar query
* @param args (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = require(27);
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse?' + params,
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse?cursor=' + encodeURIComponent(cursor),
hostType: 'read',
callback: callback
});
};
/*
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchForFacetValues = function(params, callback) {
var clone = require(21);
var omit = require(28);
var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
return this.searchForFacetValues(params, callback);
}, deprecatedMessage(
'index.searchFacet(params[, callback])',
'index.searchForFacetValues(params[, callback])'
));
IndexCore.prototype._search = function(params, url, callback) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = require(7);
var map = require(26);
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
},{"20":20,"21":21,"22":22,"23":23,"26":26,"27":27,"28":28,"7":7}],15:[function(require,module,exports){
'use strict';
var AlgoliaSearchCore = require(13);
var createAlgoliasearch = require(16);
module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) ');
},{"13":13,"16":16}],16:[function(require,module,exports){
(function (process){
'use strict';
var global = require(5);
var Promise = global.Promise || require(3).Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = require(6);
var errors = require(24);
var inlineHeaders = require(18);
var jsonpRequest = require(19);
var places = require(29);
uaSuffix = uaSuffix || '';
if (process.env.NODE_ENV === 'debug') {
require(1).enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = require(21);
var getDocumentProtocol = require(17);
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = require(31);
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
global.__algolia = {
debug: require(1),
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in global,
hasXDomainRequest: 'XDomainRequest' in global
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var reqTimeout;
var timedOut;
var connected = false;
reqTimeout = setTimeout(onTimeout, opts.timeouts.connect);
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = onProgress;
if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange;
req.onload = onLoad;
req.onerror = onError;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
// headers are meant to be sent after open
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function onLoad(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function onError(event) {
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors.Network({
more: event
})
);
}
function onTimeout() {
timedOut = true;
req.abort();
reject(new errors.RequestTimeout());
}
function onConnect() {
connected = true;
clearTimeout(reqTimeout);
reqTimeout = setTimeout(onTimeout, opts.timeouts.complete);
}
function onProgress() {
if (!connected) onConnect();
}
function onReadyStateChange() {
if (!connected && req.readyState > 1) onConnect();
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise.reject(val);
},
resolve: function resolvePromise(val) {
return Promise.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
}).call(this,require(11))
},{"1":1,"11":11,"17":17,"18":18,"19":19,"21":21,"24":24,"29":29,"3":3,"31":31,"5":5,"6":6}],17:[function(require,module,exports){
'use strict';
module.exports = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
},{}],18:[function(require,module,exports){
'use strict';
module.exports = inlineHeaders;
var encode = require(12);
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode(headers);
}
},{"12":12}],19:[function(require,module,exports){
'use strict';
module.exports = jsonpRequest;
var errors = require(24);
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeouts.complete);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
},{"24":24}],20:[function(require,module,exports){
module.exports = buildSearchMethod;
var errors = require(24);
function buildSearchMethod(queryParam, url) {
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
if (arguments.length === 0 || typeof query === 'function') {
// .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// .search(args), careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
if (args !== undefined) {
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback);
};
}
},{"24":24}],21:[function(require,module,exports){
module.exports = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
},{}],22:[function(require,module,exports){
module.exports = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.log(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
},{}],23:[function(require,module,exports){
module.exports = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace('.', '')
.replace('()', '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink;
};
},{}],24:[function(require,module,exports){
'use strict';
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
var inherits = require(6);
function AlgoliaSearchError(message, extraProperties) {
var forEach = require(4);
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
module.exports = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
},{"4":4,"6":6}],25:[function(require,module,exports){
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
module.exports = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
},{}],26:[function(require,module,exports){
var foreach = require(4);
module.exports = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
},{"4":4}],27:[function(require,module,exports){
var foreach = require(4);
module.exports = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
},{"4":4}],28:[function(require,module,exports){
module.exports = function omit(obj, test) {
var keys = require(9);
var foreach = require(4);
var filtered = {};
foreach(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
},{"4":4,"9":9}],29:[function(require,module,exports){
module.exports = createPlacesClient;
var buildSearchMethod = require(20);
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = require(21);
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod('query', '/1/places/query');
return index;
};
}
},{"20":20,"21":21}],30:[function(require,module,exports){
(function (global){
var debug = require(1)('algoliasearch:src/hostIndexState.js');
var localStorageNamespace = 'algoliasearch-client-js';
var store;
var moduleStore = {
state: {},
set: function(key, data) {
this.state[key] = data;
return this.state[key];
},
get: function(key) {
return this.state[key] || null;
}
};
var localStorageStore = {
set: function(key, data) {
try {
var namespace = JSON.parse(global.localStorage[localStorageNamespace]);
namespace[key] = data;
global.localStorage[localStorageNamespace] = JSON.stringify(namespace);
return namespace[key];
} catch (e) {
debug('localStorage set failed with', e);
cleanup();
store = moduleStore;
return store.set(key, data);
}
},
get: function(key) {
return JSON.parse(global.localStorage[localStorageNamespace])[key] || null;
}
};
store = supportsLocalStorage() ? localStorageStore : moduleStore;
module.exports = {
get: getOrSet,
set: getOrSet
};
function getOrSet(key, data) {
if (arguments.length === 1) {
return store.get(key);
}
return store.set(key, data);
}
function supportsLocalStorage() {
try {
if ('localStorage' in global &&
global.localStorage !== null &&
!global.localStorage[localStorageNamespace]) {
// actual creation of the namespace
global.localStorage.setItem(localStorageNamespace, JSON.stringify({}));
return true;
}
return false;
} catch (_) {
return false;
}
}
// In case of any error on localStorage, we clean our own namespace, this should handle
// quota errors when a lot of keys + data are used
function cleanup() {
try {
global.localStorage.removeItem(localStorageNamespace);
} catch (_) {
// nothing to do
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"1":1}],31:[function(require,module,exports){
'use strict';
module.exports = '3.20.1';
},{}]},{},[15])(15)
}); |
src/PropertyView.js | gordongordon/propertytodos | import React from 'react'
import {observer} from 'mobx-react'
// This is a React component.
// The property "model" of the passed props object is an instance of our TodoViewModel class.
// do you remember all those @observable and @computed?
// In order to let your React component automatically update whenever any of
// those observable property of an object in the component props update,
// you should pass your component to the "observer" function/decorator
@observer
export class PropertyView extends React.Component{
render(){
// const model = this.props.model
const models = this.props.models
function renderProperty( models, modelKey, model ) {
if ( model.property !== null ) {
return <SinglePropertyView models={models} modelKey={modelKey} key={model.property.id} keyGun={model.propertyKey} model={model} property={model.property} />
}
}
function renderMatchedList( items, model ) {
var element= [];
items.forEach( (property, keyID) => element.push(<SingleMatchedPropertyView key={property.id} keyGun={keyID } model={model} property={property} />) )
return <div>{element}</div>
}
// render single property model
function propertyBox( models, modelKey, model, title , count) {
return <div key={count}>
<h3>- User:[{model.user.name}] -- Property Box {title} ------------------- </h3>
{renderProperty( models, modelKey, model )}
<h5> ------ Status ------ </h5>
<SinglePropertyStatusView model={model}/>
<h3>----------------- Matched Property --------------- </h3>
{renderMatchedList(model.matchedList, model)}
<hr></hr>
</div>
}
// render mutli property models
function renderPropertyBox( models ) {
if ( models.models.size > 0 ) {
var elements = []
var count = 0;
models.models.forEach( (model, modelKey) => {
elements.push(propertyBox( models, modelKey, model , model.typeTo, count++) )
})
return <div>
{elements}
</div>
} else {
return <div>
<h3>models is empty </h3>
</div>
}
}
// just some HTML markup based of the ViewModel data.
return <div>
<h1>React & MobX Property List! User: {models.userName}</h1>
<p>
</p>
<p>
<button onClick={() => model.load()}>Reload Propertys</button>
<button onClick={() => model.save()}>Save Propertys</button>
<button onClick={() => models.clear()}>clear gundb</button>
<button onClick={() => model.addNewWrap()}>addNewWrap</button>
<button onClick={() => model.login('gordon')}>Gordon</button>
<button onClick={() => model.login('jeff')}>Jeff</button>
<button onClick={() => model.login('lala')}>Lala</button>
<button onClick={() => model.login('may')}>may</button>
<button onClick={() => model.login('mac')}>mac</button>
</p>
<SingleCreateCase model={models} userName={'gordon'} name={'#01'} location={'shatin'} typeTo={'sell'} typeBy={'forSellBy'} typeFor={'buy'} price={'999'} />
<SingleCreateCase model={models} userName={'jeff'} name={'#02'} location={'ma on sha'} typeTo={'buy'} typeBy={'forBuyBy'} typeFor={'sell'} price={'999'} />
<SingleCreateCase model={models} userName={'lala'} name={'#03'} location={'shatin'} typeTo={'buy'} typeBy={'forBuyBy'} typeFor={'sell'} price={'999'} />
<SingleCreateCase model={models} userName={'peter'} name={'#04'} location={'shatin'} typeTo={'buy'} typeBy={'forBuyBy'} typeFor={'sell'} price={'999'} />
<SingleCreateCase model={models} userName={'mac'} name={'#05'} location={'shatin'} typeTo={'lease'} typeBy={'forLeaseBy'} typeFor={'rent'} price={'999'} />
<SingleCreateCase model={models} userName={'Machel'} name={'#06'} location={'shatin'} typeTo={'rent'} typeBy={'forRentBy'} typeFor={'lease'} price={'999'} />
<SingleCreateCase model={models} userName={'gordon'} name={'#07'} location={'shatin'} typeTo={'sell'} typeBy={'forSellBy'} typeFor={'buy'} price={'999'} />
<SingleCreateCase model={models} userName={'jeff'} name={'#08'} location={'ma on sha'} typeTo={'buy'} typeBy={'forBuyBy'} typeFor={'sell'} price={'999'} />
<SingleCreateCase model={models} userName={'lala'} name={'#09'} location={'shatin'} typeTo={'buy'} typeBy={'forBuyBy'} typeFor={'sell'} price={'999'} />
<SingleCreateCase model={models} userName={'peter'} name={'#10'} location={'shatin'} typeTo={'buy'} typeBy={'forBuyBy'} typeFor={'sell'} price={'999'} />
<hr></hr>
{ renderPropertyBox( models )}
</div>
}
}
// Since putting observer only on the TodoView will result in re-rendering all the todos
// any time a single todo is updated, we create a subcomponent that handles the editing for a single todo
// and decorate it with observer. This way updates in the single todo will result in an update of the SingleTodoView.
@observer
export class SinglePropertyView extends React.Component{
render(){
//const model = this.props.model
const {property, keyID, keyGun, model, models, modelKey } = this.props;
//const key = this.props.key
//console.log( 'key ', key )
return <div>
<p> {keyID}
<input size="10" type="checkbox" checked={property.done} onChange={e => {property.done = e.target.checked}} />
<input size="10" type="text" value={property.name} onChange={e => {property.name = e.target.value}} />
<input size="10" type="text" value={property.location} onChange={e => {property.location = e.target.value}} />
<input size="10" type="text" value={property.typeTo} onChange={e => {property.typeTo = e.target.value}} />
<input size="10" type="text" value={property.price} onChange={e => {property.price = e.target.value}} />
{keyGun}
</p>
<div>
<button onClick={() => models.delete(modelKey)}>Delete</button>
</div>
</div>
}
}
// Since putting observer only on the TodoView will result in re-rendering all the todos
// any time a single todo is updated, we create a subcomponent that handles the editing for a single todo
// and decorate it with observer. This way updates in the single todo will result in an update of the SingleTodoView.
@observer
export class SingleCreateCase extends React.Component{
render(){
//const model = this.props.model
var {userName, name, location, typeTo, typeBy, typeFor, price, model} = this.props;
// <input size="10" type="text" value={userName} onChange={e => { userName = e.target.value}} />
return (<div>
<input size="10" type="text" value={name} onChange={e => { name = e.target.value}} />
<input size="10" type="text" value={location} onChange={e => { location = e.target.value}} />
<input size="10" type="text" value={typeTo} onChange={e => { typeTo = e.target.value}} />
<input size="10" type="text" value={typeBy} onChange={e => { typeBy = e.target.value}} />
<input size="10" type="text" value={typeFor} onChange={e => { typeFor = e.target.value}} />
<input size="10" type="text" value={price} onChange={e => { price = e.target.value}} />
<button onClick={() => model.create(userName, name, location, typeTo, typeBy, typeFor, price )}>Create Case</button>
</div>)
}
}
// Since putting observer only on the TodoView will result in re-rendering all the todos
// any time a single todo is updated, we create a subcomponent that handles the editing for a single todo
// and decorate it with observer. This way updates in the single todo will result in an update of the SingleTodoView.
@observer
export class SingleMatchedPropertyView extends React.Component{
render(){
//const model = this.props.model
const {property, keyID, keyGun, model} = this.props;
//const key = this.props.key
//console.log( 'key ', key )
return <div>
<p>{keyID}{property.text}
<input size="10" type="checkbox" checked={property.done} onChange={e => {property.done = e.target.checked}} />
<input size="10" type="text" value={property.name} onChange={e => {property.name = e.target.value}} />
<input size="10" type="text" value={property.location} onChange={e => {property.location = e.target.value}} />
<input size="10" type="text" value={property.typeTo} onChange={e => {property.typeTo = e.target.value}} />
<input size="10" type="text" value={property.price} onChange={e => {property.price = e.target.value}} />
{keyGun}
</p>
<button onClick={() => model.likeGun( keyGun )}>Like</button>
<button onClick={() => model.rejectGun( keyGun )}>Reject</button>
<button onClick={() => model.likeGun( keyGun )}>View</button>
</div>
}
}
// Since putting observer only on the TodoView will result in re-rendering all the todos
// any time a single todo is updated, we create a subcomponent that handles the editing for a single todo
// and decorate it with observer. This way updates in the single todo will result in an update of the SingleTodoView.
@observer
export class SinglePropertyStatusView extends React.Component{
render(){
//const model = this.props.model
const {model} = this.props;
//const key = this.props.key
//console.log( 'key ', key )
return <div>
<p>
Matched {model.matchedList.size}, Like {model.like.size}, reject {model.reject.size}, view { model.view.size }
</p>
</div>
}
}
|
src/svg-icons/image/blur-off.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBlurOff = (props) => (
<SvgIcon {...props}>
<path d="M14 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-.2 4.48l.2.02c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5l.02.2c.09.67.61 1.19 1.28 1.28zM14 3.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm-4 0c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm11 7c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM10 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm8 8c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-4 13.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM2.5 5.27l3.78 3.78L6 9c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l2.81 2.81c-.71.11-1.25.73-1.25 1.47 0 .83.67 1.5 1.5 1.5.74 0 1.36-.54 1.47-1.25l2.81 2.81c-.09-.03-.18-.06-.28-.06-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l3.78 3.78L20 20.23 3.77 4 2.5 5.27zM10 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm11-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 13c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zM3 9.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm7 11c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-3-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5z"/>
</SvgIcon>
);
ImageBlurOff = pure(ImageBlurOff);
ImageBlurOff.displayName = 'ImageBlurOff';
ImageBlurOff.muiName = 'SvgIcon';
export default ImageBlurOff;
|
game-new/src/views/itemsets/index.js | d07RiV/d3planner | import React from 'react';
import { Route, Switch } from 'react-router-dom';
import { ErrorView, withAsync, scrollView, Cache } from 'utils';
import { ItemSetsDiff } from './diff';
import { ItemSetView, highlightBox } from './common';
import './itemsets.css';
const ItemSetsList = ({build, data, items, names, pathname}) => (
<ul>
{names.map((id, index) => (
<ItemSetView key={id}
build={build}
id={id}
set={data[id]}
items={items[id] || {}}
mergeTop={index > 0 && data[names[index - 1]].name === data[id].name}
mergeBottom={index < names.length - 1 && data[names[index + 1]].name === data[id].name}
pathname={pathname}/>
))}
</ul>
);
// don't turn into functional or scrollView will break
class ItemSetsViewComponent extends React.Component {
render() {
const { build, data, items, pathname } = this.props;
let names = Object.keys(data);
names.sort((a, b) => {
const ia = data[a], ib = data[b];
if (ia.name !== ib.name) return ia.name.localeCompare(ib.name);
return a.localeCompare(b);
});
const setItems = {};
Object.keys(items).forEach(id => {
const item = items[id];
if (item.setid) {
setItems[item.setid] = (setItems[item.setid] || {});
setItems[item.setid][id] = item;
}
});
return (
<div className="ItemSetsView">
<ItemSetsList build={build}
data={data}
items={setItems}
names={names}
pathname={pathname}/>
</div>
);
}
}
const ItemSetsViewWithScroll = scrollView(ItemSetsViewComponent);
const ItemSetsViewNormal = withAsync({
data: ({match}, {cache}) => cache.fetch(`/api/${match.params.build}/itemsets`, {global: true}),
items: ({match}, {cache}) => cache.fetch(`/api/${match.params.build}/items`, {global: true}),
}, ({match, data, items, location}) => (
<ItemSetsViewWithScroll build={match.params.build} data={data} items={items} pathname={location.pathname} onHashLink={highlightBox}/>
), undefined, ErrorView);
ItemSetsViewNormal.contextTypes = Cache.context;
const ItemSetsView = () => (
<Switch>
<Route path={`/:build/itemsets/diff/:diff`} component={ItemSetsDiff}/>
<Route path={`/:build/itemsets`} component={ItemSetsViewNormal}/>
</Switch>
);
export { ItemSetsView }; |
src/containers/ListOfPosts.js | numieco/patriot-trading | import React from 'react'
import Logo from './../components/Logo'
import Loading from './../components/Loading'
import SinglePost from '../components/SinglePost'
import SinglePostArticle from '../components/SinglePostArticle'
import SideBar from './../components/SideBar'
import Footer from './../components/Footer'
import loadExternalLinks from '../helpers/loadExternalLinks'
import loadFeaturedPost from '../helpers/loadFeaturedPost'
import SoundCloud from './../Svg/SoundCloud'
import QuestionMarkLogo from './../Svg/QuestionMarkLogo'
import MicrophoneLogo from './../Svg/MicrophoneLogo'
import ArrowSVG from './../Svg/ArrowSVG'
import { FacebookButton, TwitterButton } from '../components/SocialMediaButtons'
const ghostSecret = require('../ghost-secret')
let posts = null
export default class ListOfPosts extends React.Component {
constructor (props) {
super (props)
this.state = {
posts: [],
featuredPost: null,
featuredTime: null,
postWithLinkNumber: 12,
page: 1,
frontendPage: 1,
loadTillDate: null,
postWithLink: [],
postWithoutLink: [],
postWithLinkBuffer: [],
tempArchiveTime: [],
innerWidth: window.innerWidth,
isLoaded: false
}
}
componentWillMount (props) {
loadFeaturedPost()
.then(this.processFeatured)
.catch((error) => {
console.log(error)
})
loadExternalLinks(this.state.page)
.then(this.processExternalLinks)
.catch((error) => {
console.log(error)
})
}
componentDidMount() {
this.listenResizeEvent()
window.addEventListener('resize', this.listenResizeEvent)
}
componentWillUnmount () {
window.removeEventListener('resize', this.listenResizeEvent)
}
listenResizeEvent = (event) => {
this.setState({
innerWidth: window.innerWidth
})
}
processFeatured = (result) => {
let featured = result.posts[0]
this.setState({
featuredTime: featured.published_at,
featuredId: featured.id,
featuredPost: <SinglePost featured={ true } post={ featured } key={ featured.id } />
})
}
processExternalLinks = (result) => {
this.setState({
posts: result.posts,
loadTillDate: new Date(result.posts[0].published_at)
}, () => {
let postWithLinkBuffer = this.state.postWithLink.slice()
this.state.posts.map((post, i) => {
postWithLinkBuffer.push(<SinglePost featured={ false } className='checking' post={ post } key={ i } />)
})
this.setState({
postWithLinkBuffer,
postWithLink: postWithLinkBuffer,
isLoaded: true,
page: this.state.page + 1
}, () => {
document.getElementsByTagName("body")[0].style.overflow = 'scroll'
this.loadMorePostHandle()
})
})
}
loadMorePostHandle = () => {
console.log('page: '+ this.state.page)
console.log('frontendPage: '+ this.state.frontendPage)
loadExternalLinks(this.state.page)
.then(this.processMoreExternalLinks)
.catch((error) => {
console.log(error)
})
}
processMoreExternalLinks = (result) => {
let postWithLinkBuffer = this.state.postWithLinkBuffer.slice()
result.posts.map((post, i) => {
postWithLinkBuffer.push(<SinglePost featured={ false } className='checking' post={ post } key={ 12 * this.state.page + i} />)
})
this.setState({
postWithLinkBuffer,
page: this.state.page + 1
})
}
render () {
return (
<div>
{
this.state.isLoaded
? null
: <Loading />
}
<div className='wrapper'>
<div className='container home-page'>
{
this.state.innerWidth >= 903
? (
<div className='live-price'>
<a href="http://www.kitco.com/connecting.html">
<img src="http://www.kitconet.com/images/quotes_7a.gif" alt="[Most Recent Quotes from www.kitco.com]" />
</a>
</div>
)
: null
}
<div>{this.state.featuredPost}</div>
{
this.state.innerWidth < 903
? (
<div className='live-price'>
<a href="http://www.kitco.com/connecting.html">
<img src="http://www.kitconet.com/images/quotes_7a.gif" alt="[Most Recent Quotes from www.kitco.com]" />
</a>
</div>
)
: null
}
<div className='relevant-news'>
<h1>relevant news</h1>
</div>
<div className='normal-posts' >
{ this.state.postWithLink }
</div>
<div className='load-more-post' onClick={ () => this.setState({ postWithLink: this.state.postWithLinkBuffer }, this.loadMorePostHandle) }>
load previous posts
</div>
{
this.state.innerWidth <= 902
? (
<div>
<SideBar />
<Footer />
</div>
)
: null
}
</div>
{
this.state.innerWidth > 902
? (
<div className='sidebar-container'>
<SideBar />
</div>
)
: null
}
</div>
{
this.state.innerWidth > 902
? <Footer />
: null
}
</div>
)
}
}
|
publish/test0.js | apulll/qp-react-antd-editor | 'use strict';
var _createClass = 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _hmacsha = require('hmacsha1');
var _hmacsha2 = _interopRequireDefault(_hmacsha);
var _jsBase = require('js-base64');
var _md = require('md5');
var _md2 = _interopRequireDefault(_md);
var _findIndex = require('lodash/findIndex');
var _findIndex2 = _interopRequireDefault(_findIndex);
var _uniqBy = require('lodash/uniqBy');
var _uniqBy2 = _interopRequireDefault(_uniqBy);
var _index = require('./editor/index.jsx');
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Test = function (_React$Component) {
_inherits(Test, _React$Component);
function Test(props) {
_classCallCheck(this, Test);
var _this2 = _possibleConstructorReturn(this, (Test.__proto__ || Object.getPrototypeOf(Test)).call(this, props));
_this2.state = {
htmlContent: '<h1> Head level 1</h1>\n <p style=\'text-align:center;\'><span style="color:#ED5565">red text</span>,center ,<strong>bold</strong>\uFF0C<em>italic</em></p>\n <blockquote style=\'text-align:left;\'><span style="color:#967adc">C</span> <span style="color:#a0d468">O</span><span style="color:#48cfad">L</span><span style="color:#4a89dc">O</span><span style="color:#967adc">R</span><span style="color:#434a54">S</span></blockquote>\n <p><br></p>\n <ul>\n <li><span style="color:#434a54">list 1</span></li>\n <li><span style="color:#434a54">list 2</span></li>\n <li><span style="color:#434a54">list 3</span></li>\n </ul>\n <pre><code>Block here.Block here.Block here.Block here.</code></pre>\n <pre><code>Block here.Block here.Block here.Block here.Block here.</code></pre>\n <pre><code>Block here.Block here.Block here.Block here.Block here.</code></pre>\n <p><img src="https://image.qiluyidian.mobi/43053508139910678747.jpg"/></p>\n <p><br></p>\n <h2>Yankees, Peeking at the Red Sox, Will Soon Get an Eyeful</h2>\n <p>Leaning over the railing from his perch on the top step of the first-base dugout this past weekend in Cleveland, Yankees Manager Joe Girardi did not have to divert his gaze to catch glimpses of the out-of-town scoreboard./p>\n <p>It was all there on the left-field wall.</p>\n <p>\u201CYou\u2019re going to look \u2014 it\u2019s impossible not to,\u201D Girardi said. \u201CI haven\u2019t seen a ballpark where they put it behind you. You pay attention, of course.\u201D</p>\n <p>Whenever Girardi stole a glance, there was rarely any good news for the Yankees. While Girardi\u2019s charges were clawing their way to a split of their four-game series against the formidable Indians, the Boston Red Sox were plowing past the rebuilding Chicago White Sox, sweeping four games at Fenway Park.</p>',
markdownContent: "## HEAD 2 \n markdown examples \n ``` welcome ```",
rawContent: '{"entityMap":{"0":{"type":"image","mutability":"IMMUTABLE","data":{"src":"https://image.qiluyidian.mobi/4305350813991067' + '8747.jpg"}},"1":{"type":"image","mutability":"IMMUTABLE","data":{"src":"https://image.qiluyidian.mobi/430535081399106787' + '47.jpg"}}},"blocks":[{"key":"fr2lj","text":"Yankees, Peeking at the Red Sox, Will Soon Get an Eyeful","type":"header-one","depth":0,"inlineStyleRanges":[],"entityRanges":[]' + ',"data":{}},{"key":"90kdv","text":"Leaning over the railing from his perch on the top step of the first-base dugout this past weekend in Cleveland, Yankees Manager Joe Girardi did not have to divert his gaze to catch glimpses of the out-of-town scoreboard.","type":"unstyled","depth":0,"inlin' + 'eStyleRanges":[],"entityRanges":[],"data":{}},{"key":"b60ni","text":"Whenever Girardi stole a glance, there was rarely any good news for the Yankees. While Girardi’s charges were clawing their way to a split of their four-game series against the formidable Indians, the Boston Red Sox were plowing past the rebuilding Chicago White Sox, sweeping four games at Fenway Park.","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"eui4h","text' + '":"The Yankees, who trail the Red Sox by three games in the American League East, will have their rivals right in front of them on three of the next four weekends, beginning Friday night at Yankee Stadium.","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],' + '"data":{}},{"key":"29t6l","text":" ","type":"atomic","depth":0,"inlineStyleRanges":[],"entityRanges":[{"offset":0,"lengt' + 'h":1,"key":0}],"data":{}},{"key":"7ujeo","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],' + '"data":{}},{"key":"3n9d4","text":" ","type":"atomic","depth":0,"inlineStyleRanges":[],"entityRanges":[{"offset":0,"lengt' + 'h":1,"key":1}],"data":{}},{"key":"9r0k2","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],' + '"data":{}}]}',
responseList: []
};
_this2.receiveHtml = _this2.receiveHtml.bind(_this2);
_this2.receiveMarkdown = _this2.receiveMarkdown.bind(_this2);
_this2.receiveRaw = _this2.receiveRaw.bind(_this2);
_this2.onChange = _this2.onChange.bind(_this2);
_this2.beforeUpload = _this2.beforeUpload.bind(_this2);
_this2.getSignature = _this2.getSignature.bind(_this2);
_this2.getPolicy = _this2.getPolicy.bind(_this2);
return _this2;
}
_createClass(Test, [{
key: 'receiveHtml',
value: function receiveHtml(content) {
console.log("recieved HTML content", content);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {}
}, {
key: 'receiveMarkdown',
value: function receiveMarkdown(content) {
console.log("recieved markdown content", content);
}
}, {
key: 'receiveRaw',
value: function receiveRaw(content) {
console.log("recieved Raw content", content);
}
}, {
key: 'onChange',
value: function onChange(info) {
var currFileList = info.fileList;
currFileList = currFileList.filter(function (f) {
return !f.length;
});
var url = "http://devopee.b0.upaiyun.com";
currFileList = currFileList.map(function (file) {
if (file.response) {
file.url = url + file.response.url;
}
if (!file.length) {
return file;
}
});
var _this = this;
currFileList = currFileList.filter(function (file) {
var hasNoExistCurrFileInUploadedList = !~(0, _findIndex2.default)(_this.state.responseList, function (item) {
return item.name === file.name;
});
if (hasNoExistCurrFileInUploadedList) {
if (!!_this.props.isMultiple == true) {
_this.state.responseList.push(file);
} else {
_this.state.responseList = [file];
}
}
return !!file.response || !!file.url && file.status == "done" || file.status == "uploading";
});
currFileList = (0, _uniqBy2.default)(currFileList, "name");
if (!!currFileList && currFileList.length != 0) {
this.setState({ responseList: currFileList });
}
_this.forceUpdate();
}
}, {
key: 'beforeUpload',
value: function beforeUpload(file) {
console.log("beforeUpload like", file);
}
}, {
key: 'getSignature',
value: function getSignature(fileName) {
var now = new Date();
var h = (0, _hmacsha2.default)('19931944122b23f77681b6ab765648f8', 'POST&/upyun-temp/' + fileName + '&' + now);
var Signature = _jsBase.Base64.encode(h);
return Signature;
}
}, {
key: 'getPolicy',
value: function getPolicy(fileName) {
var now = new Date();
var afterHour = new Date(now.getTime() + 1 * 60 * 60 * 1000);
var policy = _jsBase.Base64.encode(JSON.stringify({
"bucket": "devopee",
"save-key": "/" + fileName,
"expiration": Math.round(afterHour.getTime() / 1000),
"date": now
}));
return policy;
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var policy = "";
var uploadProps = {
action: "http://v0.api.upyun.com/devopee",
onChange: this.onChange,
listType: 'picture',
fileList: this.state.responseList,
data: function data(file) {
return {
Authorization: "UPYUN reactlzeditor:" + _this3.getSignature(file.name),
policy: function () {
policy = _this3.getPolicy(file.name);
return policy;
}(),
signature: (0, _md2.default)(policy + '&pLv/J4I6vfpeznxtwU+g/dsUcEY=')
};
},
multiple: true,
beforeUpload: this.beforeUpload,
showUploadList: true
};
var watermarkImage = [{
type: "white_small",
tip: "white small",
value: "http://7xjl1j.com1.z0.glb.clouddn.com/white_small.png",
valuebase64: "aHR0cDovLzd4amwxai5jb20xLnowLmdsYi5jbG91ZGRuLmNvbS93aGl0ZV9zbWFsbC5wbmc="
}, {
type: "white_big",
tip: "white big",
value: "http://7xjl1j.com1.z0.glb.clouddn.com/white_big.png",
valuebase64: "aHR0cDovLzd4amwxai5jb20xLnowLmdsYi5jbG91ZGRuLmNvbS93aGl0ZV9iaWcucG5n"
}];
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(
'div',
null,
'Editor demo 1 (use default html format ):'
),
_react2.default.createElement(_index2.default, { active: true, importContent: this.state.htmlContent, cbReceiver: this.receiveHtml, uploadProps: uploadProps }),
_react2.default.createElement('br', null),
_react2.default.createElement('br', null),
_react2.default.createElement(
'div',
null,
'Editor demo 2 (use markdown format ):'
),
_react2.default.createElement(_index2.default, {
active: true,
importContent: this.state.markdownContent,
cbReceiver: this.receiveMarkdown,
image: false,
video: false,
audio: false,
convertFormat: 'markdown' }),
_react2.default.createElement('br', null),
_react2.default.createElement('br', null),
_react2.default.createElement(
'div',
null,
'Editor demo 3 (use Raw format ):'
),
_react2.default.createElement(_index2.default, {
active: true,
importContent: this.state.rawContent,
cbReceiver: this.receiveRaw,
image: false,
video: false,
audio: false,
convertFormat: 'raw',
lang: 'zh-CN' })
);
}
}]);
return Test;
}(_react2.default.Component);
_reactDom2.default.render(_react2.default.createElement(Test, null), document.getElementById('test')); |
ajax/libs/react-dom/18.0.0-rc.1-next-629036a9c-20220224/cjs/react-dom-server-legacy.browser.development.min.js | cdnjs/cdnjs | "use strict";"production"!==process.env.NODE_ENV&&function(){var h=require("react"),o=h.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function m(e){for(var t=arguments.length,n=new Array(1<t?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];a("error",e,n)}function a(e,t,n){var r=o.ReactDebugCurrentFrame.getStackAddendum();""!==r&&(t+="%s",n=n.concat([r]));n=n.map(function(e){return String(e)});n.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,n)}function g(e){e()}var n=!1;function p(e,t){f(e,t)}function f(e,t){return n&&(n=!1,"<"!==t[0]&&e.push("\x3c!-- --\x3e")),"\x3c!-- --\x3e"===t?n=!0:e.push(t)}function l(e){e.push(null)}function y(e,t){e.destroy(t)}function r(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}function i(){try{return}catch(e){return 1}}function v(e,t){return i()&&(m("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.",t,r(e)),""+e)}function c(e,t){return i()&&(m("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.",t,r(e)),""+e)}function s(e){return i()&&(m("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.",r(e)),""+e)}var b=Object.prototype.hasOwnProperty,u=0,e=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",t=e+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",d=new RegExp("^["+e+"]["+t+"]*$"),k={},x={};function w(e){if(b.call(x,e))return 1;if(!b.call(k,e)){if(d.test(e))return x[e]=!0;k[e]=!0,m("Invalid attribute name: `%s`",e)}}function S(e,t,n,r){if(null===n||n.type!==u)switch(typeof t){case"function":case"symbol":return 1;case"boolean":if(r)return;if(null!==n)return!n.acceptsBooleans;var o=e.toLowerCase().slice(0,5);return"data-"!==o&&"aria-"!==o;default:return}}function C(e){return R.hasOwnProperty(e)?R[e]:null}function T(e,t,n,r,o,a,i){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=i}var R={};["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"].forEach(function(e){R[e]=new T(e,u,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0],e=e[1];R[t]=new T(t,1,!1,e,null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){R[e]=new T(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){R[e]=new T(e,2,!1,e,null,!1,!1)}),["allowFullScreen","async","autoFocus","autoPlay","controls","default","defer","disabled","disablePictureInPicture","disableRemotePlayback","formNoValidate","hidden","loop","noModule","noValidate","open","playsInline","readOnly","required","reversed","scoped","seamless","itemScope"].forEach(function(e){R[e]=new T(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){R[e]=new T(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){R[e]=new T(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){R[e]=new T(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){R[e]=new T(e,5,!1,e.toLowerCase(),null,!1,!1)});function E(e){return e[1].toUpperCase()}var I=/[\-\:]([a-z])/g;["accent-height","alignment-baseline","arabic-form","baseline-shift","cap-height","clip-path","clip-rule","color-interpolation","color-interpolation-filters","color-profile","color-rendering","dominant-baseline","enable-background","fill-opacity","fill-rule","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","horiz-adv-x","horiz-origin-x","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","overline-position","overline-thickness","paint-order","panose-1","pointer-events","rendering-intent","shape-rendering","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","text-decoration","text-rendering","underline-position","underline-thickness","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","vector-effect","vert-adv-y","vert-origin-x","vert-origin-y","word-spacing","writing-mode","xmlns:xlink","x-height"].forEach(function(e){var t=e.replace(I,E);R[t]=new T(t,1,!1,e,null,!1,!1)}),["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(function(e){var t=e.replace(I,E);R[t]=new T(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(I,E);R[t]=new T(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){R[e]=new T(e,1,!1,e.toLowerCase(),null,!1,!1)});R.xlinkHref=new T("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){R[e]=new T(e,1,!1,e.toLowerCase(),null,!0,!0)});var P={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0};var F=["Webkit","ms","Moz","O"];Object.keys(P).forEach(function(t){F.forEach(function(e){P[e+(e=t).charAt(0).toUpperCase()+e.substring(1)]=P[t]})});var M={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0};function D(e,t){M[t.type]||t.onChange||t.onInput||t.readOnly||t.disabled||null==t.value||m("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."),t.onChange||t.readOnly||t.disabled||null==t.checked||m("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")}function O(e,t){if(-1===e.indexOf("-"))return"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return;default:return 1}}var _={"aria-current":0,"aria-description":0,"aria-details":0,"aria-disabled":0,"aria-hidden":0,"aria-invalid":0,"aria-keyshortcuts":0,"aria-label":0,"aria-roledescription":0,"aria-autocomplete":0,"aria-checked":0,"aria-expanded":0,"aria-haspopup":0,"aria-level":0,"aria-modal":0,"aria-multiline":0,"aria-multiselectable":0,"aria-orientation":0,"aria-placeholder":0,"aria-pressed":0,"aria-readonly":0,"aria-required":0,"aria-selected":0,"aria-sort":0,"aria-valuemax":0,"aria-valuemin":0,"aria-valuenow":0,"aria-valuetext":0,"aria-atomic":0,"aria-busy":0,"aria-live":0,"aria-relevant":0,"aria-dropeffect":0,"aria-grabbed":0,"aria-activedescendant":0,"aria-colcount":0,"aria-colindex":0,"aria-colspan":0,"aria-controls":0,"aria-describedby":0,"aria-errormessage":0,"aria-flowto":0,"aria-labelledby":0,"aria-owns":0,"aria-posinset":0,"aria-rowcount":0,"aria-rowindex":0,"aria-rowspan":0,"aria-setsize":0},A={},U=new RegExp("^(aria)-["+t+"]*$"),j=new RegExp("^(aria)[A-Z]["+t+"]*$");function z(e,t){var n,r=[];for(n in t)(function(e){if(b.call(A,e)&&A[e])return!0;if(j.test(e)){var t="aria-"+e.slice(4).toLowerCase(),t=_.hasOwnProperty(t)?t:null;if(null==t)return m("Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.",e),A[e]=!0;if(e!==t)return m("Invalid ARIA attribute `%s`. Did you mean `%s`?",e,t),A[e]=!0}if(U.test(e)){t=e.toLowerCase(),t=_.hasOwnProperty(t)?t:null;if(null==t)return!(A[e]=!0);if(e!==t)return m("Unknown ARIA attribute `%s`. Did you mean `%s`?",e,t),A[e]=!0}return!0})(n)||r.push(n);t=r.map(function(e){return"`"+e+"`"}).join(", ");1===r.length?m("Invalid aria prop %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props",t,e):1<r.length&&m("Invalid aria props %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props",t,e)}var L=!1;var N={accept:"accept",acceptcharset:"acceptCharset","accept-charset":"acceptCharset",accesskey:"accessKey",action:"action",allowfullscreen:"allowFullScreen",alt:"alt",as:"as",async:"async",autocapitalize:"autoCapitalize",autocomplete:"autoComplete",autocorrect:"autoCorrect",autofocus:"autoFocus",autoplay:"autoPlay",autosave:"autoSave",capture:"capture",cellpadding:"cellPadding",cellspacing:"cellSpacing",challenge:"challenge",charset:"charSet",checked:"checked",children:"children",cite:"cite",class:"className",classid:"classID",classname:"className",cols:"cols",colspan:"colSpan",content:"content",contenteditable:"contentEditable",contextmenu:"contextMenu",controls:"controls",controlslist:"controlsList",coords:"coords",crossorigin:"crossOrigin",dangerouslysetinnerhtml:"dangerouslySetInnerHTML",data:"data",datetime:"dateTime",default:"default",defaultchecked:"defaultChecked",defaultvalue:"defaultValue",defer:"defer",dir:"dir",disabled:"disabled",disablepictureinpicture:"disablePictureInPicture",disableremoteplayback:"disableRemotePlayback",download:"download",draggable:"draggable",enctype:"encType",enterkeyhint:"enterKeyHint",for:"htmlFor",form:"form",formmethod:"formMethod",formaction:"formAction",formenctype:"formEncType",formnovalidate:"formNoValidate",formtarget:"formTarget",frameborder:"frameBorder",headers:"headers",height:"height",hidden:"hidden",high:"high",href:"href",hreflang:"hrefLang",htmlfor:"htmlFor",httpequiv:"httpEquiv","http-equiv":"httpEquiv",icon:"icon",id:"id",imagesizes:"imageSizes",imagesrcset:"imageSrcSet",innerhtml:"innerHTML",inputmode:"inputMode",integrity:"integrity",is:"is",itemid:"itemID",itemprop:"itemProp",itemref:"itemRef",itemscope:"itemScope",itemtype:"itemType",keyparams:"keyParams",keytype:"keyType",kind:"kind",label:"label",lang:"lang",list:"list",loop:"loop",low:"low",manifest:"manifest",marginwidth:"marginWidth",marginheight:"marginHeight",max:"max",maxlength:"maxLength",media:"media",mediagroup:"mediaGroup",method:"method",min:"min",minlength:"minLength",multiple:"multiple",muted:"muted",name:"name",nomodule:"noModule",nonce:"nonce",novalidate:"noValidate",open:"open",optimum:"optimum",pattern:"pattern",placeholder:"placeholder",playsinline:"playsInline",poster:"poster",preload:"preload",profile:"profile",radiogroup:"radioGroup",readonly:"readOnly",referrerpolicy:"referrerPolicy",rel:"rel",required:"required",reversed:"reversed",role:"role",rows:"rows",rowspan:"rowSpan",sandbox:"sandbox",scope:"scope",scoped:"scoped",scrolling:"scrolling",seamless:"seamless",selected:"selected",shape:"shape",size:"size",sizes:"sizes",span:"span",spellcheck:"spellCheck",src:"src",srcdoc:"srcDoc",srclang:"srcLang",srcset:"srcSet",start:"start",step:"step",style:"style",summary:"summary",tabindex:"tabIndex",target:"target",title:"title",type:"type",usemap:"useMap",value:"value",width:"width",wmode:"wmode",wrap:"wrap",about:"about",accentheight:"accentHeight","accent-height":"accentHeight",accumulate:"accumulate",additive:"additive",alignmentbaseline:"alignmentBaseline","alignment-baseline":"alignmentBaseline",allowreorder:"allowReorder",alphabetic:"alphabetic",amplitude:"amplitude",arabicform:"arabicForm","arabic-form":"arabicForm",ascent:"ascent",attributename:"attributeName",attributetype:"attributeType",autoreverse:"autoReverse",azimuth:"azimuth",basefrequency:"baseFrequency",baselineshift:"baselineShift","baseline-shift":"baselineShift",baseprofile:"baseProfile",bbox:"bbox",begin:"begin",bias:"bias",by:"by",calcmode:"calcMode",capheight:"capHeight","cap-height":"capHeight",clip:"clip",clippath:"clipPath","clip-path":"clipPath",clippathunits:"clipPathUnits",cliprule:"clipRule","clip-rule":"clipRule",color:"color",colorinterpolation:"colorInterpolation","color-interpolation":"colorInterpolation",colorinterpolationfilters:"colorInterpolationFilters","color-interpolation-filters":"colorInterpolationFilters",colorprofile:"colorProfile","color-profile":"colorProfile",colorrendering:"colorRendering","color-rendering":"colorRendering",contentscripttype:"contentScriptType",contentstyletype:"contentStyleType",cursor:"cursor",cx:"cx",cy:"cy",d:"d",datatype:"datatype",decelerate:"decelerate",descent:"descent",diffuseconstant:"diffuseConstant",direction:"direction",display:"display",divisor:"divisor",dominantbaseline:"dominantBaseline","dominant-baseline":"dominantBaseline",dur:"dur",dx:"dx",dy:"dy",edgemode:"edgeMode",elevation:"elevation",enablebackground:"enableBackground","enable-background":"enableBackground",end:"end",exponent:"exponent",externalresourcesrequired:"externalResourcesRequired",fill:"fill",fillopacity:"fillOpacity","fill-opacity":"fillOpacity",fillrule:"fillRule","fill-rule":"fillRule",filter:"filter",filterres:"filterRes",filterunits:"filterUnits",floodopacity:"floodOpacity","flood-opacity":"floodOpacity",floodcolor:"floodColor","flood-color":"floodColor",focusable:"focusable",fontfamily:"fontFamily","font-family":"fontFamily",fontsize:"fontSize","font-size":"fontSize",fontsizeadjust:"fontSizeAdjust","font-size-adjust":"fontSizeAdjust",fontstretch:"fontStretch","font-stretch":"fontStretch",fontstyle:"fontStyle","font-style":"fontStyle",fontvariant:"fontVariant","font-variant":"fontVariant",fontweight:"fontWeight","font-weight":"fontWeight",format:"format",from:"from",fx:"fx",fy:"fy",g1:"g1",g2:"g2",glyphname:"glyphName","glyph-name":"glyphName",glyphorientationhorizontal:"glyphOrientationHorizontal","glyph-orientation-horizontal":"glyphOrientationHorizontal",glyphorientationvertical:"glyphOrientationVertical","glyph-orientation-vertical":"glyphOrientationVertical",glyphref:"glyphRef",gradienttransform:"gradientTransform",gradientunits:"gradientUnits",hanging:"hanging",horizadvx:"horizAdvX","horiz-adv-x":"horizAdvX",horizoriginx:"horizOriginX","horiz-origin-x":"horizOriginX",ideographic:"ideographic",imagerendering:"imageRendering","image-rendering":"imageRendering",in2:"in2",in:"in",inlist:"inlist",intercept:"intercept",k1:"k1",k2:"k2",k3:"k3",k4:"k4",k:"k",kernelmatrix:"kernelMatrix",kernelunitlength:"kernelUnitLength",kerning:"kerning",keypoints:"keyPoints",keysplines:"keySplines",keytimes:"keyTimes",lengthadjust:"lengthAdjust",letterspacing:"letterSpacing","letter-spacing":"letterSpacing",lightingcolor:"lightingColor","lighting-color":"lightingColor",limitingconeangle:"limitingConeAngle",local:"local",markerend:"markerEnd","marker-end":"markerEnd",markerheight:"markerHeight",markermid:"markerMid","marker-mid":"markerMid",markerstart:"markerStart","marker-start":"markerStart",markerunits:"markerUnits",markerwidth:"markerWidth",mask:"mask",maskcontentunits:"maskContentUnits",maskunits:"maskUnits",mathematical:"mathematical",mode:"mode",numoctaves:"numOctaves",offset:"offset",opacity:"opacity",operator:"operator",order:"order",orient:"orient",orientation:"orientation",origin:"origin",overflow:"overflow",overlineposition:"overlinePosition","overline-position":"overlinePosition",overlinethickness:"overlineThickness","overline-thickness":"overlineThickness",paintorder:"paintOrder","paint-order":"paintOrder",panose1:"panose1","panose-1":"panose1",pathlength:"pathLength",patterncontentunits:"patternContentUnits",patterntransform:"patternTransform",patternunits:"patternUnits",pointerevents:"pointerEvents","pointer-events":"pointerEvents",points:"points",pointsatx:"pointsAtX",pointsaty:"pointsAtY",pointsatz:"pointsAtZ",prefix:"prefix",preservealpha:"preserveAlpha",preserveaspectratio:"preserveAspectRatio",primitiveunits:"primitiveUnits",property:"property",r:"r",radius:"radius",refx:"refX",refy:"refY",renderingintent:"renderingIntent","rendering-intent":"renderingIntent",repeatcount:"repeatCount",repeatdur:"repeatDur",requiredextensions:"requiredExtensions",requiredfeatures:"requiredFeatures",resource:"resource",restart:"restart",result:"result",results:"results",rotate:"rotate",rx:"rx",ry:"ry",scale:"scale",security:"security",seed:"seed",shaperendering:"shapeRendering","shape-rendering":"shapeRendering",slope:"slope",spacing:"spacing",specularconstant:"specularConstant",specularexponent:"specularExponent",speed:"speed",spreadmethod:"spreadMethod",startoffset:"startOffset",stddeviation:"stdDeviation",stemh:"stemh",stemv:"stemv",stitchtiles:"stitchTiles",stopcolor:"stopColor","stop-color":"stopColor",stopopacity:"stopOpacity","stop-opacity":"stopOpacity",strikethroughposition:"strikethroughPosition","strikethrough-position":"strikethroughPosition",strikethroughthickness:"strikethroughThickness","strikethrough-thickness":"strikethroughThickness",string:"string",stroke:"stroke",strokedasharray:"strokeDasharray","stroke-dasharray":"strokeDasharray",strokedashoffset:"strokeDashoffset","stroke-dashoffset":"strokeDashoffset",strokelinecap:"strokeLinecap","stroke-linecap":"strokeLinecap",strokelinejoin:"strokeLinejoin","stroke-linejoin":"strokeLinejoin",strokemiterlimit:"strokeMiterlimit","stroke-miterlimit":"strokeMiterlimit",strokewidth:"strokeWidth","stroke-width":"strokeWidth",strokeopacity:"strokeOpacity","stroke-opacity":"strokeOpacity",suppresscontenteditablewarning:"suppressContentEditableWarning",suppresshydrationwarning:"suppressHydrationWarning",surfacescale:"surfaceScale",systemlanguage:"systemLanguage",tablevalues:"tableValues",targetx:"targetX",targety:"targetY",textanchor:"textAnchor","text-anchor":"textAnchor",textdecoration:"textDecoration","text-decoration":"textDecoration",textlength:"textLength",textrendering:"textRendering","text-rendering":"textRendering",to:"to",transform:"transform",typeof:"typeof",u1:"u1",u2:"u2",underlineposition:"underlinePosition","underline-position":"underlinePosition",underlinethickness:"underlineThickness","underline-thickness":"underlineThickness",unicode:"unicode",unicodebidi:"unicodeBidi","unicode-bidi":"unicodeBidi",unicoderange:"unicodeRange","unicode-range":"unicodeRange",unitsperem:"unitsPerEm","units-per-em":"unitsPerEm",unselectable:"unselectable",valphabetic:"vAlphabetic","v-alphabetic":"vAlphabetic",values:"values",vectoreffect:"vectorEffect","vector-effect":"vectorEffect",version:"version",vertadvy:"vertAdvY","vert-adv-y":"vertAdvY",vertoriginx:"vertOriginX","vert-origin-x":"vertOriginX",vertoriginy:"vertOriginY","vert-origin-y":"vertOriginY",vhanging:"vHanging","v-hanging":"vHanging",videographic:"vIdeographic","v-ideographic":"vIdeographic",viewbox:"viewBox",viewtarget:"viewTarget",visibility:"visibility",vmathematical:"vMathematical","v-mathematical":"vMathematical",vocab:"vocab",widths:"widths",wordspacing:"wordSpacing","word-spacing":"wordSpacing",writingmode:"writingMode","writing-mode":"writingMode",x1:"x1",x2:"x2",x:"x",xchannelselector:"xChannelSelector",xheight:"xHeight","x-height":"xHeight",xlinkactuate:"xlinkActuate","xlink:actuate":"xlinkActuate",xlinkarcrole:"xlinkArcrole","xlink:arcrole":"xlinkArcrole",xlinkhref:"xlinkHref","xlink:href":"xlinkHref",xlinkrole:"xlinkRole","xlink:role":"xlinkRole",xlinkshow:"xlinkShow","xlink:show":"xlinkShow",xlinktitle:"xlinkTitle","xlink:title":"xlinkTitle",xlinktype:"xlinkType","xlink:type":"xlinkType",xmlbase:"xmlBase","xml:base":"xmlBase",xmllang:"xmlLang","xml:lang":"xmlLang",xmlns:"xmlns","xml:space":"xmlSpace",xmlnsxlink:"xmlnsXlink","xmlns:xlink":"xmlnsXlink",xmlspace:"xmlSpace",y1:"y1",y2:"y2",y:"y",ychannelselector:"yChannelSelector",z:"z",zoomandpan:"zoomAndPan"},B=function(){},W={},H=/^on./,V=/^on[^A-Z]/,q=new RegExp("^(aria)-["+t+"]*$"),$=new RegExp("^(aria)[A-Z]["+t+"]*$"),B=function(e,t,n,r){if(b.call(W,t)&&W[t])return!0;var o=t.toLowerCase();if("onfocusin"===o||"onfocusout"===o)return m("React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."),W[t]=!0;if(null!=r){var a=r.registrationNameDependencies,i=r.possibleRegistrationNames;if(a.hasOwnProperty(t))return!0;var s=i.hasOwnProperty(o)?i[o]:null;if(null!=s)return m("Invalid event handler property `%s`. Did you mean `%s`?",t,s),W[t]=!0;if(H.test(t))return m("Unknown event handler property `%s`. It will be ignored.",t),W[t]=!0}else if(H.test(t))return V.test(t)&&m("Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.",t),W[t]=!0;if(q.test(t)||$.test(t))return!0;if("innerhtml"===o)return m("Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."),W[t]=!0;if("aria"===o)return m("The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."),W[t]=!0;if("is"===o&&null!=n&&"string"!=typeof n)return m("Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.",typeof n),W[t]=!0;if("number"==typeof n&&isNaN(n))return m("Received NaN for the `%s` attribute. If this is expected, cast the value to a string.",t),W[t]=!0;a=C(t),i=null!==a&&a.type===u;if(N.hasOwnProperty(o)){s=N[o];if(s!==t)return m("Invalid DOM property `%s`. Did you mean `%s`?",t,s),W[t]=!0}else if(!i&&t!==o)return m("React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.",t,o),W[t]=!0;return"boolean"==typeof n&&S(t,n,a,!1)?(n?m('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.',n,t,t,n,t):m('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.',n,t,t,n,t,t,t),W[t]=!0):i||(S(t,n,a,!1)?!(W[t]=!0):"false"!==n&&"true"!==n||null===a||3!==a.type||(m("Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?",n,t,"false"===n?"The browser will interpret it as a truthy value.":'Although this works, it will not work as expected if you pass the string "false".',t,n),W[t]=!0))};function Y(e,t,n){O(e,t)||function(e,t,n){var r,o=[];for(r in t)B(e,r,t[r],n)||o.push(r);var a=o.map(function(e){return"`"+e+"`"}).join(", ");1===o.length?m("Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior ",a,e):1<o.length&&m("Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://reactjs.org/link/attribute-behavior ",a,e)}(e,t,n)}var X=/^(?:webkit|moz|o)[A-Z]/,Z=/^-ms-/,G=/-(.)/g,J=/;\s*$/,K={},Q={},ee=!1,te=!1,ne=function(e){return e.replace(G,function(e,t){return t.toUpperCase()})},re=function(e,t){var n,r,o;-1<e.indexOf("-")?(r=e,K.hasOwnProperty(r)&&K[r]||(K[r]=!0,m("Unsupported style property %s. Did you mean %s?",r,ne(r.replace(Z,"ms-"))))):X.test(e)?(n=e,K.hasOwnProperty(n)&&K[n]||(K[n]=!0,m("Unsupported vendor-prefixed style property %s. Did you mean %s?",n,n.charAt(0).toUpperCase()+n.slice(1)))):J.test(t)&&(n=e,o=t,Q.hasOwnProperty(o)&&Q[o]||(Q[o]=!0,m('Style property values shouldn\'t contain a semicolon. Try "%s: %s" instead.',n,o.replace(J,"")))),"number"==typeof t&&(isNaN(t)?(o=e,ee||(ee=!0,m("`NaN` is an invalid value for the `%s` css style property.",o))):isFinite(t)||(e=e,te||(te=!0,m("`Infinity` is an invalid value for the `%s` css style property.",e))))},oe=/["'&<>]/;function ae(e){return"boolean"==typeof e||"number"==typeof e?""+e:function(e){s(e);var t,n=""+e;if(!(e=oe.exec(n)))return n;for(var r="",o=0,a=e.index;a<n.length;a++){switch(n.charCodeAt(a)){case 34:t=""";break;case 38:t="&";break;case 39:t="'";break;case 60:t="<";break;case 62:t=">";break;default:continue}o!==a&&(r+=n.substring(o,a)),o=a+1,r+=t}return o!==a?r+n.substring(o,a):r}(e)}var ie=/([A-Z])/g,se=/^ms-/;var le=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i,ce=!1;var ue=Array.isArray;function de(e){return ue(e)}var pe='" async=""><\/script>';var fe=1;function he(e,t){return{insertionMode:e,selectedValue:t}}function me(e){return ae(e)}var ge=new Map;function ye(e){var t=ge.get(e);if(void 0!==t)return t;t=ae(e.replace(ie,"-$1").toLowerCase().replace(se,"-ms-"));return ge.set(e,t),t}function ve(e,t,n){if("object"!=typeof n)throw new Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");var r,o,a,i,s=!0;for(r in n)b.call(n,r)&&(null!=(o=n[r])&&"boolean"!=typeof o&&""!==o&&(i=a=void 0,i=0===r.indexOf("--")?(a=ae(r),c(o,r),ae((""+o).trim())):(re(r,o),a=ye(r),"number"==typeof o?0===o||b.call(P,r)?""+o:o+"px":(c(o,r),ae((""+o).trim()))),s?(s=!1,e.push(' style="',a,":",i)):e.push(";",a,":",i)));s||e.push('"')}var be=" ",ke='="';function xe(e,t,n,r){switch(n){case"style":return void ve(e,0,r);case"defaultValue":case"defaultChecked":case"innerHTML":case"suppressContentEditableWarning":case"suppressHydrationWarning":return}if(!(2<n.length)||"o"!==n[0]&&"O"!==n[0]||"n"!==n[1]&&"N"!==n[1]){var o,a=C(n);if(null!==a){switch(typeof r){case"function":case"symbol":return;case"boolean":if(!a.acceptsBooleans)return}var i=a.attributeName,s=i;switch(a.type){case 3:return void(r&&e.push(be,s,'=""'));case 4:return void(!0===r?e.push(be,s,'=""'):!1===r||e.push(be,s,ke,ae(r),'"'));case 5:isNaN(r)||e.push(be,s,ke,ae(r),'"');break;case 6:!isNaN(r)&&1<=r&&e.push(be,s,ke,ae(r),'"');break;default:a.sanitizeURL&&(v(r,i),o=r=""+r,!ce&&le.test(o)&&(ce=!0,m("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.",JSON.stringify(o)))),e.push(be,s,ke,ae(r),'"')}}else if(w(n)){switch(typeof r){case"function":case"symbol":return;case"boolean":var l=n.toLowerCase().slice(0,5);if("data-"!==l&&"aria-"!==l)return}e.push(be,n,ke,ae(r),'"')}}}function we(e,t,n){if(null!=t){if(null!=n)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");if("object"!=typeof t||!("__html"in t))throw new Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");t=t.__html;null!=t&&(s(t),e.push(""+t))}}var Se=!1,Ce=!1,Te=!1,Re=!1,Ee=!1,Ie=!1,Pe=!1;function Fe(e,t){var n=e[t];null!=n&&(n=de(n),e.multiple&&!n?m("The `%s` prop supplied to <select> must be an array if `multiple` is true.",t):!e.multiple&&n&&m("The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.",t))}var Me=' selected=""';function De(e,t,n,r){var o=r.selectedValue;e.push(Ue("option"));var a,i,s=null,l=null,c=null,u=null;for(a in t)if(b.call(t,a)){var d=t[a];if(null!=d)switch(a){case"children":s=d;break;case"selected":c=d,Pe||(m("Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."),Pe=!0);break;case"dangerouslySetInnerHTML":u=d;break;case"value":l=d;default:xe(e,0,a,d)}}if(null!==o){var p=null!==l?(v(l,"value"),""+l):(null!==u&&(Ie||(Ie=!0,m("Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected."))),r=s,i="",h.Children.forEach(r,function(e){null!=e&&(i+=e,Ee||"string"==typeof e||"number"==typeof e||(Ee=!0,m("Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>.")))}),i);if(de(o)){for(var f=0;f<o.length;f++)if(v(o[f],"value"),""+o[f]===p){e.push(Me);break}}else o===p&&e.push(Me)}else c&&e.push(Me);return e.push(">"),we(e,u,s),s}function Oe(e,t,n){e.push(Ue(n));var r,o=null,a=null;for(r in t)if(b.call(t,r)){var i=t[r];if(null!=i)switch(r){case"children":o=i;break;case"dangerouslySetInnerHTML":a=i;break;default:xe(e,0,r,i)}}return e.push(">"),we(e,a,o),"string"==typeof o?(e.push(me(o)),null):o}var _e=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Ae=new Map;function Ue(e){var t=Ae.get(e);if(void 0===t){if(!_e.test(e))throw new Error("Invalid tag: "+e);Ae.set(e,t="<"+e)}return t}function je(e,t,n,r,o){var a,i;switch(O(a=t,i=n)||z(a,i),a=n,"input"!==(i=t)&&"textarea"!==i&&"select"!==i||null==a||null!==a.value||L||(L=!0,"select"===i&&a.multiple?m("`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.",i):m("`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.",i)),Y(t,n,null),!n.suppressContentEditableWarning&&n.contentEditable&&null!=n.children&&m("A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."),2!==o.insertionMode&&3!==o.insertionMode&&-1===t.indexOf("-")&&"string"!=typeof n.is&&t.toLowerCase()!==t&&m("<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.",t),t){case"select":return function(e,t){D(0,t),Fe(t,"value"),Fe(t,"defaultValue"),void 0===t.value||void 0===t.defaultValue||Te||(m("Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://reactjs.org/link/controlled-components"),Te=!0),e.push(Ue("select"));var n,r=null,o=null;for(n in t)if(b.call(t,n)){var a=t[n];if(null!=a)switch(n){case"children":r=a;break;case"dangerouslySetInnerHTML":o=a;break;case"defaultValue":case"value":break;default:xe(e,0,n,a)}}return e.push(">"),we(e,o,r),r}(e,n);case"option":return De(e,n,0,o);case"textarea":return function(e,t){D(0,t),void 0===t.value||void 0===t.defaultValue||Re||(m("Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://reactjs.org/link/controlled-components"),Re=!0),e.push(Ue("textarea"));var n,r=null,o=null,a=null;for(n in t)if(b.call(t,n)){var i=t[n];if(null!=i)switch(n){case"children":a=i;break;case"value":r=i;break;case"defaultValue":o=i;break;case"dangerouslySetInnerHTML":throw new Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");default:xe(e,0,n,i)}}if(null===r&&null!==o&&(r=o),e.push(">"),null!=a){if(m("Use the `defaultValue` or `value` props instead of setting children on <textarea>."),null!=r)throw new Error("If you supply `defaultValue` on a <textarea>, do not pass children.");if(de(a)){if(1<a.length)throw new Error("<textarea> can only have at most one child.");s(a[0]),r=""+a[0]}s(a),r=""+a}return"string"==typeof r&&"\n"===r[0]&&e.push("\n"),null!==r&&(v(r,"value"),e.push(me(""+r))),null}(e,n);case"input":return function(e,t){D(0,t),void 0===t.checked||void 0===t.defaultChecked||Ce||(m("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components","A component",t.type),Ce=!0),void 0===t.value||void 0===t.defaultValue||Se||(m("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components","A component",t.type),Se=!0),e.push(Ue("input"));var n,r=null,o=null,a=null,i=null;for(n in t)if(b.call(t,n)){var s=t[n];if(null!=s)switch(n){case"children":case"dangerouslySetInnerHTML":throw new Error("input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");case"defaultChecked":i=s;break;case"defaultValue":o=s;break;case"checked":a=s;break;case"value":r=s;break;default:xe(e,0,n,s)}}return null!==a?xe(e,0,"checked",a):null!==i&&xe(e,0,"checked",i),null!==r?xe(e,0,"value",r):null!==o&&xe(e,0,"value",o),e.push("/>"),null}(e,n);case"menuitem":return function(e,t){for(var n in e.push(Ue("menuitem")),t)if(b.call(t,n)){var r=t[n];if(null!=r)switch(n){case"children":case"dangerouslySetInnerHTML":throw new Error("menuitems cannot have `children` nor `dangerouslySetInnerHTML`.");default:xe(e,0,n,r)}}return e.push(">"),null}(e,n);case"listing":case"pre":return function(e,t,n){e.push(Ue(n));var r,o=null,a=null;for(r in t)if(b.call(t,r)){var i=t[r];if(null!=i)switch(r){case"children":o=i;break;case"dangerouslySetInnerHTML":a=i;break;default:xe(e,0,r,i)}}if(e.push(">"),null!=a){if(null!=o)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");if("object"!=typeof a||!("__html"in a))throw new Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");n=a.__html;null!=n&&("string"==typeof n&&0<n.length&&"\n"===n[0]?e.push("\n",n):(s(n),e.push(""+n)))}return"string"==typeof o&&"\n"===o[0]&&e.push("\n"),o}(e,n,t);case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":return function(e,t,n){for(var r in e.push(Ue(n)),t)if(b.call(t,r)){var o=t[r];if(null!=o)switch(r){case"children":case"dangerouslySetInnerHTML":throw new Error(n+" is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");default:xe(e,0,r,o)}}return e.push("/>"),null}(e,n,t);case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return Oe(e,n,t);case"html":return 0===o.insertionMode&&e.push("<!DOCTYPE html>"),Oe(e,n,t);default:return(-1===t.indexOf("-")&&"string"!=typeof n.is?Oe:function(e,t,n){e.push(Ue(n));var r,o=null,a=null;for(r in t)if(b.call(t,r)){var i=t[r];if(null!=i)switch(r){case"children":o=i;break;case"dangerouslySetInnerHTML":a=i;break;case"style":ve(e,0,i);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":break;default:w(r)&&"function"!=typeof i&&"symbol"!=typeof i&&e.push(be,r,ke,ae(i),'"')}}return e.push(">"),we(e,a,o),o})(e,n,t)}}var ze='\x3c!--$?--\x3e<template id="',Le='"></template>',Ne="\x3c!--/$--\x3e";function Be(e,t,n){if(p(e,ze),null===n)throw new Error("An ID must have been assigned before we can complete the boundary.");return p(e,n),f(e,Le)}function We(e){return f(e,Ne)}var He='function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("',Ve='$RS("',qe='","',$e='")<\/script>';function Ye(e,t){t=function(e,t,n,r,o){var e=void 0===e?"":e,t=void 0===t?"<script>":'<script nonce="'+ae(t)+'">',a=[];if(void 0!==n&&a.push(t,ae(n),"<\/script>"),void 0!==r)for(var i=0;i<r.length;i++)a.push('<script src="',ae(r[i]),pe);if(void 0!==o)for(var s=0;s<o.length;s++)a.push('<script type="module" src="',ae(o[s]),pe);return{bootstrapChunks:a,startInlineScript:t,placeholderPrefix:e+"P:",segmentPrefix:e+"S:",boundaryPrefix:e+"B:",idPrefix:e,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1}}(t,void 0);return{bootstrapChunks:t.bootstrapChunks,startInlineScript:t.startInlineScript,placeholderPrefix:t.placeholderPrefix,segmentPrefix:t.segmentPrefix,boundaryPrefix:t.boundaryPrefix,idPrefix:t.idPrefix,nextSuspenseID:t.nextSuspenseID,sentCompleteSegmentFunction:t.sentCompleteSegmentFunction,sentCompleteBoundaryFunction:t.sentCompleteBoundaryFunction,sentClientRenderFunction:t.sentClientRenderFunction,generateStaticMarkup:e}}function Xe(e,t,n){n.generateStaticMarkup?e.push(ae(t)):(e=e,""!==(t=t)&&e.push(me(t),"\x3c!-- --\x3e"))}function Ze(e,t){return t.generateStaticMarkup||f(e,"\x3c!--$--\x3e")}function Ge(e,t){return t.generateStaticMarkup||f(e,"\x3c!--$!--\x3e")}function Je(e,t){return!!t.generateStaticMarkup||f(e,Ne)}function Ke(e,t){return!!t.generateStaticMarkup||f(e,Ne)}var Qe=Object.assign,et=Symbol.for("react.element"),tt=Symbol.for("react.portal"),nt=Symbol.for("react.fragment"),rt=Symbol.for("react.strict_mode"),ot=Symbol.for("react.profiler"),at=Symbol.for("react.provider"),it=Symbol.for("react.context"),st=Symbol.for("react.forward_ref"),lt=Symbol.for("react.suspense"),ct=Symbol.for("react.suspense_list"),ut=Symbol.for("react.memo"),dt=Symbol.for("react.lazy"),pt=Symbol.for("react.scope"),ft=Symbol.for("react.debug_trace_mode"),ht=Symbol.for("react.legacy_hidden"),mt=Symbol.for("react.cache"),gt=Symbol.for("react.tracing_marker"),yt=Symbol.iterator,vt="@@iterator";function bt(e){return e.displayName||"Context"}function kt(e){if(null==e)return null;if("number"==typeof e.tag&&m("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case nt:return"Fragment";case tt:return"Portal";case ot:return"Profiler";case rt:return"StrictMode";case lt:return"Suspense";case ct:return"SuspenseList";case mt:return"Cache";case gt:return"TracingMarker"}if("object"==typeof e)switch(e.$$typeof){case it:return bt(e)+".Consumer";case at:return bt(e._context)+".Provider";case st:return r=(n=e).render,o="ForwardRef",(n=n.displayName)?n:""!==(r=r.displayName||r.name||"")?o+"("+r+")":o;case ut:var t=e.displayName||null;return null!==t?t:kt(e.type)||"Memo";case dt:o=e._payload,t=e._init;try{return kt(t(o))}catch(e){return null}}var n,r,o;return null}var xt,wt,St,Ct,Tt,Rt,Et,It=0;function Pt(){}var Ft,Mt=o.ReactCurrentDispatcher;function Dt(e){if(void 0===Ft)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Ft=t&&t[1]||""}return"\n"+Ft+e}var Ot=!(Pt.__reactDisabledLog=!0),_t=new("function"==typeof WeakMap?WeakMap:Map);function At(t,e){if(!t||Ot)return"";var n,r=_t.get(t);if(void 0!==r)return r;Ot=!0;var o,a=Error.prepareStackTrace;Error.prepareStackTrace=void 0,o=Mt.current,Mt.current=null,0===It&&(xt=console.log,wt=console.info,St=console.warn,Ct=console.error,Tt=console.group,Rt=console.groupCollapsed,Et=console.groupEnd,r={configurable:!0,enumerable:!0,value:Pt,writable:!0},Object.defineProperties(console,{info:r,log:r,warn:r,error:r,group:r,groupCollapsed:r,groupEnd:r})),It++;try{if(e){var i=function(){throw Error()};if(Object.defineProperty(i.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(i,[])}catch(e){n=e}Reflect.construct(t,[],i)}else{try{i.call()}catch(e){n=e}t.call(i.prototype)}}else{try{throw Error()}catch(e){n=e}t()}}catch(e){if(e&&n&&"string"==typeof e.stack){for(var s=e.stack.split("\n"),l=n.stack.split("\n"),c=s.length-1,u=l.length-1;1<=c&&0<=u&&s[c]!==l[u];)u--;for(;1<=c&&0<=u;c--,u--)if(s[c]!==l[u]){if(1!==c||1!==u)do{if(c--,--u<0||s[c]!==l[u]){var d="\n"+s[c].replace(" at new "," at ");return t.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",t.displayName)),"function"==typeof t&&_t.set(t,d),d}}while(1<=c&&0<=u);break}}}finally{Ot=!1,Mt.current=o,0===--It&&(o={configurable:!0,enumerable:!0,writable:!0},Object.defineProperties(console,{log:Qe({},o,{value:xt}),info:Qe({},o,{value:wt}),warn:Qe({},o,{value:St}),error:Qe({},o,{value:Ct}),group:Qe({},o,{value:Tt}),groupCollapsed:Qe({},o,{value:Rt}),groupEnd:Qe({},o,{value:Et})})),It<0&&m("disabledDepth fell below zero. This is a bug in React. Please file an issue."),Error.prepareStackTrace=a}a=t?t.displayName||t.name:"",a=a?Dt(a):"";return"function"==typeof t&&_t.set(t,a),a}function Ut(e){return At(e,!1)}var jt={},zt=o.ReactDebugCurrentFrame;function Lt(e){var t;e?(t=e._owner,t=function e(t,n,r){if(null==t)return"";if("function"==typeof t)return At(t,!(!(o=(o=t).prototype)||!o.isReactComponent));var o;if("string"==typeof t)return Dt(t);switch(t){case lt:return Dt("Suspense");case ct:return Dt("SuspenseList")}if("object"==typeof t)switch(t.$$typeof){case st:return Ut(t.render);case ut:return e(t.type,n,r);case dt:var a=t._payload,i=t._init;try{return e(i(a),n,r)}catch(e){}}return""}(e.type,e._source,t?t.type:null),zt.setExtraStackFrame(t)):zt.setExtraStackFrame(null)}function Nt(e,t,n,r,o){var a,i=Function.call.bind(b);for(a in e)if(i(e,a)){var s=void 0;try{if("function"!=typeof e[a]){var l=Error((r||"React class")+": "+n+" type `"+a+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[a]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw l.name="Invariant Violation",l}s=e[a](t,a,r,n,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(e){s=e}!s||s instanceof Error||(Lt(o),m("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",r||"React class",n,a,typeof s),Lt(null)),s instanceof Error&&!(s.message in jt)&&(jt[s.message]=!0,Lt(o),m("Failed %s type: %s",n,s.message),Lt(null))}}var Bt={},Wt={};function Ht(e,t){var n=e.contextTypes;if(!n)return Wt;var r,o={};for(r in n)o[r]=t[r];return Nt(n,o,"context",kt(e)||"Unknown"),o}Object.freeze(Wt);var Vt={},qt=null,$t=null;function Yt(e){e.context._currentValue2=e.parentValue}function Xt(e){e.context._currentValue2=e.value}function Zt(e,t){if(e!==t){Yt(e);var n=e.parent,e=t.parent;if(null===n){if(null!==e)throw new Error("The stacks must reach the root at the same time. This is a bug in React.")}else{if(null===e)throw new Error("The stacks must reach the root at the same time. This is a bug in React.");Zt(n,e)}Xt(t)}}function Gt(e){var t=$t,e=e;t!==e&&(null===t?function e(t){var n=t.parent;null!==n&&e(n),Xt(t)}(e):null===e?function e(t){Yt(t);t=t.parent;null!==t&&e(t)}(t):(t.depth===e.depth?Zt:t.depth>e.depth?function e(t,n){Yt(t);t=t.parent;if(null===t)throw new Error("The depth must equal at least at zero before reaching the root. This is a bug in React.");(t.depth===n.depth?Zt:e)(t,n)}:function e(t,n){var r=n.parent;if(null===r)throw new Error("The depth must equal at least at zero before reaching the root. This is a bug in React.");(t.depth===r.depth?Zt:e)(t,r),Xt(n)})(t,e),$t=e)}function Jt(e){return e._currentValue2}function Kt(e){return e._reactInternals}var Qt={},en={},tn=new Set,nn=new Set,rn=new Set,on=new Set,an=new Set,sn=new Set,ln=new Set,cn=new Set,un=function(e,t){var n;null!==e&&"function"!=typeof e&&(cn.has(n=t+"_"+e)||(cn.add(n),m("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.",t,e)))},dn=function(e,t){void 0===t&&(e=kt(e)||"Component",an.has(e)||(an.add(e),m("%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.",e)))};function pn(e,t){var n=e.constructor,e=n&&kt(n)||"ReactClass",n=e+"."+t;Qt[n]||(m("%s(...): Can only update a mounting component. This usually means you called %s() outside componentWillMount() on the server. This is a no-op.\n\nPlease check the code for the %s component.",t,t,e),Qt[n]=!0)}var fn={isMounted:function(e){return!1},enqueueSetState:function(e,t,n){var r=Kt(e);null===r.queue?pn(e,"setState"):(r.queue.push(t),null!=n&&un(n,"setState"))},enqueueReplaceState:function(e,t,n){e=Kt(e);e.replace=!0,e.queue=[t],null!=n&&un(n,"setState")},enqueueForceUpdate:function(e,t){null===Kt(e).queue?pn(e,"forceUpdate"):null!=t&&un(t,"setState")}};function hn(e,t){var n,r=t.state;"function"==typeof t.componentWillMount&&(!0!==t.componentWillMount.__suppressDeprecationWarning&&(n=kt(e)||"Unknown",en[n]||(function(e){for(var t=arguments.length,n=new Array(1<t?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];a("warn",e,n)}("componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code from componentWillMount to componentDidMount (preferred in most cases) or the constructor.\n\nPlease update the following components: %s",n),en[n]=!0)),t.componentWillMount()),"function"==typeof t.UNSAFE_componentWillMount&&t.UNSAFE_componentWillMount(),r!==t.state&&(m("%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",kt(e)||"Component"),fn.enqueueReplaceState(t,t.state,null))}function mn(e,t,n,r){var o;a=e,o=n,s=kt(i=t)||"Component",a.render||(i.prototype&&"function"==typeof i.prototype.render?m("%s(...): No `render` method found on the returned component instance: did you accidentally return an object from the constructor?",s):m("%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.",s)),!a.getInitialState||a.getInitialState.isReactClassApproved||a.state||m("getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",s),a.getDefaultProps&&!a.getDefaultProps.isReactClassApproved&&m("getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",s),a.propTypes&&m("propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.",s),a.contextType&&m("contextType was defined as an instance property on %s. Use a static property to define contextType instead.",s),a.contextTypes&&m("contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.",s),i.contextType&&i.contextTypes&&!sn.has(i)&&(sn.add(i),m("%s declares both contextTypes and contextType static properties. The legacy contextTypes property will be ignored.",s)),"function"==typeof a.componentShouldUpdate&&m("%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",s),i.prototype&&i.prototype.isPureReactComponent&&void 0!==a.shouldComponentUpdate&&m("%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.",kt(i)||"A pure component"),"function"==typeof a.componentDidUnmount&&m("%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",s),"function"==typeof a.componentDidReceiveProps&&m("%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().",s),"function"==typeof a.componentWillRecieveProps&&m("%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",s),"function"==typeof a.UNSAFE_componentWillRecieveProps&&m("%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",s),o=a.props!==o,void 0!==a.props&&o&&m("%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.",s,s),a.defaultProps&&m("Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.",s,s),"function"!=typeof a.getSnapshotBeforeUpdate||"function"==typeof a.componentDidUpdate||nn.has(i)||(nn.add(i),m("%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.",kt(i))),"function"==typeof a.getDerivedStateFromProps&&m("%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.",s),"function"==typeof a.getDerivedStateFromError&&m("%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.",s),"function"==typeof i.getSnapshotBeforeUpdate&&m("%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.",s),(o=a.state)&&("object"!=typeof o||de(o))&&m("%s.state: must be set to an object or null",s),"function"==typeof a.getChildContext&&"object"!=typeof i.childContextTypes&&m("%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",s);var a=void 0!==e.state?e.state:null;e.updater=fn,e.props=n,e.state=a;var i={queue:[],replace:!1};e._reactInternals=i;var s=t.contextType;e.context="object"==typeof s&&null!==s?Jt(s):r,e.state===n&&(l=kt(t)||"Component",on.has(l)||(on.add(l),m("%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.",l)));var l,s=t.getDerivedStateFromProps;"function"==typeof s&&(e.state=(l=t,s=s(s=n,a=a),dn(l,s),null==s?a:Qe({},a,s))),"function"==typeof t.getDerivedStateFromProps||"function"==typeof e.getSnapshotBeforeUpdate||"function"!=typeof e.UNSAFE_componentWillMount&&"function"!=typeof e.componentWillMount||(hn(t,e),function(e,t,n,r){if(null!==e.queue&&0<e.queue.length){var o=e.queue,a=e.replace;if(e.queue=null,e.replace=!1,a&&1===o.length)t.state=o[0];else{for(var i=a?o[0]:t.state,s=!0,l=a?1:0;l<o.length;l++){var c=o[l],c="function"==typeof c?c.call(t,i,n,r):c;null!=c&&(s?(s=!1,i=Qe({},i,c)):Qe(i,c))}t.state=i}}else e.queue=null}(i,e,n,r))}var gn={id:1,overflow:""};function yn(e){var t=e.overflow,e=e.id;return(e&~(1<<bn(e)-1)).toString(32)+t}function vn(e,t,n){var r=e.id,o=e.overflow,a=bn(r)-1,i=r&~(1<<a),s=n+1,l=bn(t)+a;if(30<l){e=a-a%5,r=(i&(1<<e)-1).toString(32),n=i>>e,e=a-e;return{id:1<<bn(t)+e|(s<<e|n),overflow:r+o}}return{id:1<<l|(s<<a|i),overflow:o}}function bn(e){return 32-kn(e)}var kn=Math.clz32||function(e){e>>>=0;return 0!=e?31-(xn(e)/wn|0)|0:32},xn=Math.log,wn=Math.LN2;var Sn,Cn="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},Tn=null,Rn=null,En=null,In=null,Pn=!1,Fn=!1,Mn=0,Dn=null,On=0,_n=25,An=!1;function Un(){if(null===Tn)throw new Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");return An&&m("Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks"),Tn}function jn(){if(0<On)throw new Error("Rendered more hooks than during the previous render");return{memoizedState:null,queue:null,next:null}}function zn(){return null===In?null===En?(Pn=!1,En=In=jn()):(Pn=!0,In=En):In=null===In.next?(Pn=!1,In.next=jn()):(Pn=!0,In.next),In}function Ln(){return 0!==Mn}function Nn(){Fn=An=!1,On=0,In=Dn=En=Rn=Tn=null}function Bn(e,t){return"function"==typeof t?t(e):t}function Wn(e,t,n){if(e!==Bn&&(Sn="useReducer"),Tn=Un(),In=zn(),Pn){var r=In.queue,o=r.dispatch;if(null!==Dn){var a=Dn.get(r);if(void 0!==a){Dn.delete(r);var i=In.memoizedState,s=a;do{var l=s.action}while(An=!0,i=e(i,l),An=!1,null!==(s=s.next));return[In.memoizedState=i,o]}}return[In.memoizedState,o]}An=!0,t=e===Bn?"function"==typeof t?t():t:void 0!==n?n(t):t,An=!1,In.memoizedState=t;t=In.queue={last:null,dispatch:null},t=t.dispatch=function(e,t,n){if(_n<=On)throw new Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");if(e===Tn){Fn=!0;e={action:n,next:null},n=(Dn=null===Dn?new Map:Dn).get(t);if(void 0===n)Dn.set(t,e);else{for(var r=n;null!==r.next;)r=r.next;r.next=e}}}.bind(null,Tn,t);return[In.memoizedState,t]}function Hn(e,t){Tn=Un();var n=void 0===t?null:t;if(null!==(In=zn())){t=In.memoizedState;if(null!==t)if(null!==n)if(function(e,t){if(null!==t){e.length!==t.length&&m("The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s",Sn,"["+e.join(", ")+"]","["+t.join(", ")+"]");for(var n=0;n<t.length&&n<e.length;n++)if(!Cn(e[n],t[n]))return;return 1}m("%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.",Sn)}(n,t[1]))return t[0]}An=!0;e=e();return An=!1,In.memoizedState=[e,n],e}function Vn(){throw new Error("startTransition cannot be called during server rendering.")}function qn(){}var $n={readContext:function(e){return An&&m("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."),Jt(e)},useContext:function(e){return Sn="useContext",Un(),Jt(e)},useMemo:Hn,useReducer:Wn,useRef:function(e){Tn=Un();var t=(In=zn()).memoizedState;return null!==t?t:(e={current:e},Object.seal(e),In.memoizedState=e)},useState:function(e){return Sn="useState",Wn(Bn,e)},useInsertionEffect:qn,useLayoutEffect:function(e,t){Sn="useLayoutEffect",m("useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for common fixes.")},useCallback:function(e,t){return Hn(function(){return e},t)},useImperativeHandle:qn,useEffect:qn,useDebugValue:qn,useDeferredValue:function(e){return Un(),e},useTransition:function(){return Un(),[!1,Vn]},useId:function(){var e=yn(Rn.treeContext),t=Yn;if(null===t)throw new Error("Invalid hook call. Hooks can only be called inside of the body of a function component.");var n=Mn++;return e=e,n=n,e=":"+t.idPrefix+"R"+e+":",0<n&&(e+=n.toString(32)+":"),e},useMutableSource:function(e,t,n){return Un(),t(e._source)},useSyncExternalStore:function(e,t,n){if(void 0===n)throw new Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");return n()}},Yn=null;function Xn(e){Yn=e}function Zn(e){try{var t="",n=e;do{switch(n.tag){case 0:t+=Dt(n.type);break;case 1:t+=Ut(n.type);break;case 2:t+=At(n.type,!0)}}while(n=n.parent);return t}catch(e){return"\nError generating stack: "+e.message+"\n"+e.stack}}var Gn=o.ReactCurrentDispatcher,Jn=o.ReactDebugCurrentFrame,Kn=0,Qn=1,er=2,tr=3,nr=4,rr=0,or=1,ar=2,ir=12800;function sr(e){console.error(e)}function lr(){}function cr(n,e,t,r,o,a,i,s){n.allPendingTasks++,null===t?n.pendingRootTasks++:t.pendingTasks++;var l={node:e,ping:function(){var e,t;(t=(e=n).pingedTasks).push(l),1===t.length&&g(function(){Br(e)})},blockedBoundary:t,blockedSegment:r,abortSet:o,legacyContext:a,context:i,treeContext:s,componentStack:null};return o.add(l),l}function ur(e,t,n,r){return{status:Kn,id:-1,index:t,parentFlushed:!1,chunks:[],children:[],formatContext:r,boundary:n}}var dr=null;function pr(){return null===dr||null===dr.componentStack?"":Zn(dr.componentStack)}function fr(e,t){e.componentStack={tag:0,parent:e.componentStack,type:t}}function hr(e,t){e.componentStack={tag:1,parent:e.componentStack,type:t}}function mr(e){null===e.componentStack?m("Unexpectedly popped too many stack frames. This is a bug in React."):e.componentStack=e.componentStack.parent}function gr(e,t){(0,e.onError)(t)}function yr(e,t){(0,e.onErrorShell)(t),null!==e.destination?(e.status=ar,y(e.destination,t)):(e.status=or,e.fatalError=t)}function vr(e,t,n,r){fr(t,n);var o=t.blockedSegment,a=je(o.chunks,n,r,e.responseState,o.formatContext),i=o.formatContext;o.formatContext=function(e,t,n){switch(t){case"select":return he(fe,null!=n.value?n.value:n.defaultValue);case"svg":return he(2,null);case"math":return he(3,null);case"foreignObject":return he(fe,null);case"table":return he(4,null);case"thead":case"tbody":case"tfoot":return he(5,null);case"colgroup":return he(7,null);case"tr":return he(6,null)}return 4<=e.insertionMode||0===e.insertionMode?he(fe,null):e}(i,n,r),Ur(e,t,a),o.formatContext=i,function(e,t){switch(t){case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"input":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":break;default:e.push("</",t,">")}}(o.chunks,n),mr(t)}function br(e,t,n,r,o){Tn={},Rn=t,An=!1,Mn=0;t=n(r,o);return function(e,t,n,r){for(;Fn;)Fn=!1,Mn=0,On+=1,In=null,n=e(t,r);return Nn(),n}(n,r,t,o)}function kr(e,t,n,r,o){var a=n.render();n.props!==o&&(Rr||m("It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.",kt(r)||"a component"),Rr=!0);var i=r.childContextTypes;if(null!=i){o=t.legacyContext,i=function(e,t,n,r){if("function"!=typeof e.getChildContext){var o=kt(t)||"Unknown";return Bt[o]||(Bt[o]=!0,m("%s.childContextTypes is specified but there is no getChildContext() method on the instance. You can either define getChildContext() on %s or remove childContextTypes from it.",o,o)),n}for(var a in e=e.getChildContext())if(!(a in r))throw new Error((kt(t)||"Unknown")+'.getChildContext(): key "'+a+'" is not defined in childContextTypes.');return Nt(r,e,"child context",kt(t)||"Unknown"),Qe({},n,e)}(n,r,o,i);return t.legacyContext=i,_r(e,t,a),void(t.legacyContext=o)}_r(e,t,a)}function xr(e,t,n,r){t.componentStack={tag:2,parent:t.componentStack,type:n};var o=Ht(n,t.legacyContext),a=function(e,t,n){var r=e.contextType;"contextType"in e&&(null===r||void 0!==r&&r.$$typeof===it&&void 0===r._context||ln.has(e)||(ln.add(e),a="",a=void 0===r?" However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file.":"object"!=typeof r?" However, it is set to a "+typeof r+".":r.$$typeof===at?" Did you accidentally pass the Context.Provider instead?":void 0!==r._context?" Did you accidentally pass the Context.Consumer instead?":" However, it is set to an object with keys {"+Object.keys(r).join(", ")+"}.",m("%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s",kt(e)||"Component",a)));var o,a=new e(t,"object"==typeof r&&null!==r?Jt(r):n);return"function"!=typeof e.getDerivedStateFromProps||null!==a.state&&void 0!==a.state||(o=kt(e)||"Component",tn.has(o)||(tn.add(o),m("`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.",o,null===a.state?"null":"undefined",o))),"function"!=typeof e.getDerivedStateFromProps&&"function"!=typeof a.getSnapshotBeforeUpdate||(n=r=t=null,"function"==typeof a.componentWillMount&&!0!==a.componentWillMount.__suppressDeprecationWarning?t="componentWillMount":"function"==typeof a.UNSAFE_componentWillMount&&(t="UNSAFE_componentWillMount"),"function"==typeof a.componentWillReceiveProps&&!0!==a.componentWillReceiveProps.__suppressDeprecationWarning?r="componentWillReceiveProps":"function"==typeof a.UNSAFE_componentWillReceiveProps&&(r="UNSAFE_componentWillReceiveProps"),"function"==typeof a.componentWillUpdate&&!0!==a.componentWillUpdate.__suppressDeprecationWarning?n="componentWillUpdate":"function"==typeof a.UNSAFE_componentWillUpdate&&(n="UNSAFE_componentWillUpdate"),null===t&&null===r&&null===n||(o=kt(e)||"Component",e="function"==typeof e.getDerivedStateFromProps?"getDerivedStateFromProps()":"getSnapshotBeforeUpdate()",rn.has(o)||(rn.add(o),m("Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://reactjs.org/link/unsafe-component-lifecycles",o,e,null!==t?"\n "+t:"",null!==r?"\n "+r:"",null!==n?"\n "+n:"")))),a}(n,r,o);mn(a,n,r,o),kr(e,t,a,n,r),mr(t)}var wr={},Sr={},Cr={},Tr={},Rr=!1,Er=!1,Ir=!1,Pr=!1;function Fr(e,t,n,r){var o=Ht(n,t.legacyContext);hr(t,n),n.prototype&&"function"==typeof n.prototype.render&&(i=kt(n)||"Unknown",wr[i]||(m("The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.",i,i),wr[i]=!0));var a=br(0,t,n,r,o),i=Ln();if("object"==typeof a&&null!==a&&"function"==typeof a.render&&void 0===a.$$typeof&&(s=kt(n)||"Unknown",Sr[s]||(m("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.",s,s,s),Sr[s]=!0)),"object"==typeof a&&null!==a&&"function"==typeof a.render&&void 0===a.$$typeof){var s=kt(n)||"Unknown";Sr[s]||(m("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.",s,s,s),Sr[s]=!0),mn(a,n,r,o),kr(e,t,a,n,r)}else if(!function(e){e&&e.childContextTypes&&m("%s(...): childContextTypes cannot be defined on a function component.",e.displayName||e.name||"Component");{var t;"function"==typeof e.getDerivedStateFromProps&&(t=kt(e)||"Unknown",Tr[t]||(m("%s: Function components do not support getDerivedStateFromProps.",t),Tr[t]=!0))}"object"==typeof e.contextType&&null!==e.contextType&&(e=kt(e)||"Unknown",Cr[e]||(m("%s: Function components do not support contextType.",e),Cr[e]=!0))}(n),i){i=t.treeContext;t.treeContext=vn(i,1,0);try{_r(e,t,a)}finally{t.treeContext=i}}else _r(e,t,a);mr(t)}function Mr(e,t){if(e&&e.defaultProps){var n,r=Qe({},t),o=e.defaultProps;for(n in o)void 0===r[n]&&(r[n]=o[n]);return r}return t}function Dr(e,t,n,r){var o=n._context,a=r.value,i=r.children,s=t.context;t.context=(n=a,a=(r=o)._currentValue2,r._currentValue2=n,void 0!==r._currentRenderer2&&null!==r._currentRenderer2&&r._currentRenderer2!==Vt&&m("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."),r._currentRenderer2=Vt,n={parent:$t,depth:null===$t?0:$t.depth+1,context:r,parentValue:a,value:n},$t=n),_r(e,t,i),t.context=function(e){var t=$t;if(null===t)throw new Error("Tried to pop a Context at the root of the app. This is a bug in React.");return t.context!==e&&m("The parent context is not the expected context. This is probably a bug in React."),t.context._currentValue2=t.parentValue,void 0!==e._currentRenderer2&&null!==e._currentRenderer2&&e._currentRenderer2!==Vt&&m("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."),e._currentRenderer2=Vt,$t=t.parent}(o),s!==t.context&&m("Popping the context provider did not return back to the original snapshot. This is a bug in React.")}function Or(e,t,n,r,o){if("function"==typeof n)return(c=n).prototype&&c.prototype.isReactComponent?void xr(e,t,n,r):void Fr(e,t,n,r);if("string"!=typeof n){switch(n){case ht:case ft:case rt:case ot:case nt:return void _r(e,t,r.children);case ct:return fr(t,"SuspenseList"),_r(e,t,r.children),void mr(t);case pt:throw new Error("ReactDOMServer does not yet support scope components.");case lt:return void function(t,e,n){fr(e,"Suspense");var r=e.blockedBoundary,o=e.blockedSegment,a=n.fallback,i=n.children,s=new Set,l={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:s},c=ur(0,o.chunks.length,l,o.formatContext);o.children.push(c),(n=ur(0,0,null,o.formatContext)).parentFlushed=!0,e.blockedBoundary=l,e.blockedSegment=n;try{if(Ur(t,e,i),n.status=Qn,l.completedSegments.push(n),0===l.pendingTasks)return mr(e)}catch(e){n.status=nr,gr(t,e),l.forceClientRender=!0}finally{e.blockedBoundary=r,e.blockedSegment=o}(s=cr(t,a,r,c,s,e.legacyContext,e.context,e.treeContext)).componentStack=e.componentStack,t.pingedTasks.push(s),mr(e)}(e,t,r)}if("object"==typeof n&&null!==n)switch(n.$$typeof){case st:return void function(e,t,n,r,o){if(hr(t,n.render),r=br(0,t,n.render,r,o),Ln()){o=t.treeContext;t.treeContext=vn(o,1,0);try{_r(e,t,r)}finally{t.treeContext=o}}else _r(e,t,r);mr(t)}(e,t,n,r,o);case ut:return l=o,s=(s=n).type,void Or(e,t,s,Mr(s,r),l);case at:return void Dr(e,t,n,r);case it:return a=e,i=t,s=r,void 0===(l=n)._context?l!==l.Consumer&&(Pr||(Pr=!0,m("Rendering <Context> directly is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?"))):l=l._context,"function"!=typeof(s=s.children)&&m("A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."),void _r(a,i,s(Jt(l)));case dt:return void function(e,t,n,r,o){fr(t,"Lazy");var a=n._payload,a=(0,n._init)(a);Or(e,t,a,Mr(a,r),o),mr(t)}(e,t,n,r)}var a,i,s,l,c="";throw(void 0===n||"object"==typeof n&&null!==n&&0===Object.keys(n).length)&&(c+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."),new Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: "+(null==n?n:typeof n)+"."+c)}vr(e,t,n,r)}function _r(e,t,n){if("object"==typeof(t.node=n)&&null!==n){switch(n.$$typeof){case et:return void Or(e,t,n.type,n.props,n.ref);case tt:throw new Error("Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render.");case dt:var r=n._payload;return void _r(e,t,(0,n._init)(r))}if(de(n))return void Ar(e,t,n);var o=null!==(c=n)&&"object"==typeof c&&"function"==typeof(c=yt&&c[yt]||c[vt])?c:null;if(o){l=n,c=o(),"function"==typeof Symbol&&"Generator"===l[Symbol.toStringTag]&&(Er||m("Using Generators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. Keep in mind you might need to polyfill these features for older browsers."),Er=!0),l.entries===c&&(Ir||m("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Ir=!0);var a=o.call(n);if(a){var i=a.next();if(i.done)return;for(var s=[];s.push(i.value),!(i=a.next()).done;);return void Ar(e,t,s)}}o=Object.prototype.toString.call(n);throw new Error("Objects are not valid as a React child (found: "+("[object Object]"===o?"object with keys {"+Object.keys(n).join(", ")+"}":o)+"). If you meant to render a collection of children, use an array instead.")}var l,c;"string"!=typeof n?"number"!=typeof n?"function"==typeof n&&m("Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it."):Xe(t.blockedSegment.chunks,""+n,e.responseState):Xe(t.blockedSegment.chunks,n,e.responseState)}function Ar(e,t,n){for(var r=n.length,o=0;o<r;o++){var a=t.treeContext;t.treeContext=vn(a,r,o);try{Ur(e,t,n[o])}finally{t.treeContext=a}}}function Ur(t,n,r){var o,a,i,s=n.blockedSegment.formatContext,l=n.legacyContext,c=n.context,u=n.componentStack;try{return _r(t,n,r)}catch(e){if(Nn(),"object"==typeof e&&null!==e&&"function"==typeof e.then)return o=t,i=e,r=(a=n).blockedSegment,t=ur(0,r.chunks.length,null,r.formatContext),r.children.push(t),t=cr(o,a.node,a.blockedBoundary,t,a.abortSet,a.legacyContext,a.context,a.treeContext),null!==a.componentStack&&(t.componentStack=a.componentStack.parent),t=t.ping,i.then(t,t),n.blockedSegment.formatContext=s,n.legacyContext=l,Gt(n.context=c),void(n.componentStack=u);throw n.blockedSegment.formatContext=s,n.legacyContext=l,Gt(n.context=c),n.componentStack=u,e}}function jr(e){var t=e.blockedBoundary,e=e.blockedSegment;e.status=tr,Lr(this,t,e)}function zr(e){var t=this,n=e.blockedBoundary;e.blockedSegment.status=tr,null===n?(t.allPendingTasks--,t.status!==ar&&(t.status=ar,null!==t.destination&&l(t.destination))):(n.pendingTasks--,n.forceClientRender||(n.forceClientRender=!0,n.parentFlushed&&t.clientRenderedBoundaries.push(n)),n.fallbackAbortableTasks.forEach(zr,t),n.fallbackAbortableTasks.clear(),t.allPendingTasks--,0===t.allPendingTasks&&(0,t.onCompleteAll)())}function Lr(e,t,n){if(null===t){if(n.parentFlushed){if(null!==e.completedRootSegment)throw new Error("There can only be one root segment. This is a bug in React.");e.completedRootSegment=n}e.pendingRootTasks--,0===e.pendingRootTasks&&(e.onErrorShell=lr,(0,e.onCompleteShell)())}else{var r;t.pendingTasks--,t.forceClientRender||(0===t.pendingTasks?(n.parentFlushed&&n.status===Qn&&t.completedSegments.push(n),t.parentFlushed&&e.completedBoundaries.push(t),t.fallbackAbortableTasks.forEach(jr,e),t.fallbackAbortableTasks.clear()):n.parentFlushed&&n.status===Qn&&((r=t.completedSegments).push(n),1===r.length&&t.parentFlushed&&e.partialBoundaries.push(t)))}e.allPendingTasks--,0===e.allPendingTasks&&(0,e.onCompleteAll)()}function Nr(t,n){var r=n.blockedSegment;if(r.status===Kn){Gt(n.context);var o,a,i,s,e=dr;dr=n;try{_r(t,n,n.node),n.abortSet.delete(n),r.status=Qn,Lr(t,n.blockedBoundary,r)}catch(e){Nn(),"object"==typeof e&&null!==e&&"function"==typeof e.then?(o=n.ping,e.then(o,o)):(n.abortSet.delete(n),r.status=nr,a=t,i=n.blockedBoundary,gr(a,s=e),null===i?yr(a,s):(i.pendingTasks--,i.forceClientRender||(i.forceClientRender=!0,i.parentFlushed&&a.clientRenderedBoundaries.push(i))),a.allPendingTasks--,0===a.allPendingTasks&&(0,a.onCompleteAll)())}finally{dr=e}}}function Br(t){if(t.status!==ar){var e,n=$t,r=Gn.current;Gn.current=$n,e=Jn.getCurrentStack,Jn.getCurrentStack=pr;var o=Yn;Xn(t.responseState);try{for(var a=t.pingedTasks,i=0;i<a.length;i++)Nr(t,a[i]);a.splice(0,i),null!==t.destination&&Xr(t,t.destination)}catch(e){gr(t,e),yr(t,e)}finally{Xn(o),Gn.current=r,Jn.getCurrentStack=e,r===$n&&Gt(n)}}}function Wr(e,t,n){switch(n.parentFlushed=!0,n.status){case Kn:var r=n.id=e.nextSegmentId++;return u=t,d=e.responseState,r=r,p(u,'<template id="'),p(u,d.placeholderPrefix),p(u,r.toString(16)),f(u,'"></template>');case Qn:n.status=er;for(var o=!0,a=n.chunks,i=0,s=n.children,l=0;l<s.length;l++){for(var c=s[l];i<c.index;i++)p(t,a[i]);o=Hr(e,t,c)}for(;i<a.length-1;i++)p(t,a[i]);return o=i<a.length?f(t,a[i]):o;default:throw new Error("Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.")}var u,d}function Hr(e,t,n){var r=n.boundary;if(null===r)return Wr(e,t,n);if(r.parentFlushed=!0,r.forceClientRender)return Ge(t,e.responseState),Wr(e,t,n),Ke(t,e.responseState);if(0<r.pendingTasks){r.rootSegmentID=e.nextSegmentId++,0<r.completedSegments.length&&e.partialBoundaries.push(r);a=r.id=(o=e.responseState,a=o.nextSuspenseID++,o.boundaryPrefix+a.toString(16));return Be(t,e.responseState,a),Wr(e,t,n),We(t,e.responseState)}if(r.byteSize>e.progressiveChunkSize)return r.rootSegmentID=e.nextSegmentId++,e.completedBoundaries.push(r),Be(t,e.responseState,r.id),Wr(e,t,n),We(t,e.responseState);Ze(t,e.responseState);var o,a,r=r.completedSegments;if(1!==r.length)throw new Error("A previously unvisited boundary must have exactly one root segment. This is a bug in React.");return Hr(e,t,r[0]),Je(t,e.responseState)}function Vr(e,t,n){return function(e,t,n){if(p(e,t.startInlineScript),t.sentClientRenderFunction?p(e,'$RX("'):(t.sentClientRenderFunction=!0,p(e,'function $RX(a){if(a=document.getElementById(a))a=a.previousSibling,a.data="$!",a._reactRetry&&a._reactRetry()};$RX("')),null===n)throw new Error("An ID must have been assigned before we can complete the boundary.");return p(e,n),f(e,'")<\/script>')}(t,e.responseState,n.id)}function qr(e,t,n){return function(e,t,n,r){switch(n.insertionMode){case 0:case fe:return p(e,'<div hidden id="'),p(e,t.segmentPrefix),p(e,r.toString(16)),f(e,'">');case 2:return p(e,'<svg aria-hidden="true" style="display:none" id="'),p(e,t.segmentPrefix),p(e,r.toString(16)),f(e,'">');case 3:return p(e,'<math aria-hidden="true" style="display:none" id="'),p(e,t.segmentPrefix),p(e,r.toString(16)),f(e,'">');case 4:return p(e,'<table hidden id="'),p(e,t.segmentPrefix),p(e,r.toString(16)),f(e,'">');case 5:return p(e,'<table hidden><tbody id="'),p(e,t.segmentPrefix),p(e,r.toString(16)),f(e,'">');case 6:return p(e,'<table hidden><tr id="'),p(e,t.segmentPrefix),p(e,r.toString(16)),f(e,'">');case 7:return p(e,'<table hidden><colgroup id="'),p(e,t.segmentPrefix),p(e,r.toString(16)),f(e,'">');default:throw new Error("Unknown insertion mode. This is a bug in React.")}}(t,e.responseState,n.formatContext,n.id),Hr(e,t,n),function(e,t){switch(t.insertionMode){case 0:case fe:return f(e,"</div>");case 2:return f(e,"</svg>");case 3:return f(e,"</math>");case 4:return f(e,"</table>");case 5:return f(e,"</tbody></table>");case 6:return f(e,"</tr></table>");case 7:return f(e,"</colgroup></table>");default:throw new Error("Unknown insertion mode. This is a bug in React.")}}(t,n.formatContext)}function $r(e,t,n){for(var r=n.completedSegments,o=0;o<r.length;o++)Yr(e,t,n,r[o]);return r.length=0,function(e,t,n,r){if(p(e,t.startInlineScript),t.sentCompleteBoundaryFunction?p(e,'$RC("'):(t.sentCompleteBoundaryFunction=!0,p(e,'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("')),null===n)throw new Error("An ID must have been assigned before we can complete the boundary.");return r=r.toString(16),p(e,n),p(e,'","'),p(e,t.segmentPrefix),p(e,r),f(e,'")<\/script>')}(t,e.responseState,n.id,n.rootSegmentID)}function Yr(e,t,n,r){if(r.status===er)return 1;var o,a,i=r.id;if(-1!==i)return qr(e,t,r),o=t,a=e.responseState,i=i,p(o,a.startInlineScript),a.sentCompleteSegmentFunction?p(o,Ve):(a.sentCompleteSegmentFunction=!0,p(o,He)),p(o,a.segmentPrefix),i=i.toString(16),p(o,i),p(o,qe),p(o,a.placeholderPrefix),p(o,i),f(o,$e);if(-1===(r.id=n.rootSegmentID))throw new Error("A root segment ID must have been assigned by now. This is a bug in React.");return qr(e,t,r)}function Xr(e,t){try{var n=e.completedRootSegment;null!==n&&0===e.pendingRootTasks&&(Hr(e,t,n),e.completedRootSegment=null,function(e,t){for(var n=t.bootstrapChunks,r=0;r<n.length-1;r++)p(e,n[r]);r<n.length&&f(e,n[r])}(t,e.responseState));for(var r=e.clientRenderedBoundaries,o=0;o<r.length;o++)if(!Vr(e,t,r[o]))return e.destination=null,o++,void r.splice(0,o);r.splice(0,o);var a=e.completedBoundaries;for(o=0;o<a.length;o++)if(!$r(e,t,a[o]))return e.destination=null,o++,void a.splice(0,o);a.splice(0,o);var i=e.partialBoundaries;for(o=0;o<i.length;o++)if(!function(e,t,n){for(var r=n.completedSegments,o=0;o<r.length;o++)if(!Yr(e,t,n,r[o]))return o++,void r.splice(0,o);return r.splice(0,o),1}(e,t,i[o]))return e.destination=null,o++,void i.splice(0,o);i.splice(0,o);var s=e.completedBoundaries;for(o=0;o<s.length;o++)if(!$r(e,t,s[o]))return e.destination=null,o++,void s.splice(0,o);s.splice(0,o)}finally{0===e.allPendingTasks&&0===e.pingedTasks.length&&0===e.clientRenderedBoundaries.length&&0===e.completedBoundaries.length&&(0!==e.abortableTasks.size&&m("There was still abortable task at the root when we closed. This is a bug in React."),l(t))}}function Zr(){}function Gr(e,t,n){var r=!1,o=null,a="",i={push:function(e){return null!==e&&(a+=e),!0},destroy:function(e){r=!0,o=e}},s=!1;var l,c,u,d,p,f,h,m,h=(l=e,c=Ye(n,t?t.identifierPrefix:void 0),u={insertionMode:fe,selectedValue:null},d=1/0,p=Zr,f=void 0,e=function(){s=!0},n=[],t=new Set,(u=ur(h={destination:null,responseState:c,progressiveChunkSize:void 0===d?ir:d,status:rr,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:t,pingedTasks:n,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===p?sr:p,onCompleteAll:void 0===f?lr:f,onCompleteShell:void 0===e?lr:e,onErrorShell:void 0===h?lr:h},0,null,u)).parentFlushed=!0,t=cr(h,l,null,u,t,Wt,qt,gn),n.push(t),h);if(m=h,g(function(){Br(m)}),function(t){try{var e=t.abortableTasks;e.forEach(zr,t),e.clear(),null!==t.destination&&Xr(t,t.destination)}catch(e){gr(t,e),yr(t,e)}}(h),function(t,e){if(t.status===or)return t.status=ar,y(e,t.fatalError);if(t.status!==ar&&null===t.destination){t.destination=e;try{Xr(t,e)}catch(e){gr(t,e),yr(t,e)}}}(h,i),r)throw o;if(!s)throw new Error("A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.");return a}exports.renderToNodeStream=function(){throw new Error("ReactDOMServer.renderToNodeStream(): The streaming API is not available in the browser. Use ReactDOMServer.renderToString() instead.")},exports.renderToStaticMarkup=function(e,t){return Gr(e,t,!0)},exports.renderToStaticNodeStream=function(){throw new Error("ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.")},exports.renderToString=function(e,t){return Gr(e,t,!1)},exports.version="18.0.0-rc.1-629036a9c-20220224"}(); |
examples/huge-apps/routes/Course/routes/Announcements/components/Announcements.js | trotzig/react-router | import React from 'react';
class Announcements extends React.Component {
render () {
return (
<div>
<h3>Announcements</h3>
{this.props.children || <p>Choose an announcement from the sidebar.</p>}
</div>
);
}
}
export default Announcements;
|
src/components/navElem.js | ryannma/website | import React from 'react';
import { Link, browserHistory, Router } from 'react-router';
import classNames from 'classnames';
const NavElem = React.createClass({
handleClick: function(path) {
browserHistory.push(path);
},
render: function() {
let path = this.props.path;
let location = this.props.location;
let navElemClass = classNames(
"nav-element",
{active: location === path ? true : false});
return (
<span
className={navElemClass}
onClick={this.handleClick.bind(this, path)}
>
{this.props.display}
</span>
);
}
});
export default NavElem; |
src/components/Link/Link.js | cineindustria/site | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import history from '../../history';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
class Link extends React.Component {
static propTypes = {
to: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
onClick: PropTypes.func,
};
static defaultProps = {
onClick: null,
};
handleClick = (event) => {
if (this.props.onClick) {
this.props.onClick(event);
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
if (event.defaultPrevented === true) {
return;
}
event.preventDefault();
history.push(this.props.to);
};
render() {
const { to, children, ...props } = this.props;
return <a href={to} {...props} onClick={this.handleClick}>{children}</a>;
}
}
export default Link;
|
app/javascript/mastodon/features/public_timeline/index.js | tootsuite/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandPublicTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import ColumnSettingsContainer from './containers/column_settings_container';
import { connectPublicStream } from '../../actions/streaming';
const messages = defineMessages({
title: { id: 'column.public', defaultMessage: 'Federated timeline' },
});
const mapStateToProps = (state, { columnId }) => {
const uuid = columnId;
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === uuid);
const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']);
const onlyRemote = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyRemote']) : state.getIn(['settings', 'public', 'other', 'onlyRemote']);
const timelineState = state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`]);
return {
hasUnread: !!timelineState && timelineState.get('unread') > 0,
onlyMedia,
onlyRemote,
};
};
export default @connect(mapStateToProps)
@injectIntl
class PublicTimeline extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static defaultProps = {
onlyMedia: false,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasUnread: PropTypes.bool,
onlyMedia: PropTypes.bool,
onlyRemote: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch, onlyMedia, onlyRemote } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn(onlyRemote ? 'REMOTE' : 'PUBLIC', { other: { onlyMedia, onlyRemote } }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, onlyMedia, onlyRemote } = this.props;
dispatch(expandPublicTimeline({ onlyMedia, onlyRemote }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote }));
}
componentDidUpdate (prevProps) {
if (prevProps.onlyMedia !== this.props.onlyMedia || prevProps.onlyRemote !== this.props.onlyRemote) {
const { dispatch, onlyMedia, onlyRemote } = this.props;
this.disconnect();
dispatch(expandPublicTimeline({ onlyMedia, onlyRemote }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote }));
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { dispatch, onlyMedia, onlyRemote } = this.props;
dispatch(expandPublicTimeline({ maxId, onlyMedia, onlyRemote }));
}
render () {
const { intl, columnId, hasUnread, multiColumn, onlyMedia, onlyRemote } = this.props;
const pinned = !!columnId;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='globe'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer columnId={columnId} />
</ColumnHeader>
<StatusListContainer
timelineId={`public${onlyRemote ? ':remote' : ''}${onlyMedia ? ':media' : ''}`}
onLoadMore={this.handleLoadMore}
trackScroll={!pinned}
scrollKey={`public_timeline-${columnId}`}
emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other servers to fill it up' />}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
packages/slate-html-serializer/benchmark/html-serializer/serialize.js | 6174/slate | /** @jsx h */
/* eslint-disable react/jsx-key */
import Html from '../..'
import React from 'react'
import h from '../../test/helpers/h'
import parse5 from 'parse5' // eslint-disable-line import/no-extraneous-dependencies
const html = new Html({
parseHtml: parse5.parseFragment,
rules: [
{
serialize(obj, children) {
switch (obj.kind) {
case 'block': {
switch (obj.type) {
case 'paragraph': return React.createElement('p', {}, children)
case 'quote': return React.createElement('blockquote', {}, children)
}
}
case 'mark': {
switch (obj.type) {
case 'bold': return React.createElement('strong', {}, children)
case 'italic': return React.createElement('em', {}, children)
}
}
}
}
}
]
})
export default function (state) {
html.serialize(state)
}
export const input = (
<state>
<document>
{Array.from(Array(10)).map(() => (
<quote>
<paragraph>
This is editable <b>rich</b> text, <i>much</i> better than a textarea!
</paragraph>
</quote>
))}
</document>
</state>
)
|
tests/views/HomeView.spec.js | davecarlson/reacty | import React from 'react'
import TestUtils from 'react-addons-test-utils'
import { bindActionCreators } from 'redux'
import { HomeView } from 'views/HomeView/HomeView'
import { mount } from 'enzyme'
function shallowRender (component) {
const renderer = TestUtils.createRenderer()
renderer.render(component)
return renderer.getRenderOutput()
}
function renderWithProps (props = {}) {
return TestUtils.renderIntoDocument(<HomeView {...props} />)
}
function shallowRenderWithProps (props = {}) {
return shallowRender(<HomeView {...props} />)
}
describe('(View) Home', function () {
let _component, _rendered, _props, _spies
beforeEach(function () {
_spies = {}
_props = {
counter: 0,
...bindActionCreators({
doubleAsync: (_spies.doubleAsync = sinon.spy()),
increment: (_spies.increment = sinon.spy())
}, _spies.dispatch = sinon.spy())
}
_component = shallowRenderWithProps(_props)
_rendered = renderWithProps(_props)
})
it('Should render as a <div>.', function () {
expect(_component.type).to.equal('div')
})
it('Should include an <h1> with welcome text.', function () {
const h1 = TestUtils.findRenderedDOMComponentWithTag(_rendered, 'h1')
expect(h1).to.exist
expect(h1.textContent).to.match(/Welcome to the React Redux Starter Kit/)
})
it('Should render with an <h2> that includes Sample Counter text.', function () {
const h2 = TestUtils.findRenderedDOMComponentWithTag(_rendered, 'h2')
expect(h2).to.exist
expect(h2.textContent).to.match(/Sample Counter/)
})
it('Should render props.counter at the end of the sample counter <h2>.', function () {
const h2 = TestUtils.findRenderedDOMComponentWithTag(
renderWithProps({ ..._props, counter: 5 }), 'h2'
)
expect(h2).to.exist
expect(h2.textContent).to.match(/5$/)
})
it('Should render exactly two buttons.', function () {
const wrapper = mount(<HomeView {..._props} />)
expect(wrapper).to.have.descendants('.btn')
})
describe('An increment button...', function () {
let _btn
beforeEach(() => {
_btn = TestUtils.scryRenderedDOMComponentsWithTag(_rendered, 'button')
.filter(a => /Increment/.test(a.textContent))[0]
})
it('should be rendered.', function () {
expect(_btn).to.exist
})
it('should dispatch an action when clicked.', function () {
_spies.dispatch.should.have.not.been.called
TestUtils.Simulate.click(_btn)
_spies.dispatch.should.have.been.called
})
})
describe('A Double (Async) button...', function () {
let _btn
beforeEach(() => {
_btn = TestUtils.scryRenderedDOMComponentsWithTag(_rendered, 'button')
.filter(a => /Double/.test(a.textContent))[0]
})
it('should be rendered.', function () {
expect(_btn).to.exist
})
it('should dispatch an action when clicked.', function () {
_spies.dispatch.should.have.not.been.called
TestUtils.Simulate.click(_btn)
_spies.dispatch.should.have.been.called
})
})
})
|
core/frontend/themes/default/assets/js/jquery.min.js | phpjim/cmf-old | /*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-1.10.2.min.map
*/
(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t
}({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle);
u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
/*! jQuery Migrate v1.2.2-pre | (c) 2005, 2013 jQuery Foundation, Inc. and other contributors | jquery.org/license */
void 0===jQuery.migrateMute&&(jQuery.migrateMute=!0),function(e,t,n){function i(n){var i=t.console;a[n]||(a[n]=!0,e.migrateWarnings.push(n),i&&i.warn&&!e.migrateMute&&(i.warn("JQMIGRATE: "+n),e.migrateTrace&&i.trace&&i.trace()))}function r(t,r,a,o){if(Object.defineProperty)try{return Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get:function(){return i(o),a},set:function(e){i(o),a=e}}),n}catch(s){}e._definePropertyBroken=!0,t[r]=a}var a={};e.migrateWarnings=[],!e.migrateMute&&t.console&&t.console.log&&t.console.log("JQMIGRATE: Logging is active"),e.migrateTrace===n&&(e.migrateTrace=!0),e.migrateReset=function(){a={},e.migrateWarnings.length=0},"BackCompat"===document.compatMode&&i("jQuery is not compatible with Quirks Mode");var o=e("<input/>",{size:1}).attr("size")&&e.attrFn,s=e.attr,l=e.attrHooks.value&&e.attrHooks.value.get||function(){return null},c=e.attrHooks.value&&e.attrHooks.value.set||function(){return n},u=/^(?:input|button)$/i,d=/^[238]$/,h=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,f=/^(?:checked|selected)$/i;r(e,"attrFn",o||{},"jQuery.attrFn is deprecated"),e.attr=function(t,r,a,l){var c=r.toLowerCase(),p=t&&t.nodeType;return l&&(4>s.length&&i("jQuery.fn.attr( props, pass ) is deprecated"),t&&!d.test(p)&&(o?r in o:e.isFunction(e.fn[r])))?e(t)[r](a):("type"===r&&a!==n&&u.test(t.nodeName)&&t.parentNode&&i("Can't change the 'type' of an input or button in IE 6/7/8"),!e.attrHooks[c]&&h.test(c)&&(e.attrHooks[c]={get:function(t,i){var r,a=e.prop(t,i);return a===!0||"boolean"!=typeof a&&(r=t.getAttributeNode(i))&&r.nodeValue!==!1?i.toLowerCase():n},set:function(t,n,i){var r;return n===!1?e.removeAttr(t,i):(r=e.propFix[i]||i,r in t&&(t[r]=!0),t.setAttribute(i,i.toLowerCase())),i}},f.test(c)&&i("jQuery.fn.attr('"+c+"') may use property instead of attribute")),s.call(e,t,r,a))},e.attrHooks.value={get:function(e,t){var n=(e.nodeName||"").toLowerCase();return"button"===n?l.apply(this,arguments):("input"!==n&&"option"!==n&&i("jQuery.fn.attr('value') no longer gets properties"),t in e?e.value:null)},set:function(e,t){var r=(e.nodeName||"").toLowerCase();return"button"===r?c.apply(this,arguments):("input"!==r&&"option"!==r&&i("jQuery.fn.attr('value', val) no longer sets properties"),e.value=t,n)}};var p,m,g=e.fn.init,v=e.parseJSON,y=/^([^<]*)(<[\w\W]+>)([^>]*)$/;e.fn.init=function(t,n,r){var a;return t&&"string"==typeof t&&!e.isPlainObject(n)&&(a=y.exec(e.trim(t)))&&a[0]&&("<"!==t.charAt(0)&&i("$(html) HTML strings must start with '<' character"),a[3]&&i("$(html) HTML text after last tag is ignored"),"#"===a[0].charAt(0)&&(i("HTML string cannot start with a '#' character"),e.error("JQMIGRATE: Invalid selector string (XSS)")),n&&n.context&&(n=n.context),e.parseHTML)?g.call(this,e.parseHTML(a[2],n,!0),n,r):g.apply(this,arguments)},e.fn.init.prototype=e.fn,e.parseJSON=function(e){return e?v.apply(this,arguments):(i("jQuery.parseJSON requires a valid JSON string"),null)},e.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||0>e.indexOf("compatible")&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e.browser||(p=e.uaMatch(navigator.userAgent),m={},p.browser&&(m[p.browser]=!0,m.version=p.version),m.chrome?m.webkit=!0:m.webkit&&(m.safari=!0),e.browser=m),r(e,"browser",e.browser,"jQuery.browser is deprecated"),e.boxModel=e.support.boxModel="CSS1Compat"===document.compatMode,r(e,"boxModel",e.boxModel,"jQuery.boxModel is deprecated"),r(e.support,"boxModel",e.support.boxModel,"jQuery.support.boxModel is deprecated"),e.sub=function(){function t(e,n){return new t.fn.init(e,n)}e.extend(!0,t,this),t.superclass=this,t.fn=t.prototype=this(),t.fn.constructor=t,t.sub=this.sub,t.fn.init=function(i,r){var a=e.fn.init.call(this,i,r,n);return a instanceof t?a:t(a)},t.fn.init.prototype=t.fn;var n=t(document);return i("jQuery.sub() is deprecated"),t},e.ajaxSetup({converters:{"text json":e.parseJSON}});var b=e.fn.data;e.fn.data=function(t){var r,a,o=this[0];return!o||"events"!==t||1!==arguments.length||(r=e.data(o,t),a=e._data(o,t),r!==n&&r!==a||a===n)?b.apply(this,arguments):(i("Use of jQuery.fn.data('events') is deprecated"),a)};var w=/\/(java|ecma)script/i,x=e.fn.andSelf||e.fn.addBack;e.fn.andSelf=function(){return i("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()"),x.apply(this,arguments)},e.clean||(e.clean=function(t,r,a,o){r=r||document,r=!r.nodeType&&r[0]||r,r=r.ownerDocument||r,i("jQuery.clean() is deprecated");var s,l,c,u,d=[];if(e.merge(d,e.buildFragment(t,r).childNodes),a)for(c=function(e){return!e.type||w.test(e.type)?o?o.push(e.parentNode?e.parentNode.removeChild(e):e):a.appendChild(e):n},s=0;null!=(l=d[s]);s++)e.nodeName(l,"script")&&c(l)||(a.appendChild(l),l.getElementsByTagName!==n&&(u=e.grep(e.merge([],l.getElementsByTagName("script")),c),d.splice.apply(d,[s+1,0].concat(u)),s+=u.length));return d});var _=e.event.add,k=e.event.remove,C=e.event.trigger,T=e.fn.toggle,S=e.fn.live,E=e.fn.die,$="ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",A=RegExp("\\b(?:"+$+")\\b"),I=/(?:^|\s)hover(\.\S+|)\b/,D=function(t){return"string"!=typeof t||e.event.special.hover?t:(I.test(t)&&i("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"),t&&t.replace(I,"mouseenter$1 mouseleave$1"))};e.event.props&&"attrChange"!==e.event.props[0]&&e.event.props.unshift("attrChange","attrName","relatedNode","srcElement"),e.event.dispatch&&r(e.event,"handle",e.event.dispatch,"jQuery.event.handle is undocumented and deprecated"),e.event.add=function(e,t,n,r,a){e!==document&&A.test(t)&&i("AJAX events should be attached to document: "+t),_.call(this,e,D(t||""),n,r,a)},e.event.remove=function(e,t,n,i,r){k.call(this,e,D(t)||"",n,i,r)},e.fn.error=function(){var e=Array.prototype.slice.call(arguments,0);return i("jQuery.fn.error() is deprecated"),e.splice(0,0,"error"),arguments.length?this.bind.apply(this,e):(this.triggerHandler.apply(this,e),this)},e.fn.toggle=function(t,n){if(!e.isFunction(t)||!e.isFunction(n))return T.apply(this,arguments);i("jQuery.fn.toggle(handler, handler...) is deprecated");var r=arguments,a=t.guid||e.guid++,o=0,s=function(n){var i=(e._data(this,"lastToggle"+t.guid)||0)%o;return e._data(this,"lastToggle"+t.guid,i+1),n.preventDefault(),r[i].apply(this,arguments)||!1};for(s.guid=a;r.length>o;)r[o++].guid=a;return this.click(s)},e.fn.live=function(t,n,r){return i("jQuery.fn.live() is deprecated"),S?S.apply(this,arguments):(e(this.context).on(t,this.selector,n,r),this)},e.fn.die=function(t,n){return i("jQuery.fn.die() is deprecated"),E?E.apply(this,arguments):(e(this.context).off(t,this.selector||"**",n),this)},e.event.trigger=function(e,t,n,r){return n||A.test(e)||i("Global events are undocumented and deprecated"),C.call(this,e,t,n||document,r)},e.each($.split("|"),function(t,n){e.event.special[n]={setup:function(){var t=this;return t!==document&&(e.event.add(document,n+"."+e.guid,function(){e.event.trigger(n,null,t,!0)}),e._data(this,n,e.guid++)),!1},teardown:function(){return this!==document&&e.event.remove(document,n+"."+e._data(this,n)),!1}}})}(jQuery,window);
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie=function(e,i,o){if("undefined"==typeof i){var n=null;if(document.cookie&&""!=document.cookie)for(var r=document.cookie.split(";"),t=0;t<r.length;t++){var p=jQuery.trim(r[t]);if(p.substring(0,e.length+1)==e+"="){n=decodeURIComponent(p.substring(e.length+1));break}}return n}o=o||{},null===i&&(i="",o.expires=-1);var u="";if(o.expires&&("number"==typeof o.expires||o.expires.toUTCString)){var s;"number"==typeof o.expires?(s=new Date,s.setTime(s.getTime()+24*o.expires*60*60*1e3)):s=o.expires,u="; expires="+s.toUTCString()}var a=o.path?"; path="+o.path:"",c=o.domain?"; domain="+o.domain:"",m=o.secure?"; secure":"";document.cookie=[e,"=",encodeURIComponent(i),u,a,c,m].join("")}; |
src/components/MaintainBusinessRules/AddBusinessRule.js | RegOpz/RegOpzWebApp | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { bindActionCreators, dispatch } from 'redux';
import DatePicker from 'react-datepicker';
import { Button } from 'react-bootstrap';
import {
Link,
hashHistory
} from 'react-router';
import { WithContext as ReactTags } from 'react-tag-input';
import _ from 'lodash';
import RuleAssist from './RuleAssist';
import {
actionFetchSources,
actionFetchSourceColumnList
} from '../../actions/MaintainReportRuleAction';
import {
actionInsertBusinessRule,
actionUpdateBusinessRule
} from '../../actions/BusinessRulesAction';
class AddBusinessRule extends Component {
constructor(props) {
super(props);
this.state = {
rulesTags: [],
dataFieldsTags: [],
fieldsSuggestions: [],
dataFieldsSuggestions: [],
componentDidUpdateCount: 0,
requestType: this.props.businessRule && this.props.businessRule.id ? "update":"add",
ruleIndex: null,
readOnly: !this.props.editable,
form: {
id: null,
source_id: null,
rule_execution_order: null,
business_rule: null,
rule_description: null,
logical_condition: null,
python_implementation: null,
data_fields_list: null,
business_or_validation: null,
rule_type: null,
last_updated_by: null
},
audit_form: {
comment: null
},
showRuleAssist: false,
selectedSource: null,
ruleAssistProps: null
};
// this.handleRuleRefDelete = this.handleRuleRefDelete.bind(this);
// this.handleRuleRefAddition = this.handleRuleRefAddition.bind(this);
// this.handleRuleRefDrag = this.handleRuleRefDrag.bind(this);
this.handleDataFieldsDelete = this.handleDataFieldsDelete.bind(this);
this.handleDataFieldsAddition = this.handleDataFieldsAddition.bind(this);
this.handleDataFieldsDrag = this.handleDataFieldsDrag.bind(this);
this.searchAnywhere = this.searchAnywhere.bind(this);
this.handleRuleAssistClick = this.handleRuleAssistClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentWillReceiveProps(nextProps) {
console.log('Next Props: ', nextProps);
}
componentWillMount() {
this.props.fetchSources();
console.log("Inside componentWillMount of AddBusinessRule",this.props.businessRule);
if (this.props.businessRule) {
Object.assign(this.state.form, this.props.businessRule);
this.initialiseFormFields();
}
}
componentDidUpdate() {
// console.log("componentDidUpdate", this.sourceId, this.sourceId.selectedIndex)
//let table_name = document.getElementById("sourceId").options[this.state.form.source_id].getAttribute('target');
if (this.state.componentDidUpdateCount == 0 && this.state.form.source_id ) {
let table_name = this.sourceId.options[this.sourceId.selectedIndex].getAttribute('target');
//alert(table_name);
this.props.fetchSourceColumnList(table_name);
//set the value componentDidUpdateCount to 1 to indicate that column list Updated
//no need to call componentDidUpdate again
this.setState({ componentDidUpdateCount: 1 });
}
}
searchAnywhere(textInputValue, possibleSuggestionsArray) {
var lowerCaseQuery = textInputValue.toLowerCase()
return possibleSuggestionsArray.filter(function (suggestion) {
return suggestion.toLowerCase().includes(lowerCaseQuery)
})
}
// handleRuleRefDelete(i) {
// let rulesTags = this.state.rulesTags;
// rulesTags.splice(i, 1);
// this.setState({ rulesTags: rulesTags });
// }
//
// handleRuleRefAddition(tag) {
// let rulesTags = this.state.rulesTags;
// rulesTags.push({
// id: rulesTags.length + 1,
// text: tag
// });
// this.setState({ rulesTags: rulesTags });
// }
//
// handleRuleRefDrag(tag, currPos, newPos) {
// let rulesTags = this.state.rulesTags;
//
// // mutate array
// rulesTags.splice(currPos, 1);
// rulesTags.splice(newPos, 0, tag);
//
// // re-render
// this.setState({ rulesTags: rulesTags });
// }
handleDataFieldsDelete(i) {
let dataFieldsTags = this.state.dataFieldsTags;
dataFieldsTags.splice(i, 1);
this.setState({ dataFieldsTags: dataFieldsTags });
}
handleDataFieldsAddition(tag) {
let dataFieldsTags = this.state.dataFieldsTags;
console.log('inside dataFieldsTags addition 0', dataFieldsTags, this.state.dataFieldsTags);
// check whether its a valid rule to be added
if (this.state.fieldsSuggestions.indexOf(tag) != -1) {
dataFieldsTags.push({
id: dataFieldsTags.length + 1,
text: tag
});
}
else {
alert("Not a valid data field, please check...", tag)
}
this.setState({ dataFieldsTags: dataFieldsTags });
}
handleDataFieldsDrag(tag, currPos, newPos) {
let dataFieldsTags = this.state.dataFieldsTags;
// mutate array
dataFieldsTags.splice(currPos, 1);
dataFieldsTags.splice(newPos, 0, tag);
// re-render
this.setState({ dataFieldsTags: dataFieldsTags });
}
flatenTags() {
// this.state.form.python_implementation = '';
this.state.form.data_fields_list = '';
console.log('inside process', this.state);
// this.state.rulesTags.map(function (item, index) {
// console.log('Inside rulesTags.map....:', item.text);
// this.state.form.python_implementation += `${item.text}`;
// }.bind(this));
this.state.dataFieldsTags.map(function (item, index) {
if (index == 0) {
this.state.form.data_fields_list += `${item.text}`;
}
else {
this.state.form.data_fields_list += `,${item.text}`;
}
}.bind(this));
console.log('inside process form check', this.state.form);
}
initialiseFormFields() {
//this.setState({form: this.props.drill_down_result.cell_rules[this.state.ruleIndex]});
this.state.form = this.props.businessRule;
// if (this.state.rulesTags.length == 0) {
// this.state.rulesTags.push({ id: 1, text: this.state.form.python_implementation });
// }
if (this.state.dataFieldsTags.length == 0) {
const { data_fields_list } = this.state.form;
let dataFieldsTagsArray = data_fields_list ? data_fields_list.split(',') : [];
dataFieldsTagsArray.map((item, index) => {
if (item != '') {
this.state.dataFieldsTags.push({ id: index + 1, text: item });
}
})
}
}
handleRuleAssistClick() {
this.flatenTags();
let formCopy = { ...this.state.form };
// console.log("assist click", this.sourceId.selectedIndex)
let sourceTable = {
source_id: formCopy.source_id,
source_table_name: this.sourceId.options[this.sourceId.selectedIndex].getAttribute('target')
}
this.setState({
showRuleAssist: true,
ruleAssistProps: {
rule: formCopy,
sourceTable: sourceTable
}
});
console.log('State Saved',this.state.ruleAssistProps);
}
render() {
this.state.fieldsSuggestions = [];
this.state.dataFieldsSuggestions = [];
const { rulesTags, dataFieldsTags, fieldsSuggestions, dataFieldsSuggestions } = this.state;
if (typeof (this.props.source_table_columns) != 'undefined') {
if (this.props.source_table_columns.length) {
const columns_suggestion = this.props.source_table_columns;
console.log('columns_suggestion', columns_suggestion);
columns_suggestion.map(function (item, index) {
this.state.fieldsSuggestions.push(item.Field);
}.bind(this));
}
if (dataFieldsTags.length) {
dataFieldsTags.map(function (item, index) {
this.state.dataFieldsSuggestions.push(item.text);
}.bind(this));
}
}
if (typeof (this.props.sources) == 'undefined') {
return (
<h1>Loading...</h1>
)
}
else if (this.state.showRuleAssist) {
console.log("Rule assists", this.props.editable);
return (
<RuleAssist
rule={this.state.ruleAssistProps.rule}
sourceTable={this.state.ruleAssistProps.sourceTable}
editable={ !this.state.readOnly }
cancelEditing={() => {
this.setState({ showRuleAssist: false });
}}
handleSaveEditing={this.handleSaveEditing.bind(this)}
handleClose={() => {
this.setState({ showRuleAssist: false });
}}
/>
);
}
else {
const { source_suggestion } = this.props.sources;
// if(typeof(this.state.ruleIndex) != 'undefined'){
// console.log('inside initialiseFormFields')
// this.initialiseFormFields();
// }
console.log('in render', this.state)
return (
<div className="row">
<div className="x_panel">
<div className="x_title">
<h2>Manage Rule <small> { this.props.businessRule ? "Edit": "Add a new"} rule</small></h2>
<ul className="nav navbar-right panel_toolbox">
<li>
<a className="close-link" onClick={this.props.handleClose}><i className="fa fa-close"></i></a>
</li>
</ul>
<div className="clearfix"></div>
</div>
<div className="x_content">
<br />
<form id="businessRuleForm" className="form-horizontal form-label-left"
onSubmit={this.handleSubmit}
>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">ID <span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input
defaultValue={this.state.form.id}
placeholder="System Reference ID"
readOnly="readonly"
type="text"
className="form-control col-md-7 col-xs-12"
/>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">Business Rule Ref<span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input
placeholder="Enter Business Rule Ref"
value={this.state.form.business_rule}
type="text"
readOnly={this.state.readOnly || this.state.requestType == "update"}
maxLength="10"
required="required"
className="form-control col-md-7 col-xs-12"
onChange={
(event) => {
let newState = { ...this.state };
newState.form.business_rule = event.target.value;
this.setState(newState);
}
}
/>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">Rule Execution Order<span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input
placeholder="Enter Business Rule Execution order"
value={this.state.form.rule_execution_order}
type="text"
readOnly={this.state.readOnly || this.state.requestType == "update"}
maxLength="10"
required="required"
className="form-control col-md-7 col-xs-12"
onChange={
(event) => {
let newState = { ...this.state };
newState.form.rule_execution_order = event.target.value;
this.setState(newState);
}
}
/>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">Business Rule Description<span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<textarea
placeholder="Enter Business Rule Description here..."
value={this.state.form.rule_description}
type="text"
readOnly={this.state.readOnly}
maxLength="300"
required="required"
className="form-control col-md-7 col-xs-12"
onChange={
(event) => {
let newState = { ...this.state };
newState.form.rule_description = event.target.value;
this.setState(newState);
}
}
/>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">Business Rule Logic Description<span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<textarea
placeholder="Enter Business Rule Logic Description here..."
value={this.state.form.logical_condition}
type="text"
readOnly={this.state.readOnly}
maxLength="300"
required="required"
className="form-control col-md-7 col-xs-12"
onChange={
(event) => {
let newState = { ...this.state };
newState.form.logical_condition = event.target.value;
this.setState(newState);
}
}
/>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">Source ID <span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<select
defaultValue={this.state.form.source_id}
required="required"
readOnly={this.state.readOnly}
disabled={this.state.readOnly}
className="form-control"
ref={(select) => { this.sourceId = select; }}
onChange={
(event) => {
let table_name = (event.target.options[event.target.selectedIndex].getAttribute('target'));
let newState = { ...this.state };
console.log('table name in change event', table_name);
newState.form.source_id = event.target.value;
newState.form.python_implementation = null;
newState.form.data_fields_list = null;
newState.dataFieldsTags=[];
newState.selectedSource = {
id: event.target.value,
tableName: table_name,
index: event.target.selectedIndex
}
this.setState(newState);
//Now reset the field python_implementation
document.getElementById("python_implementation").value=null;
this.props.fetchSourceColumnList(table_name);
}
}
>
<option value="">Choose option</option>
{
source_suggestion.map(function (item, index) {
return (
<option key={index} target={item.source_table_name} value={item.source_id}>{item.source_id} - {item.source_table_name}</option>
)
})
}
</select>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">Data Attribute Fields <span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<ReactTags tags={dataFieldsTags}
suggestions={fieldsSuggestions}
readOnly={this.state.readOnly}
handleDelete={this.handleDataFieldsDelete}
handleAddition={this.handleDataFieldsAddition}
handleDrag={this.handleDataFieldsDrag}
handleFilterSuggestions={this.searchAnywhere}
allowDeleteFromEmptyInput={false}
autocomplete={true}
minQueryLength={1}
classNames={{
tagInput: 'tagInputClass',
tagInputField: 'tagInputFieldClass form-control',
suggestions: 'suggestionsClass',
}}
placeholder="Enter List of Attributes required for the rule"
required="required"
/>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">Rule Condition <span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<textarea
id="python_implementation"
placeholder="Enter actual rule logic using selected attributes"
value={ this.state.form.python_implementation }
type="text"
readOnly={this.state.readOnly}
required="required"
className="form-control col-md-7 col-xs-12"
onChange={
(event) => {
// let newState = { ...this.state };
// newState.form.python_implementation = event.target.value;
event.target.value=null;
console.log("this.state.form.python_implementation",this.state.form.python_implementation);
//this.setState(newState);
}
}
/>
</div>
{
!this.state.readOnly &&
<button
type="button"
disabled={ !this.state.dataFieldsTags.length }
onClick={this.handleRuleAssistClick}
className="btn btn-primary btn-xs"
>
Edit
</button>
}
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="rounding-option">Business or Validation Rule<span className="required">*</span></label>
<div className="col-md-3 col-sm-3 col-xs-12">
<select
defaultValue={this.state.form.business_or_validation}
readOnly={this.state.readOnly}
disabled={this.state.readOnly}
className="form-control"
required="required"
onChange={
(event) => {
let newState = { ...this.state };
newState.form.business_or_validation = event.target.value;
this.setState(newState);
}
}
>
<option value="">Choose option</option>
<option key="BUSINESS" value="BUSINESS">BUSINESS</option>
<option key="VALIDATION" value="VALIDATION">VALIDATION</option>
</select>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="rounding-option">Rule Type<span className="required"></span></label>
<div className="col-md-3 col-sm-3 col-xs-12">
<select
defaultValue={this.state.form.rule_type}
readOnly={this.state.readOnly}
disabled={this.state.readOnly}
className="form-control"
onChange={
(event) => {
let newState = { ...this.state };
newState.form.rule_type = event.target.value;
this.setState(newState);
}
}
>
<option value="">Choose option</option>
<option key="DERIVED" value="DERIVED">DERIVED - This is a self reference value check</option>
<option key="USEDATA" value="USEDATA">USEDATA - Rule is evaluated using supplied data</option>
<option key="KEYCOLUMN" value="KEYCOLUMN">KEYCOLUMN - Key attribute of the data source</option>
<option key="BUYCURRENCY" value="BUYCURRENCY">BUYCURRENCY - Buy currency of the position</option>
<option key="SELLCURRENCY" value="SELLCURRENCY">SELLCURRENCY - Sell currency of the position</option>
</select>
</div>
</div>
{
!this.state.readOnly &&
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="Comment">Comment <span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<textarea
type="text"
placeholder="Enter a Comment"
required="required"
className="form-control col-md-7 col-xs-12"
value={this.state.audit_form.comment}
maxLength="1000"
minLength="20"
onChange={
(event) => {
let { audit_form } = this.state;
audit_form.comment = event.target.value;
this.setState({ audit_form });
}
}
/>
</div>
</div>
}
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor="first-name">Last Updated by <span className="required">*</span></label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input
value={ this.state.requestType=="add" ? this.props.login_details.user : this.state.form.last_updated_by }
type="text" required="required"
className="form-control col-md-7 col-xs-12"
readOnly="readonly" />
</div>
</div>
<div className="form-group">
<div className="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<button type="button" className="btn btn-primary" onClick={ this.props.handleCancel }>
Cancel</button>
{
!this.state.readOnly &&
<button type="submit" className="btn btn-success" >Submit</button>
}
</div>
</div>
</form>
</div>
</div>
</div>
)
}
}
handleSaveEditing(currentFormula){
console.log('inside saveEditing');
let formCopy = { ...this.state.form };
formCopy.python_implementation = currentFormula;
this.setState({ showRuleAssist: false, form: formCopy });
}
handleSubmit(event) {
console.log('inside submit', this.state.form);
event.preventDefault();
this.flatenTags();
let data = {
table_name: "business_rules",
update_info: this.state.form
};
// add audit info to the data part
data['change_type'] = this.state.requestType == 'add' ? 'INSERT' : 'UPDATE';
let audit_info = {
id: this.state.form.id,
table_name: data.table_name,
change_type: data.change_type,
change_reference: `Rule: ${this.state.form.business_rule} of Source: ${this.state.form.source_id}`,
maker: this.props.login_details.user,
maker_tenant_id: this.props.login_details.domainInfo.tenant_id,
group_id: this.props.groupId,
};
Object.assign(audit_info, this.state.audit_form);
data['audit_info'] = audit_info;
console.log('inside submit', this.state.form);
if (this.state.requestType == "add") {
this.props.insertBusinessRule(data, this.state.ruleIndex);
}
else {
this.props.updateBusinessRule(data);
}
this.props.handleClose(event);
}
}
function mapStateToProps(state) {
console.log("On map state of Add report rule", state);
return {
sources: state.maintain_report_rules_store.sources,
business_rules: state.business_rules,
source_table_columns: state.maintain_report_rules_store.source_table_columns,
login_details: state.login_store,
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchSources: (sourceId) => {
dispatch(actionFetchSources(sourceId));
},
fetchSourceColumnList: (table_name) => {
dispatch(actionFetchSourceColumnList(table_name));
},
insertBusinessRule: (item, at) => {
dispatch(actionInsertBusinessRule(item, at))
},
updateBusinessRule: (item) => {
dispatch(actionUpdateBusinessRule(item))
}
}
}
const VisibleAddBusinessRule = connect(
mapStateToProps,
mapDispatchToProps
)(AddBusinessRule);
export default VisibleAddBusinessRule;
|
client/src/components/Jobs/Jobs.js | jenovs/bears-team-14 | import React, { Component } from 'react';
import { TransitionGroup } from 'react-transition-group';
import FeaturedItems from '../FeaturedItems';
import Search from '../Search';
import { Header, SearchStatus, StyledCSSTransition } from './styled';
import filterData from '../../helpers/filterData';
class Jobs extends Component {
constructor(props) {
super(props);
this.state = {
data: props.data,
filteredData: props.data,
showFoundCount: false,
};
}
componentWillReceiveProps(nextProps) {
this.setState(() => ({
data: nextProps.data,
filteredData: nextProps.data,
}));
}
componentDidUpdate() {
// Trigger lazy loading
window.scrollBy(0, 1);
window.scrollBy(0, -1);
}
filterItems = (key = '') => {
const data = this.state.data;
if (!key.length)
return this.setState(() => ({
filteredData: data,
showFoundCount: false,
}));
const filteredData = filterData(data, key);
this.setState(() => ({
filteredData,
showFoundCount: true,
searchKey: key,
}));
};
render() {
const { filteredData, searchKey, showFoundCount } = this.state;
const { data, ...props } = this.props;
return (
<div>
<Header>Explore jobs</Header>
<Search handleFilter={this.filterItems} />
<TransitionGroup>
{showFoundCount && (
<StyledCSSTransition>
<SearchStatus>
Found {filteredData.length} matches for{' '}
<strong>"{searchKey}"</strong>
</SearchStatus>
</StyledCSSTransition>
)}
</TransitionGroup>
<FeaturedItems data={filteredData} {...props} />
</div>
);
}
}
export default Jobs;
|
src/esm/components/structure/cards/people-card/index.js | KissKissBankBank/kitten | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["className", "children"],
_excluded2 = ["className", "style", "peopleAvatar"],
_excluded3 = ["className", "style"],
_excluded4 = ["className", "style"];
import React from 'react';
import styled from 'styled-components';
import classNames from 'classnames';
import { pxToRem } from '../../../../helpers/utils/typography';
import { mq } from '../../../../constants/screen-config';
import { AvatarWithTextAndBadge } from '../../../information/avatar-with-text-and-badge';
import { PeopleCircleIconNext } from '../../../graphics/icons-next/people-circle-icon-next';
var StyledPeopleCard = styled.article.withConfig({
displayName: "people-card__StyledPeopleCard",
componentId: "sc-an51ay-0"
})(["max-width:100%;position:relative;display:block;box-sizing:border-box;text-decoration:none;background-color:var(--color-grey-000);padding:", "};border:var(--border);border-radius:var(--border-radius-s);display:flex;gap:0 ", ";height:", ";@media ", "{flex-direction:row;gap:0 ", ";}.k-PeopleCard__image{display:flex;align-items:center;}.k-PeopleCard__cell{flex:1 1 auto;}.k-PeopleCard__lastCell{flex:0 0 auto;z-index:2;display:flex;align-items:stretch;justify-content:stretch;margin:", " ", ";.k-DropdownMenu .k-DropdownMenu__button{box-sizing:border-box;display:flex;justify-content:center;align-items:center;height:100%;padding:0 ", ";&:focus-visible .k-DropdownMenu__button__inside{outline:auto;outline-offset:", ";}}}"], pxToRem(15), pxToRem(15), pxToRem(63), mq.mobile, pxToRem(10), pxToRem(-20), pxToRem(-30), pxToRem(30), pxToRem(-2));
export var PeopleCard = function PeopleCard(_ref) {
var _ref$className = _ref.className,
className = _ref$className === void 0 ? '' : _ref$className,
children = _ref.children,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement(StyledPeopleCard, _extends({
className: classNames('k-PeopleCard', className)
}, props), children);
};
PeopleCard.Image = function (_ref2) {
var className = _ref2.className,
style = _ref2.style,
_ref2$peopleAvatar = _ref2.peopleAvatar,
peopleAvatar = _ref2$peopleAvatar === void 0 ? true : _ref2$peopleAvatar,
props = _objectWithoutPropertiesLoose(_ref2, _excluded2);
return /*#__PURE__*/React.createElement("div", _extends({}, props, {
className: classNames('k-PeopleCard__image', className)
}), peopleAvatar ? /*#__PURE__*/React.createElement(AvatarWithTextAndBadge, null, /*#__PURE__*/React.createElement(AvatarWithTextAndBadge.Image, {
alt: "",
size: "small",
src: "/kitten-0.jpg"
})) : /*#__PURE__*/React.createElement(PeopleCircleIconNext, null));
};
PeopleCard.Cell = function (_ref3) {
var className = _ref3.className,
style = _ref3.style,
props = _objectWithoutPropertiesLoose(_ref3, _excluded3);
return /*#__PURE__*/React.createElement("div", _extends({}, props, {
className: classNames('k-PeopleCard__cell', className)
}));
};
PeopleCard.LastCell = function (_ref4) {
var className = _ref4.className,
style = _ref4.style,
props = _objectWithoutPropertiesLoose(_ref4, _excluded4);
return /*#__PURE__*/React.createElement("div", _extends({}, props, {
className: classNames('k-PeopleCard__lastCell', className)
}));
}; |
ajax/libs/redux-form/1.4.1/redux-form.js | emmy41124/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReduxForm"] = factory(require("react"));
else
root["ReduxForm"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_13__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 _reducer = __webpack_require__(5);
var _reducer2 = _interopRequireDefault(_reducer);
var _reduxForm = __webpack_require__(6);
var _reduxForm2 = _interopRequireDefault(_reduxForm);
var _connectReduxForm = __webpack_require__(14);
var _connectReduxForm2 = _interopRequireDefault(_connectReduxForm);
var _mapValues = __webpack_require__(1);
var _mapValues2 = _interopRequireDefault(_mapValues);
var _bindActionData = __webpack_require__(4);
var _bindActionData2 = _interopRequireDefault(_bindActionData);
var _actions = __webpack_require__(3);
var actions = _interopRequireWildcard(_actions);
// bind form as first parameter of action creators
var boundActions = _extends({}, _mapValues2['default'](_extends({}, actions, {
initializeWithKey: function initializeWithKey(key, data) {
return _bindActionData2['default'](actions.initialize, { key: key })(data);
}
}), function (action) {
return function (form) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return _bindActionData2['default'](action, { form: form }).apply(undefined, args);
};
}));
var blur = boundActions.blur;
var change = boundActions.change;
var initialize = boundActions.initialize;
var initializeWithKey = boundActions.initializeWithKey;
var reset = boundActions.reset;
var startAsyncValidation = boundActions.startAsyncValidation;
var stopAsyncValidation = boundActions.stopAsyncValidation;
var touch = boundActions.touch;
var untouch = boundActions.untouch;
exports.blur = blur;
exports.change = change;
exports.connectReduxForm = _connectReduxForm2['default'];
exports.reducer = _reducer2['default'];
exports.initialize = initialize;
exports.initializeWithKey = initializeWithKey;
exports.reset = reset;
exports.startAsyncValidation = startAsyncValidation;
exports.stopAsyncValidation = stopAsyncValidation;
exports.touch = touch;
exports.untouch = untouch;
exports['default'] = _reduxForm2['default'];
/***/ },
/* 1 */
/***/ function(module, exports) {
/**
* Maps all the values in the given object through the given function and saves them, by key, to a result object
*/
"use strict";
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports["default"] = mapValues;
function mapValues(obj, fn) {
return Object.keys(obj).reduce(function (accumulator, key) {
var _extends2;
return _extends({}, accumulator, (_extends2 = {}, _extends2[key] = fn(obj[key], key), _extends2));
}, {});
}
module.exports = exports["default"];
/***/ },
/* 2 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var BLUR = 'redux-form/BLUR';
exports.BLUR = BLUR;
var CHANGE = 'redux-form/CHANGE';
exports.CHANGE = CHANGE;
var FOCUS = 'redux-form/FOCUS';
exports.FOCUS = FOCUS;
var INITIALIZE = 'redux-form/INITIALIZE';
exports.INITIALIZE = INITIALIZE;
var RESET = 'redux-form/RESET';
exports.RESET = RESET;
var START_ASYNC_VALIDATION = 'redux-form/START_ASYNC_VALIDATION';
exports.START_ASYNC_VALIDATION = START_ASYNC_VALIDATION;
var START_SUBMIT = 'redux-form/START_SUBMIT';
exports.START_SUBMIT = START_SUBMIT;
var STOP_ASYNC_VALIDATION = 'redux-form/STOP_ASYNC_VALIDATION';
exports.STOP_ASYNC_VALIDATION = STOP_ASYNC_VALIDATION;
var STOP_SUBMIT = 'redux-form/STOP_SUBMIT';
exports.STOP_SUBMIT = STOP_SUBMIT;
var TOUCH = 'redux-form/TOUCH';
exports.TOUCH = TOUCH;
var UNTOUCH = 'redux-form/UNTOUCH';
exports.UNTOUCH = UNTOUCH;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.blur = blur;
exports.change = change;
exports.focus = focus;
exports.initialize = initialize;
exports.reset = reset;
exports.startAsyncValidation = startAsyncValidation;
exports.startSubmit = startSubmit;
exports.stopAsyncValidation = stopAsyncValidation;
exports.stopSubmit = stopSubmit;
exports.touch = touch;
exports.untouch = untouch;
var _actionTypes = __webpack_require__(2);
function blur(field, value) {
return { type: _actionTypes.BLUR, field: field, value: value };
}
function change(field, value) {
return { type: _actionTypes.CHANGE, field: field, value: value };
}
function focus(field) {
return { type: _actionTypes.FOCUS, field: field };
}
function initialize(data) {
return { type: _actionTypes.INITIALIZE, data: data };
}
function reset() {
return { type: _actionTypes.RESET };
}
function startAsyncValidation() {
return { type: _actionTypes.START_ASYNC_VALIDATION };
}
function startSubmit() {
return { type: _actionTypes.START_SUBMIT };
}
function stopAsyncValidation(errors) {
return { type: _actionTypes.STOP_ASYNC_VALIDATION, errors: errors };
}
function stopSubmit() {
return { type: _actionTypes.STOP_SUBMIT };
}
function touch() {
for (var _len = arguments.length, fields = Array(_len), _key = 0; _key < _len; _key++) {
fields[_key] = arguments[_key];
}
return { type: _actionTypes.TOUCH, fields: fields };
}
function untouch() {
for (var _len2 = arguments.length, fields = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
fields[_key2] = arguments[_key2];
}
return { type: _actionTypes.UNTOUCH, fields: fields };
}
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = bindActionData;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _mapValues = __webpack_require__(1);
var _mapValues2 = _interopRequireDefault(_mapValues);
/**
* Adds additional properties to the results of the function or map of functions passed
*/
function bindActionData(action, data) {
if (typeof action === 'function') {
return function () {
return _extends({}, action.apply(undefined, arguments), data);
};
}
if (typeof action === 'object') {
return _mapValues2['default'](action, function (value) {
return bindActionData(value, data);
});
}
return action;
}
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _actionTypes = __webpack_require__(2);
var _mapValues = __webpack_require__(1);
var _mapValues2 = _interopRequireDefault(_mapValues);
var initialState = {
_asyncValidating: false,
_submitting: false,
_active: undefined
};
exports.initialState = initialState;
var getValues = function getValues(state) {
return Object.keys(state).reduce(function (accumulator, name) {
var _extends2;
return name[0] === '_' ? accumulator : _extends({}, accumulator, (_extends2 = {}, _extends2[name] = state[name].value, _extends2));
}, {});
};
var reducer = function reducer() {
var state = arguments.length <= 0 || arguments[0] === undefined ? initialState : arguments[0];
var _extends3, _extends4, _extends5;
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
switch (action.type) {
case _actionTypes.BLUR:
return _extends({}, state, (_extends3 = {}, _extends3[action.field] = _extends({}, state[action.field], {
value: action.value,
touched: !!(action.touch || (state[action.field] || {}).touched)
}), _extends3._active = undefined, _extends3));
case _actionTypes.CHANGE:
return _extends({}, state, (_extends4 = {}, _extends4[action.field] = _extends({}, state[action.field], {
value: action.value,
touched: !!(action.touch || (state[action.field] || {}).touched),
asyncError: null
}), _extends4));
case _actionTypes.FOCUS:
return _extends({}, state, (_extends5 = {}, _extends5[action.field] = _extends({}, state[action.field], {
visited: true
}), _extends5._active = action.field, _extends5));
case _actionTypes.INITIALIZE:
return _extends({}, _mapValues2['default'](action.data, function (value) {
return {
initial: value,
value: value
};
}), {
_asyncValidating: false,
_submitting: false,
_active: undefined
});
case _actionTypes.RESET:
return _extends({}, _mapValues2['default'](state, function (field, name) {
return name[0] === '_' ? field : {
initial: field.initial,
value: field.initial
};
}), {
_active: undefined,
_asyncValidating: false,
_submitting: false
});
case _actionTypes.START_ASYNC_VALIDATION:
return _extends({}, state, {
_asyncValidating: true
});
case _actionTypes.START_SUBMIT:
return _extends({}, state, {
_submitting: true
});
case _actionTypes.STOP_ASYNC_VALIDATION:
return _extends({}, state, _mapValues2['default'](action.errors, function (error, key) {
return _extends({}, state[key], {
asyncError: error
});
}), {
_asyncValidating: false
});
case _actionTypes.STOP_SUBMIT:
return _extends({}, state, {
_submitting: false
});
case _actionTypes.TOUCH:
return _extends({}, state, action.fields.reduce(function (accumulator, field) {
var _extends6;
return _extends({}, accumulator, (_extends6 = {}, _extends6[field] = _extends({}, state[field], {
touched: true
}), _extends6));
}, {}));
case _actionTypes.UNTOUCH:
return _extends({}, state, action.fields.reduce(function (accumulator, field) {
var _extends7;
return _extends({}, accumulator, (_extends7 = {}, _extends7[field] = _extends({}, state[field], {
touched: false
}), _extends7));
}, {}));
default:
return state;
}
};
function formReducer() {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _extends10;
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var form = action.form;
var key = action.key;
var rest = _objectWithoutProperties(action, ['form', 'key']);
if (!form) {
return state;
}
if (key) {
var _extends8, _extends9;
return _extends({}, state, (_extends9 = {}, _extends9[form] = _extends({}, state[form], (_extends8 = {}, _extends8[key] = reducer((state[form] || {})[key], rest), _extends8)), _extends9));
}
return _extends({}, state, (_extends10 = {}, _extends10[form] = reducer(state[form], rest), _extends10));
}
/**
* Adds additional functionality to the reducer
*/
function decorate(target) {
target.plugin = function plugin(reducers) {
var _this = this;
return decorate(function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var result = _this(state, action);
return _extends({}, result, _mapValues2['default'](reducers, function (red, key) {
return red(result[key] || initialState, action);
}));
});
};
target.normalize = function normalize(normalizers) {
var _this2 = this;
return decorate(function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var result = _this2(state, action);
return _extends({}, result, _mapValues2['default'](normalizers, function (formNormalizers, form) {
return _extends({}, result[form], _mapValues2['default'](formNormalizers, function (fieldNormalizer, field) {
return _extends({}, result[form][field], {
value: fieldNormalizer(result[form][field] ? result[form][field].value : undefined, // value
state[form] && state[form][field] ? state[form][field].value : undefined, // previous value
getValues(result[form])) // all field values
});
}));
}));
});
};
return target;
}
exports['default'] = decorate(formReducer);
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = reduxForm;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(13);
var _react2 = _interopRequireDefault(_react);
var _actions = __webpack_require__(3);
var formActions = _interopRequireWildcard(_actions);
var _getDisplayName = __webpack_require__(15);
var _getDisplayName2 = _interopRequireDefault(_getDisplayName);
var _isPristine = __webpack_require__(16);
var _isPristine2 = _interopRequireDefault(_isPristine);
var _isValid = __webpack_require__(17);
var _isValid2 = _interopRequireDefault(_isValid);
var _bindActionData = __webpack_require__(4);
var _bindActionData2 = _interopRequireDefault(_bindActionData);
var _reducer = __webpack_require__(5);
function isReadonly(prop) {
var writeProps = ['asyncValidate', 'handleBlur', 'handleChange', 'handleFocus', 'handleSubmit', 'onBlur', 'onChange', 'onFocus'];
return ! ~writeProps.indexOf(prop);
}
function getSubForm(form, formName, formKey) {
if (form && form[formName]) {
if (formKey) {
if (form[formName][formKey]) {
return form[formName][formKey];
}
} else {
return form[formName];
}
}
return _reducer.initialState;
}
function getValue(passedValue, event) {
if (passedValue !== undefined || !event) {
return passedValue;
}
if (event.target === undefined) {
// is it a value instead of an event?
return event;
}
var _event$target = event.target;
var type = _event$target.type;
var value = _event$target.value;
var checked = _event$target.checked;
if (type === 'checkbox') {
return checked;
}
return value;
}
function silenceEvents(fn) {
return function (event) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (event && event.preventDefault) {
event.preventDefault();
event.stopPropagation();
return fn.apply(undefined, args);
}
return fn.apply(undefined, [event].concat(args));
};
}
function isAsyncValid(errors) {
if (!errors) {
return true;
}
if (errors.valid === undefined) {
return !Object.keys(errors);
}
return !!errors.valid;
}
function reduxForm(config) {
var _extends6 = _extends({
validate: function validate() {
return {};
},
touchOnBlur: true,
touchOnChange: false,
readonly: false,
asyncValidate: null,
asyncBlurFields: []
}, config);
var formName = _extends6.form;
var fields = _extends6.fields;
var syncValidate = _extends6.validate;
var readonly = _extends6.readonly;
var touchOnBlur = _extends6.touchOnBlur;
var touchOnChange = _extends6.touchOnChange;
var asyncValidate = _extends6.asyncValidate;
var asyncBlurFields = _extends6.asyncBlurFields;
if (!fields || !fields.length) {
throw new Error('No fields passed to redux-form. Must be passed to ' + 'connectReduxForm({fields: ["my", "field", "names"]})');
}
var filterProps = function filterProps(props) {
return readonly ? Object.keys(props).reduce(function (accumulator, prop) {
var _extends2;
return isReadonly(prop) ? _extends({}, accumulator, (_extends2 = {}, _extends2[prop] = props[prop], _extends2)) : accumulator;
}, {}) : props;
};
return function (DecoratedComponent) {
return (function (_Component) {
_inherits(ReduxForm, _Component);
function ReduxForm() {
_classCallCheck(this, ReduxForm);
_Component.apply(this, arguments);
}
ReduxForm.prototype.componentWillMount = function componentWillMount() {
var _props = this.props;
var initialValues = _props.initialValues;
var dispatch = _props.dispatch;
var formName = _props.formName;
var formKey = _props.formKey;
// eslint-disable-line no-shadow
if (initialValues) {
var _ref = formKey ? _bindActionData2['default'](formActions, { form: formName, key: formKey }) : _bindActionData2['default'](formActions, { form: formName });
var initialize = _ref.initialize;
dispatch(initialize(initialValues));
}
};
ReduxForm.prototype.render = function render() {
var _this = this;
// Read props
var _props2 = this.props;
var formName = _props2.formName;
var form = _props2.form;
var formKey = _props2.formKey;
var dispatch = _props2.dispatch;
var passableProps = _objectWithoutProperties(_props2, ['formName', 'form', 'formKey', 'dispatch']);
// eslint-disable-line no-shadow
if (!formName) {
throw new Error('No form name given to redux-form. Must be passed to ' + 'connectReduxForm({form: [form name]}) or as a "formName" prop');
}
var subForm = getSubForm(form, formName, formKey);
// Calculate calculable state
var allValid = true;
var allPristine = true;
var values = fields.reduce(function (accumulator, field) {
var _extends3;
return _extends({}, accumulator, (_extends3 = {}, _extends3[field] = subForm[field] ? subForm[field].value : undefined, _extends3));
}, {});
// Create actions
var _ref2 = formKey ? _bindActionData2['default'](formActions, { form: formName, key: formKey }) : _bindActionData2['default'](formActions, { form: formName });
var blur = _ref2.blur;
var change = _ref2.change;
var focus = _ref2.focus;
var initialize = _ref2.initialize;
var reset = _ref2.reset;
var startAsyncValidation = _ref2.startAsyncValidation;
var startSubmit = _ref2.startSubmit;
var stopAsyncValidation = _ref2.stopAsyncValidation;
var stopSubmit = _ref2.stopSubmit;
var touch = _ref2.touch;
var untouch = _ref2.untouch;
function runAsyncValidation() {
dispatch(startAsyncValidation(formKey));
var promise = asyncValidate(values);
if (!promise || typeof promise.then !== 'function') {
throw new Error('asyncValidate function passed to reduxForm must return a promise!');
}
return promise.then(function (asyncErrors) {
dispatch(stopAsyncValidation(asyncErrors));
return isAsyncValid(asyncErrors);
}, function (err) {
dispatch(stopAsyncValidation({}));
throw new Error('redux-form: Asynchronous validation failed: ' + err);
});
}
var handleBlur = function handleBlur(name, value) {
return function (event) {
var fieldValue = getValue(value, event);
var doBlur = _bindActionData2['default'](blur, { touch: touchOnBlur });
dispatch(doBlur(name, fieldValue));
if (asyncValidate && ~asyncBlurFields.indexOf(name)) {
var _extends4;
var syncError = syncValidate(_extends({}, values, (_extends4 = {}, _extends4[name] = fieldValue, _extends4)))[name];
// only dispatch async call if all synchronous client-side validation passes for this field
if (!syncError) {
runAsyncValidation();
}
}
};
};
var handleFocus = function handleFocus(name) {
return function () {
dispatch(focus(name));
};
};
var handleChange = function handleChange(name, value) {
return function (event) {
var doChange = _bindActionData2['default'](change, { touch: touchOnChange });
dispatch(doChange(name, getValue(value, event)));
};
};
var handleSubmit = function handleSubmit(submitOrEvent) {
var createEventHandler = function createEventHandler(submit) {
return function (event) {
if (event && event.preventDefault) {
event.preventDefault();
event.stopPropagation();
}
var submitWithPromiseCheck = function submitWithPromiseCheck() {
var result = submit(values);
if (result && typeof result.then === 'function') {
// you're showing real promise, kid!
var stopAndReturn = function stopAndReturn(x) {
dispatch(stopSubmit());
return x;
};
dispatch(startSubmit());
result.then(stopAndReturn, stopAndReturn);
}
};
dispatch(touch.apply(undefined, fields));
if (allValid) {
if (asyncValidate) {
return runAsyncValidation().then(function (asyncValid) {
if (allValid && asyncValid) {
return submitWithPromiseCheck(values);
}
});
}
return submitWithPromiseCheck(values);
}
};
};
if (typeof submitOrEvent === 'function') {
return createEventHandler(submitOrEvent);
}
var onSubmit = _this.props.onSubmit;
if (!onSubmit) {
throw new Error('You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop');
}
createEventHandler(onSubmit)(submitOrEvent /* is event */);
};
// Define fields
var syncErrors = syncValidate(values);
var allFields = fields.reduce(function (accumulator, name) {
var _extends5;
var field = subForm[name] || {};
var pristine = _isPristine2['default'](field.value, field.initial);
var error = syncErrors[name] || field.asyncError;
var valid = _isValid2['default'](error);
if (!valid) {
allValid = false;
}
if (!pristine) {
allPristine = false;
}
return _extends({}, accumulator, (_extends5 = {}, _extends5[name] = filterProps({
active: subForm._active === name,
checked: typeof field.value === 'boolean' ? field.value : undefined,
dirty: !pristine,
error: error,
handleBlur: handleBlur(name),
handleChange: handleChange(name),
handleFocus: handleFocus(name),
invalid: !valid,
name: name,
onBlur: handleBlur(name),
onChange: handleChange(name),
onFocus: handleFocus(name),
pristine: pristine,
touched: field.touched,
valid: valid,
value: field.value,
visited: field.visited
}), _extends5));
}, {});
// Return decorated component
return _react2['default'].createElement(DecoratedComponent, _extends({
// State:
active: subForm._active,
asyncValidating: subForm._asyncValidating,
dirty: !allPristine,
fields: allFields,
formKey: formKey,
invalid: !allValid,
pristine: allPristine,
submitting: subForm._submitting,
valid: allValid,
values: values,
// Actions:
asyncValidate: silenceEvents(runAsyncValidation),
handleBlur: silenceEvents(handleBlur),
handleChange: silenceEvents(handleChange),
handleFocus: handleFocus,
handleSubmit: silenceEvents(handleSubmit),
initializeForm: silenceEvents(function (initialValues) {
return dispatch(initialize(initialValues));
}),
resetForm: silenceEvents(function () {
return dispatch(reset());
}),
touch: silenceEvents(function () {
return dispatch(touch.apply(undefined, arguments));
}),
touchAll: silenceEvents(function () {
return dispatch(touch.apply(undefined, fields));
}),
untouch: silenceEvents(function () {
return dispatch(untouch.apply(undefined, arguments));
}),
untouchAll: silenceEvents(function () {
return dispatch(untouchAll.apply(undefined, fields));
}),
// Other:
dispatch: dispatch
}, passableProps));
};
_createClass(ReduxForm, null, [{
key: 'displayName',
value: 'ReduxForm(' + _getDisplayName2['default'](DecoratedComponent) + ')',
enumerable: true
}, {
key: 'DecoratedComponent',
value: DecoratedComponent,
enumerable: true
}, {
key: 'propTypes',
value: {
formName: _react.PropTypes.string,
formKey: _react.PropTypes.string,
form: _react.PropTypes.object,
onSubmit: _react.PropTypes.func,
dispatch: _react.PropTypes.func.isRequired,
initialValues: _react.PropTypes.object
},
enumerable: true
}, {
key: 'defaultProps',
value: {
formName: formName
},
enumerable: true
}]);
return ReduxForm;
})(_react.Component);
};
}
module.exports = exports['default'];
/***/ },
/* 7 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = createStoreShape;
function createStoreShape(PropTypes) {
return PropTypes.shape({
subscribe: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired
});
}
module.exports = exports["default"];
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = createStore;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _utilsIsPlainObject = __webpack_require__(10);
var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);
/**
* These are private action types reserved by Redux.
* For any unknown actions, you must return the current state.
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
var ActionTypes = {
INIT: '@@redux/INIT'
};
exports.ActionTypes = ActionTypes;
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [initialState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
function createStore(reducer, initialState) {
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.');
}
var currentReducer = reducer;
var currentState = initialState;
var listeners = [];
var isDispatching = false;
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
var index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action) {
if (!_utilsIsPlainObject2['default'](action)) {
throw new Error('Actions must be plain objects. Use custom middleware for async actions.');
}
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
listeners.slice().forEach(function (listener) {
return listener();
});
return action;
}
/**
* Returns the reducer currently used by the store to calculate the state.
*
* It is likely that you will only need this function if you implement a hot
* reloading mechanism for Redux.
*
* @returns {Function} The reducer used by the current store.
*/
function getReducer() {
return currentReducer;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer) {
currentReducer = nextReducer;
dispatch({ type: ActionTypes.INIT });
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT });
return {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
getReducer: getReducer,
replaceReducer: replaceReducer
};
}
/***/ },
/* 9 */
/***/ function(module, exports) {
/**
* Composes functions from left to right.
*
* @param {...Function} funcs - The functions to compose. Each is expected to
* accept a function as an argument and to return a function.
* @returns {Function} A function obtained by composing functions from left to
* right.
*/
"use strict";
exports.__esModule = true;
exports["default"] = compose;
function compose() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return funcs.reduceRight(function (composed, f) {
return f(composed);
});
}
module.exports = exports["default"];
/***/ },
/* 10 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = isPlainObject;
var fnToString = function fnToString(fn) {
return Function.prototype.toString.call(fn);
};
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype;
if (proto === null) {
return true;
}
var constructor = proto.constructor;
return typeof constructor === 'function' && constructor instanceof constructor && fnToString(constructor) === fnToString(Object);
}
module.exports = exports['default'];
/***/ },
/* 11 */
/***/ function(module, exports) {
/**
* Applies a function to every key-value pair inside an object.
*
* @param {Object} obj The source object.
* @param {Function} fn The mapper function taht receives the value and the key.
* @returns {Object} A new object that contains the mapped values for the keys.
*/
"use strict";
exports.__esModule = true;
exports["default"] = mapValues;
function mapValues(obj, fn) {
return Object.keys(obj).reduce(function (result, key) {
result[key] = fn(obj[key], key);
return result;
}, {});
}
module.exports = exports["default"];
/***/ },
/* 12 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
currentQueue[queueIndex].run();
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 13 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_13__;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = connectReduxForm;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _reactRedux = __webpack_require__(21);
var _reduxForm = __webpack_require__(6);
var _reduxForm2 = _interopRequireDefault(_reduxForm);
var connector = _reactRedux.connect(function (state) {
return {
form: state.form
};
});
function reduceDecorators() {
for (var _len = arguments.length, decorators = Array(_len), _key = 0; _key < _len; _key++) {
decorators[_key] = arguments[_key];
}
return function (DecoratedComponent) {
return decorators.reduce(function (accumulator, decorator) {
return decorator(accumulator);
}, DecoratedComponent);
};
}
function connectReduxForm() {
return reduceDecorators(_reduxForm2['default'].apply(undefined, arguments), connector);
}
module.exports = exports['default'];
/***/ },
/* 15 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = getDisplayName;
function getDisplayName(Comp) {
return Comp.displayName || Comp.name || 'Component';
}
module.exports = exports['default'];
/***/ },
/* 16 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = isPristine;
function isPristine(initial, data) {
if (initial === data) {
return true;
}
if (initial && typeof initial === 'object') {
if (!data || typeof data !== 'object') {
return false;
}
var dataKeys = Object.keys(data);
for (var i = 0; i < dataKeys.length; i++) {
var key = dataKeys[i];
if (!isPristine(initial[key], data[key])) {
return false;
}
}
} else if (initial || data) {
// allow '' to equate to undefined or null
return initial === data;
}
return true;
}
module.exports = exports['default'];
/***/ },
/* 17 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = isValid;
function isValid(error) {
if (!Array.isArray(error)) {
return !error;
}
return error.reduce(function (valid, errorValue) {
return valid && !errorValue;
}, true);
}
module.exports = exports["default"];
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = createAll;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createProvider = __webpack_require__(20);
var _createProvider2 = _interopRequireDefault(_createProvider);
var _createConnect = __webpack_require__(19);
var _createConnect2 = _interopRequireDefault(_createConnect);
function createAll(React) {
var Provider = _createProvider2['default'](React);
var connect = _createConnect2['default'](React);
return { Provider: Provider, connect: connect };
}
module.exports = exports['default'];
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
exports.__esModule = true;
var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = createConnect;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _utilsCreateStoreShape = __webpack_require__(7);
var _utilsCreateStoreShape2 = _interopRequireDefault(_utilsCreateStoreShape);
var _utilsShallowEqual = __webpack_require__(23);
var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual);
var _utilsIsPlainObject = __webpack_require__(22);
var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);
var _utilsWrapActionCreators = __webpack_require__(24);
var _utilsWrapActionCreators2 = _interopRequireDefault(_utilsWrapActionCreators);
var _invariant = __webpack_require__(25);
var _invariant2 = _interopRequireDefault(_invariant);
var defaultMapStateToProps = function defaultMapStateToProps() {
return {};
};
var defaultMapDispatchToProps = function defaultMapDispatchToProps(dispatch) {
return { dispatch: dispatch };
};
var defaultMergeProps = function defaultMergeProps(stateProps, dispatchProps, parentProps) {
return _extends({}, parentProps, stateProps, dispatchProps);
};
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
// Helps track hot reloading.
var nextVersion = 0;
function createConnect(React) {
var Component = React.Component;
var PropTypes = React.PropTypes;
var storeShape = _utilsCreateStoreShape2['default'](PropTypes);
return function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
var shouldSubscribe = Boolean(mapStateToProps);
var finalMapStateToProps = mapStateToProps || defaultMapStateToProps;
var finalMapDispatchToProps = _utilsIsPlainObject2['default'](mapDispatchToProps) ? _utilsWrapActionCreators2['default'](mapDispatchToProps) : mapDispatchToProps || defaultMapDispatchToProps;
var finalMergeProps = mergeProps || defaultMergeProps;
var shouldUpdateStateProps = finalMapStateToProps.length > 1;
var shouldUpdateDispatchProps = finalMapDispatchToProps.length > 1;
// Helps track hot reloading.
var version = nextVersion++;
function computeStateProps(store, props) {
var state = store.getState();
var stateProps = shouldUpdateStateProps ? finalMapStateToProps(state, props) : finalMapStateToProps(state);
_invariant2['default'](_utilsIsPlainObject2['default'](stateProps), '`mapStateToProps` must return an object. Instead received %s.', stateProps);
return stateProps;
}
function computeDispatchProps(store, props) {
var dispatch = store.dispatch;
var dispatchProps = shouldUpdateDispatchProps ? finalMapDispatchToProps(dispatch, props) : finalMapDispatchToProps(dispatch);
_invariant2['default'](_utilsIsPlainObject2['default'](dispatchProps), '`mapDispatchToProps` must return an object. Instead received %s.', dispatchProps);
return dispatchProps;
}
function _computeNextState(stateProps, dispatchProps, parentProps) {
var mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps);
_invariant2['default'](_utilsIsPlainObject2['default'](mergedProps), '`mergeProps` must return an object. Instead received %s.', mergedProps);
return mergedProps;
}
return function wrapWithConnect(WrappedComponent) {
var Connect = (function (_Component) {
_inherits(Connect, _Component);
Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
return !_utilsShallowEqual2['default'](this.state.props, nextState.props);
};
_createClass(Connect, null, [{
key: 'displayName',
value: 'Connect(' + getDisplayName(WrappedComponent) + ')',
enumerable: true
}, {
key: 'WrappedComponent',
value: WrappedComponent,
enumerable: true
}, {
key: 'contextTypes',
value: {
store: storeShape
},
enumerable: true
}, {
key: 'propTypes',
value: {
store: storeShape
},
enumerable: true
}]);
function Connect(props, context) {
_classCallCheck(this, Connect);
_Component.call(this, props, context);
this.version = version;
this.store = props.store || context.store;
_invariant2['default'](this.store, 'Could not find "store" in either the context or ' + ('props of "' + this.constructor.displayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + this.constructor.displayName + '".'));
this.stateProps = computeStateProps(this.store, props);
this.dispatchProps = computeDispatchProps(this.store, props);
this.state = {
props: this.computeNextState()
};
}
Connect.prototype.computeNextState = function computeNextState() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
return _computeNextState(this.stateProps, this.dispatchProps, props);
};
Connect.prototype.updateStateProps = function updateStateProps() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var nextStateProps = computeStateProps(this.store, props);
if (_utilsShallowEqual2['default'](nextStateProps, this.stateProps)) {
return false;
}
this.stateProps = nextStateProps;
return true;
};
Connect.prototype.updateDispatchProps = function updateDispatchProps() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var nextDispatchProps = computeDispatchProps(this.store, props);
if (_utilsShallowEqual2['default'](nextDispatchProps, this.dispatchProps)) {
return false;
}
this.dispatchProps = nextDispatchProps;
return true;
};
Connect.prototype.updateState = function updateState() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var nextState = this.computeNextState(props);
if (!_utilsShallowEqual2['default'](nextState, this.state.props)) {
this.setState({
props: nextState
});
}
};
Connect.prototype.isSubscribed = function isSubscribed() {
return typeof this.unsubscribe === 'function';
};
Connect.prototype.trySubscribe = function trySubscribe() {
if (shouldSubscribe && !this.unsubscribe) {
this.unsubscribe = this.store.subscribe(this.handleChange.bind(this));
this.handleChange();
}
};
Connect.prototype.tryUnsubscribe = function tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
};
Connect.prototype.componentDidMount = function componentDidMount() {
this.trySubscribe();
};
Connect.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (!_utilsShallowEqual2['default'](nextProps, this.props)) {
if (shouldUpdateStateProps) {
this.updateStateProps(nextProps);
}
if (shouldUpdateDispatchProps) {
this.updateDispatchProps(nextProps);
}
this.updateState(nextProps);
}
};
Connect.prototype.componentWillUnmount = function componentWillUnmount() {
this.tryUnsubscribe();
};
Connect.prototype.handleChange = function handleChange() {
if (this.updateStateProps()) {
this.updateState();
}
};
Connect.prototype.getWrappedInstance = function getWrappedInstance() {
return this.refs.wrappedInstance;
};
Connect.prototype.render = function render() {
return React.createElement(WrappedComponent, _extends({ ref: 'wrappedInstance'
}, this.state.props));
};
return Connect;
})(Component);
if (
// Node-like CommonJS environments (Browserify, Webpack)
typeof process !== 'undefined' && typeof process.env !== 'undefined' && ("development") !== 'production' ||
// React Native
typeof __DEV__ !== 'undefined' && __DEV__ //eslint-disable-line no-undef
) {
Connect.prototype.componentWillUpdate = function componentWillUpdate() {
if (this.version === version) {
return;
}
// We are hot reloading!
this.version = version;
// Update the state and bindings.
this.trySubscribe();
this.updateStateProps();
this.updateDispatchProps();
this.updateState();
};
}
return Connect;
};
};
}
module.exports = exports['default'];
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(12)))
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports['default'] = createProvider;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _utilsCreateStoreShape = __webpack_require__(7);
var _utilsCreateStoreShape2 = _interopRequireDefault(_utilsCreateStoreShape);
function isUsingOwnerContext(React) {
var version = React.version;
if (typeof version !== 'string') {
return false;
}
var sections = version.split('.');
var major = parseInt(sections[0], 10);
var minor = parseInt(sections[1], 10);
return major === 0 && minor === 13;
}
function createProvider(React) {
var Component = React.Component;
var PropTypes = React.PropTypes;
var Children = React.Children;
var storeShape = _utilsCreateStoreShape2['default'](PropTypes);
var requireFunctionChild = isUsingOwnerContext(React);
var didWarn = false;
function warnAboutFunction() {
if (didWarn || requireFunctionChild) {
return;
}
didWarn = true;
console.error( // eslint-disable-line no-console
'With React 0.14 and later versions, you no longer need to ' + 'wrap <Provider> child into a function.');
}
function warnAboutElement() {
if (didWarn || !requireFunctionChild) {
return;
}
didWarn = true;
console.error( // eslint-disable-line no-console
'With React 0.13, you need to ' + 'wrap <Provider> child into a function. ' + 'This restriction will be removed with React 0.14.');
}
return (function (_Component) {
_inherits(Provider, _Component);
Provider.prototype.getChildContext = function getChildContext() {
return { store: this.state.store };
};
_createClass(Provider, null, [{
key: 'childContextTypes',
value: {
store: storeShape.isRequired
},
enumerable: true
}, {
key: 'propTypes',
value: {
store: storeShape.isRequired,
children: (requireFunctionChild ? PropTypes.func : PropTypes.element).isRequired
},
enumerable: true
}]);
function Provider(props, context) {
_classCallCheck(this, Provider);
_Component.call(this, props, context);
this.state = { store: props.store };
}
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var store = this.state.store;
var nextStore = nextProps.store;
if (store !== nextStore) {
var nextReducer = nextStore.getReducer();
store.replaceReducer(nextReducer);
}
};
Provider.prototype.render = function render() {
var children = this.props.children;
if (typeof children === 'function') {
warnAboutFunction();
children = children();
} else {
warnAboutElement();
}
return Children.only(children);
};
return Provider;
})(Component);
}
module.exports = exports['default'];
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(13);
var _react2 = _interopRequireDefault(_react);
var _componentsCreateAll = __webpack_require__(18);
var _componentsCreateAll2 = _interopRequireDefault(_componentsCreateAll);
var _createAll = _componentsCreateAll2['default'](_react2['default']);
var Provider = _createAll.Provider;
var connect = _createAll.connect;
exports.Provider = Provider;
exports.connect = connect;
/***/ },
/* 22 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = isPlainObject;
var fnToString = function fnToString(fn) {
return Function.prototype.toString.call(fn);
};
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype;
if (proto === null) {
return true;
}
var constructor = proto.constructor;
return typeof constructor === 'function' && constructor instanceof constructor && fnToString(constructor) === fnToString(Object);
}
module.exports = exports['default'];
/***/ },
/* 23 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = shallowEqual;
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = exports["default"];
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = wrapActionCreators;
var _redux = __webpack_require__(26);
function wrapActionCreators(actionCreators) {
return function (dispatch) {
return _redux.bindActionCreators(actionCreators, dispatch);
};
}
module.exports = exports['default'];
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if (true) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
'Invariant Violation: ' +
format.replace(/%s/g, function() { return args[argIndex++]; })
);
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createStore = __webpack_require__(8);
var _createStore2 = _interopRequireDefault(_createStore);
var _utilsCombineReducers = __webpack_require__(29);
var _utilsCombineReducers2 = _interopRequireDefault(_utilsCombineReducers);
var _utilsBindActionCreators = __webpack_require__(28);
var _utilsBindActionCreators2 = _interopRequireDefault(_utilsBindActionCreators);
var _utilsApplyMiddleware = __webpack_require__(27);
var _utilsApplyMiddleware2 = _interopRequireDefault(_utilsApplyMiddleware);
var _utilsCompose = __webpack_require__(9);
var _utilsCompose2 = _interopRequireDefault(_utilsCompose);
exports.createStore = _createStore2['default'];
exports.combineReducers = _utilsCombineReducers2['default'];
exports.bindActionCreators = _utilsBindActionCreators2['default'];
exports.applyMiddleware = _utilsApplyMiddleware2['default'];
exports.compose = _utilsCompose2['default'];
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = applyMiddleware;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _compose = __webpack_require__(9);
var _compose2 = _interopRequireDefault(_compose);
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
function applyMiddleware() {
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function (next) {
return function (reducer, initialState) {
var store = next(reducer, initialState);
var _dispatch = store.dispatch;
var chain = [];
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch(action) {
return _dispatch(action);
}
};
chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
_dispatch = _compose2['default'].apply(undefined, chain.concat([store.dispatch]));
return _extends({}, store, {
dispatch: _dispatch
});
};
};
}
module.exports = exports['default'];
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = bindActionCreators;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _utilsMapValues = __webpack_require__(11);
var _utilsMapValues2 = _interopRequireDefault(_utilsMapValues);
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(undefined, arguments));
};
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*/
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators == null) {
throw new Error('bindActionCreators expected an object or a function, instead received ' + typeof actionCreators + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
}
return _utilsMapValues2['default'](actionCreators, function (actionCreator) {
return bindActionCreator(actionCreator, dispatch);
});
}
module.exports = exports['default'];
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
exports.__esModule = true;
exports['default'] = combineReducers;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createStore = __webpack_require__(8);
var _utilsIsPlainObject = __webpack_require__(10);
var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);
var _utilsMapValues = __webpack_require__(11);
var _utilsMapValues2 = _interopRequireDefault(_utilsMapValues);
var _utilsPick = __webpack_require__(30);
var _utilsPick2 = _interopRequireDefault(_utilsPick);
function getErrorMessage(key, action) {
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Reducer "' + key + '" returned undefined handling ' + actionName + '. ' + 'To ignore an action, you must explicitly return the previous state.';
}
function verifyStateShape(initialState, currentState) {
var reducerKeys = Object.keys(currentState);
if (reducerKeys.length === 0) {
console.error('Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.');
return;
}
if (!_utilsIsPlainObject2['default'](initialState)) {
console.error('initialState has unexpected type of "' + ({}).toString.call(initialState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected initialState to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'));
return;
}
var unexpectedKeys = Object.keys(initialState).filter(function (key) {
return reducerKeys.indexOf(key) < 0;
});
if (unexpectedKeys.length > 0) {
console.error('Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" in initialState will be ignored. ') + ('Expected to find one of the known reducer keys instead: "' + reducerKeys.join('", "') + '"'));
}
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var finalReducers = _utilsPick2['default'](reducers, function (val) {
return typeof val === 'function';
});
Object.keys(finalReducers).forEach(function (key) {
var reducer = finalReducers[key];
if (typeof reducer(undefined, { type: _createStore.ActionTypes.INIT }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
}
var type = Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
}
});
var defaultState = _utilsMapValues2['default'](finalReducers, function () {
return undefined;
});
var stateShapeVerified;
return function combination(state, action) {
if (state === undefined) state = defaultState;
var finalState = _utilsMapValues2['default'](finalReducers, function (reducer, key) {
var newState = reducer(state[key], action);
if (typeof newState === 'undefined') {
throw new Error(getErrorMessage(key, action));
}
return newState;
});
if (
// Node-like CommonJS environments (Browserify, Webpack)
typeof process !== 'undefined' && typeof process.env !== 'undefined' && ("development") !== 'production' ||
// React Native
typeof __DEV__ !== 'undefined' && __DEV__ //eslint-disable-line no-undef
) {
if (!stateShapeVerified) {
verifyStateShape(state, finalState);
stateShapeVerified = true;
}
}
return finalState;
};
}
module.exports = exports['default'];
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(12)))
/***/ },
/* 30 */
/***/ function(module, exports) {
/**
* Picks key-value pairs from an object where values satisfy a predicate.
*
* @param {Object} obj The object to pick from.
* @param {Function} fn The predicate the values must satisfy to be copied.
* @returns {Object} The object with the values that satisfied the predicate.
*/
"use strict";
exports.__esModule = true;
exports["default"] = pick;
function pick(obj, fn) {
return Object.keys(obj).reduce(function (result, key) {
if (fn(obj[key])) {
result[key] = obj[key];
}
return result;
}, {});
}
module.exports = exports["default"];
/***/ }
/******/ ])
});
; |
test/integration/basic/pages/nav/querystring.js | callumlocke/next.js | import React from 'react'
import Link from 'next/link'
export default class AsyncProps extends React.Component {
static async getInitialProps ({ query: { id = 0 } }) {
return { id }
}
render () {
return (
<div className='nav-querystring'>
<Link href={`/nav/querystring?id=${parseInt(this.props.id) + 1}`}>
<a id='next-id-link'>Click here</a>
</Link>
<Link href='/nav/querystring'>
<a id='main-page'>Click here</a>
</Link>
<p className={`nav-id-${this.props.id}`}>{this.props.id}</p>
</div>
)
}
}
|
webroot/rsrc/externals/javelin/ext/reactor/core/ReactorNode.js | schlaile/phabricator | /**
* @provides javelin-reactornode
* @requires javelin-install
* javelin-reactor
* javelin-util
* javelin-reactor-node-calmer
* @javelin
*/
JX.install('ReactorNode', {
members : {
_transformer : null,
_sendsTo : null,
_nextPulse : null,
_graphID : null,
getGraphID : function() {
return this._graphID || this.__id__;
},
setGraphID : function(id) {
this._graphID = id;
return this;
},
setTransformer : function(fn) {
this._transformer = fn;
return this;
},
/**
* Set up dest as a listener to this.
*/
listen : function(dest) {
this._sendsTo[dest.__id__] = dest;
return { remove : JX.bind(null, this._removeListener, dest) };
},
/**
* Helper for listen.
*/
_removeListener : function(dest) {
delete this._sendsTo[dest.__id__];
},
/**
* For internal use by the Reactor system
*/
primeValue : function(value) {
this._nextPulse = value;
},
getListeners : function() {
var result = [];
for (var k in this._sendsTo) {
result.push(this._sendsTo[k]);
}
return result;
},
/**
* For internal use by the Reactor system
*/
getNextPulse : function() {
return this._nextPulse;
},
getTransformer : function() {
return this._transformer;
},
forceSendValue : function(pulse) {
JX.Reactor.propagatePulse(pulse, this);
},
// fn should return JX.Reactor.DoNotPropagate to indicate a value that
// should not be retransmitted.
transform : function(fn) {
return new JX.ReactorNode([this], fn);
},
/**
* Suppress events to happen at most once per min_interval.
* The last event that fires within an interval will fire at the end
* of the interval. Events that are sandwiched between other events
* within an interval are dropped.
*/
calm : function(min_interval) {
var result = new JX.ReactorNode([this], JX.id);
var transformer = new JX.ReactorNodeCalmer(result, min_interval);
result.setTransformer(JX.bind(transformer, transformer.onPulse));
return result;
}
},
construct : function(source_streams, transformer) {
this._nextPulse = JX.Reactor.DoNotPropagate;
this._transformer = transformer;
this._sendsTo = {};
for (var ix = 0; ix < source_streams.length; ix++) {
source_streams[ix].listen(this);
}
}
});
|
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js | aastey/react-router | /*globals COURSES:true */
import React from 'react'
import { Link } from 'react-router'
class Sidebar extends React.Component {
render() {
let { assignments } = COURSES[this.props.params.courseId]
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
)
}
}
export default Sidebar
|
src/App/App.js | jutaeho/react-map | import React from 'react';
class Maps extends React.Component {
constructor(props) {
super(props);
this.state = {
maps: this.props.data
}
}
render () {
return (
<div className="row">
{this.props.data.map((item, i) => (
<div className="col-xs-6 col-md-4" key={i}>
<div className="thumbnail" key={i}>
<div id={item.name} className="map-canvas" key={i}></div>
<div className="caption">
<div className="input-group">
<input type="text" className="form-control" value={item.name} disabled/>
<span className="input-group-btn">
<button className="btn btn-danger" type="button">Remove</button>
</span>
</div>
</div>
</div>
</div>
))}
</div>
);
}
}
export default class MapCreator extends React.Component {
constructor() {
super();
this.state = {
maps: [],
current: '',
};
this.handleClick = this.handleClick.bind(this);
this.handleAllRemove = this.handleAllRemove.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleClick (e) {
e.preventDefault();
var nitem = {
name: this.state.current,
map: null
};
this.setState((prev) => ({
maps: prev.maps.concat(nitem),
current: ''
}));
setTimeout(() => {
nitem.map = new ol.Map({
target: nitem.name,
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([126.82, 37.41]),
zoom: 7
})
})
}, 500);
}
handleChange (e) {
this.setState({ current: e.target.value });
}
handleRemove (e) {
this.setState((prev) => ({
}));
}
handleAllRemove (e) {
e.preventDefault();
this.setState({
maps: [],
current: ''
});
}
render () {
return (
<div>
<div className="input-group">
<span className="input-group-addon">DOM</span>
<input type="text" className="form-control" placeholder="Enter a name" value={this.state.current} onChange={this.handleChange}/>
<span className="input-group-btn">
<button className="btn btn-primary" type="button" onClick={this.handleClick}>Create</button>
<button className="btn btn-danger" type="button" onClick={this.handleAllRemove}>Remove</button>
</span>
</div>
<hr/>
<Maps data={this.state.maps}/>
</div>
)
}
}
|
components/widgets/charts/LayerChart.js | resource-watch/resource-watch | import React from 'react';
import PropTypes from 'prop-types';
import isEqual from 'lodash/isEqual';
class LayerChart extends React.Component {
constructor(props) {
super(props);
this.state = {
basemap: '',
background: '',
};
}
componentDidMount() {
this.mounted = true;
this.getBasemapPreview();
this.getImagePreview();
}
shouldComponentUpdate(nextProps, nextState) {
return !isEqual(nextProps.data, this.props.data)
|| nextState.background !== this.state.background
|| nextState.basemap !== this.state.basemap;
}
componentWillUnmount() {
this.mounted = false;
}
getSize() {
return {
width: this.chart ? this.chart.offsetWidth : 0,
height: this.chart ? this.chart.offsetHeight : 0,
};
}
getBasemapPreview() {
const basemap = {
account: 'wri-01',
body: {
maxzoom: 18,
minzoom: 3,
layers: [{
type: 'mapnik',
options: {
sql: 'SELECT * FROM gadm28_countries',
cartocss: '#gadm28_countries{ polygon-fill: #bbbbbb; polygon-opacity: 1; line-color: #FFFFFF; line-width: 0.5; line-opacity: 0.5;}',
cartocss_version: '2.3.0',
},
}],
},
};
const layerTpl = {
version: '1.3.0',
stat_tag: 'API',
layers: basemap.body.layers,
};
const params = `?stat_tag=API&config=${encodeURIComponent(JSON.stringify(layerTpl))}`;
const xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', `https://${basemap.account}.carto.com/api/v1/map${params}`);
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200 && this.mounted) {
const response = JSON.parse(xmlhttp.responseText);
const dimensions = this.getSize();
const options = {
token: response.layergroupid,
z: 1,
lat: 0,
lng: 0,
width: dimensions.width,
height: dimensions.height,
format: 'png',
};
this.setState({
basemap: `https://${response.cdn_url.https}/${basemap.account}/api/v1/map/static/center/${options.token}/${options.z}/${options.lat}/${options.lng}/${options.width}/${options.height}.${options.format}`,
});
} else {
console.error('Basemap could not be loaded');
}
}
};
xmlhttp.send(null);
}
getImagePreview() {
const { data } = this.props;
if (!data || !data.account) return;
if (this.mounted) this.props.toggleLoading(true);
const layerTpl = {
version: '1.3.0',
stat_tag: 'API',
layers: data.body.layers,
};
const params = `?stat_tag=API&config=${encodeURIComponent(JSON.stringify(layerTpl))}`;
const xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', `https://${data.account}.carto.com/api/v1/map${params}`);
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState === 4) {
if (this.mounted) this.props.toggleLoading(false);
if (xmlhttp.status === 200 && this.mounted) {
const response = JSON.parse(xmlhttp.responseText);
const dimensions = this.getSize();
const options = {
token: response.layergroupid,
z: 1,
lat: 0,
lng: 0,
width: dimensions.width,
height: dimensions.height,
format: 'png',
};
this.setState({
background: `https://${response.cdn_url.https}/${data.account}/api/v1/map/static/center/${options.token}/${options.z}/${options.lat}/${options.lng}/${options.width}/${options.height}.${options.format}`,
});
} else {
console.error('Basemap could not be loaded');
}
}
};
xmlhttp.send(null);
}
render() {
return (
<div className="c-we-chart">
<div
ref={(c) => { this.chart = c; }}
className="chart"
style={{ backgroundImage: `url('${this.state.background}') , url('${this.state.basemap}')` }}
/>
</div>
);
}
}
LayerChart.propTypes = {
// Define the chart data
data: PropTypes.object,
dimensions: PropTypes.object,
toggleLoading: PropTypes.func,
};
export default LayerChart;
|
src/Heading.js | hcjk/react-pasta | import React from 'react'
import PropTypes from 'prop-types'
import Base from './Base'
import { typeScale } from './BaseStyle'
const Heading = (props) => {
const { level } = props
return (
<Base
{...props}
className={`Heading${level}`}
propertyType={`h${level}`}
baseStyle={{
fontSize: typeScale[level - 1]
}}
/>)
}
Heading.propTypes = {
level: PropTypes.oneOf([1, 2, 3, 4, 5, 6]).isRequired
}
export default Heading
|
views/blocks/Photo/Photo.js | urfu-2016/team5 | import React from 'react';
import './Photo.css';
import b from 'b_';
const photo = b.lock('photo');
function Status(props) {
if (props.userIsCreator || props.status === null) {
return null;
}
return (
<div className={['control', photo('checker')].join(' ')}>
<i className={`fa ${props.status ? 'fa-check' : 'fa-times'}`} area-hidden="true"></i>
</div>
);
}
function Button(props) {
if (props.userIsCreator || props.status) {
return null;
}
return (
<button
className={['control', photo('button')].join(' ')}
disabled={!props.existGeolocation || props.sending}
onClick={props.handleClick}>
<i className={`fa fa-crosshairs ${props.sending ? 'fa-spin' : ''}`} aria-hidden="true"></i>
</button>
);
}
function ShowDescriptionButton(props) {
if (!(props.userIsCreator || props.status) || !props.description) {
return null;
}
return (
<button
className={['control', photo('button')].join(' ')}
onClick={props.handleShowDescription}>
<i className="fa fa-info" aria-hidden="true"></i>
</button>
);
}
export default class Photo extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.handleShowDescription = this.handleShowDescription.bind(this);
this.state = {
showDescription: false
};
}
handleShowDescription() {
this.setState(prevState => ({showDescription: !prevState.showDescription}));
}
handleClick() {
this.props.canSend(canSend => {
if (canSend) {
this.props.onAction();
}
});
}
render() {
const {
existGeolocation,
userIsCreator,
description,
sending,
status,
title,
src
} = this.props;
return (
<div className={photo()}>
<div className={photo('img', {hidden: this.state.showDescription})}>
<Status status={status} userIsCreator={userIsCreator}/>
<Button status={status} existGeolocation={existGeolocation}
userIsCreator={userIsCreator} sending={sending}
handleClick={this.handleClick}
/>
<ShowDescriptionButton status={status}
handleShowDescription={this.handleShowDescription}
userIsCreator={userIsCreator}
description={description}
/>
<img src={src}></img>
{(userIsCreator || status) && title &&
<p className={photo('title')}>
{title}
</p>
}
</div>
{(userIsCreator || status) && description &&
<div className={photo('description', {show: this.state.showDescription})}>
<p>{description}</p>
<button
className={['control', photo('button', {back: true})].join(' ')}
onClick={this.handleShowDescription}>
<i className="fa fa-times" aria-hidden="true"></i>
</button>
</div>
}
</div>
);
}
}
|
__tests__/index.ios.js | TrungSpy/React-Native-SampleProject | import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
sdk-js/browser-forms/jquery-1.11.2.js | wilfoderek/camunda-bpm-examples | /*!
* jQuery JavaScript Library v1.11.2
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-17T15:27Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
version = "1.11.2",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1, IE<9
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( support.ownLast ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1, IE<9
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.0-pre
* http://sizzlejs.com/
*
* Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-16
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
nodeType = context.nodeType;
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
if ( !seed && documentIsHTML ) {
// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType !== 1 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
parent = doc.defaultView;
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Support tests
---------------------------------------------------------------------- */
documentIsHTML = !isXML( doc );
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( doc.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\f]' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
jQuery.fn.extend({
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !(--remaining) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
var strundefined = typeof undefined;
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
// Execute ASAP in case we need to set body.style.zoom
jQuery(function() {
// Minified: var a,b,c,d
var val, div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
if ( val ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
});
(function() {
var div = document.createElement( "div" );
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute("classid") === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
// Minified: var a,b,c
var input = document.createElement( "input" ),
div = document.createElement( "div" ),
fragment = document.createDocumentFragment();
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
})();
(function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
for ( i in { submit: true, change: true, focusin: true }) {
eventName = "on" + i;
if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: IE < 9, Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!support.noCloneEvent || !support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
deletedIds.push( id );
}
}
}
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
(function() {
var shrinkWrapBlocksVal;
support.shrinkWrapBlocks = function() {
if ( shrinkWrapBlocksVal != null ) {
return shrinkWrapBlocksVal;
}
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
// Minified: var b,c,d
var div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
// Support: IE6
// Check if elements with layout shrink-wrap their children
if ( typeof div.style.zoom !== strundefined ) {
// Reset CSS: box-sizing; display; margin; border
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;" +
"padding:1px;width:1px;zoom:1";
div.appendChild( document.createElement( "div" ) ).style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
return shrinkWrapBlocksVal;
};
})();
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
if ( elem.ownerDocument.defaultView.opener ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
}
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
var condition = conditionFn();
if ( condition == null ) {
// The test was not ready at this point; screw the hook this time
// but check again when needed next time.
return;
}
if ( condition ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
// Minified: var b,c,d,e,f,g, h,i
var div, style, a, pixelPositionVal, boxSizingReliableVal,
reliableHiddenOffsetsVal, reliableMarginRightVal;
// Setup
div = document.createElement( "div" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
style = a && a.style;
// Finish early in limited (non-browser) environments
if ( !style ) {
return;
}
style.cssText = "float:left;opacity:.5";
// Support: IE<9
// Make sure that element opacity exists (as opposed to filter)
support.opacity = style.opacity === "0.5";
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
style.WebkitBoxSizing === "";
jQuery.extend(support, {
reliableHiddenOffsets: function() {
if ( reliableHiddenOffsetsVal == null ) {
computeStyleTests();
}
return reliableHiddenOffsetsVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
// Support: Android 2.3
reliableMarginRight: function() {
if ( reliableMarginRightVal == null ) {
computeStyleTests();
}
return reliableMarginRightVal;
}
});
function computeStyleTests() {
// Minified: var b,c,d,j
var div, body, container, contents;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
// Support: IE<9
// Assume reasonable values in the absence of getComputedStyle
pixelPositionVal = boxSizingReliableVal = false;
reliableMarginRightVal = true;
// Check for getComputedStyle so that this code is not run in IE<9.
if ( window.getComputedStyle ) {
pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
boxSizingReliableVal =
( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
contents = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
contents.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
contents.style.marginRight = contents.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );
div.removeChild( contents );
}
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
contents = div.getElementsByTagName( "td" );
contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
if ( reliableHiddenOffsetsVal ) {
contents[ 0 ].style.display = "";
contents[ 1 ].style.display = "none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
}
body.removeChild( container );
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
// Minified: var a,b,c,d,e
var input, div, select, a, opt;
// Setup
div = document.createElement( "div" );
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName("a")[ 0 ];
// First batch of tests.
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
})();
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hook for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
} :
function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
}) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType.charAt( 0 ) === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!support.reliableHiddenOffsets() &&
((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6+
function() {
// XHR cannot access local files, always use ActiveX for that case
return !this.isLocal &&
// Support: IE7-8
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
/^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
});
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
if ( !options.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off, url.length ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
ajax/libs/6to5/3.6.5/browser.js | ppoffice/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.to5=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.11.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,curPosition()]:tokPos;initParserState();if(options.strictMode){strict=true}return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={strictMode:false,playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowHashBang:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.ecmaVersion>=6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(){lastEnd=tokEnd;readToken();return new Token}getToken.jumpTo=function(pos,exprAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokExprAllowed=!!exprAllowed;skipSpace()};getToken.current=function(){return new Token};if(typeof Symbol!=="undefined"){getToken[Symbol.iterator]=function(){return{next:function(){var token=getToken();return{done:token.type===_eof,value:token}}}}}getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokContext,tokExprAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inType;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=curPosition();inFunction=inGenerator=inAsync=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _jsxName={type:"jsxName"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_template={type:"template"};var _ellipsis={type:"...",beforeExpr:true};var _backQuote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _jsxText={type:"jsxText"};var _paamayimNekudotayim={type:"::",beforeExpr:true};var _hash={type:"#"};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _exponent={binop:11,beforeExpr:true,rightAssociative:true};var _jsxTagStart={type:"jsxTagStart"},_jsxTagEnd={type:"jsxTagEnd"};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,paamayimNekudotayim:_paamayimNekudotayim,exponent:_exponent,hash:_hash,arrow:_arrow,template:_template,star:_star,assign:_assign,backQuote:_backQuote,dollarBraceL:_dollarBraceL,jsxName:_jsxName,jsxText:_jsxText,jsxTagStart:_jsxTagStart,jsxTagEnd:_jsxTagEnd};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];var isReservedWord3=function anonymous(str){switch(str.length){case 6:switch(str){case"double":case"export":case"import":case"native":case"public":case"static":case"throws":return true}return false;case 4:switch(str){case"byte":case"char":case"enum":case"goto":case"long":return true}return false;case 5:switch(str){case"class":case"final":case"float":case"short":case"super":return true}return false;case 7:switch(str){case"boolean":case"extends":case"package":case"private":return true}return false;case 9:switch(str){case"interface":case"protected":case"transient":return true}return false;case 8:switch(str){case"abstract":case"volatile":return true}return false;case 10:return str==="implements";case 3:return str==="int";case 12:return str==="synchronized"}};var isReservedWord5=function anonymous(str){switch(str.length){case 5:switch(str){case"class":case"super":case"const":return true}return false;case 6:switch(str){case"export":case"import":return true}return false;case 4:return str==="enum";case 7:return str==="extends"}};var isStrictReservedWord=function anonymous(str){switch(str.length){case 9:switch(str){case"interface":case"protected":return true}return false;case 7:switch(str){case"package":case"private":return true}return false;case 6:switch(str){case"public":case"static":return true}return false;case 10:return str==="implements";case 3:return str==="let";case 5:return str==="yield"}};var isStrictBadIdWord=function anonymous(str){switch(str){case"eval":case"arguments":return true}return false};var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var isEcma5AndLessKeyword=function anonymous(str){switch(str.length){case 4:switch(str){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 5:switch(str){case"break":case"catch":case"throw":case"while":case"false":return true}return false;case 3:switch(str){case"for":case"try":case"var":case"new":return true}return false;case 6:switch(str){case"return":case"switch":case"typeof":case"delete":return true}return false;case 8:switch(str){case"continue":case"debugger":case"function":return true}return false;case 2:switch(str){case"do":case"if":case"in":return true}return false;case 7:switch(str){case"default":case"finally":return true}return false;case 10:return str==="instanceof"}};var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=function anonymous(str){switch(str.length){case 5:switch(str){case"break":case"catch":case"throw":case"while":case"false":case"const":case"class":case"yield":return true}return false;case 4:switch(str){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 6:switch(str){case"return":case"switch":case"typeof":case"delete":case"export":case"import":return true}return false;case 3:switch(str){case"for":case"try":case"var":case"new":case"let":return true}return false;case 8:switch(str){case"continue":case"debugger":case"function":return true}return false;case 7:switch(str){case"default":case"finally":case"extends":return true}return false;case 2:switch(str){case"do":case"if":case"in":return true}return false;case 10:return str==="instanceof"}};var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var decimalNumber=/^\d+$/;var hexNumber=/^[\da-fA-F]+$/;var newline=/[\n\r\u2028\u2029]/;function isNewLine(code){return code===10||code===13||code===8232||code==8233}var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(line,col){this.line=line;this.column=col}Position.prototype.offset=function(n){return new Position(this.line,this.column+n)};function curPosition(){return new Position(tokCurLine,tokPos-tokLineStart)}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokType=_eof;tokContext=[b_stat];tokExprAllowed=true;inType=strict=false;if(tokPos===0&&options.allowHashBang&&input.slice(0,2)==="#!"){skipLineComment(2)}}var b_stat={token:"{",isExpr:false},b_expr={token:"{",isExpr:true},b_tmpl={token:"${",isExpr:true};var p_stat={token:"(",isExpr:false},p_expr={token:"(",isExpr:true};var q_tmpl={token:"`",isExpr:true},f_expr={token:"function",isExpr:true};var j_oTag={token:"<tag",isExpr:false},j_cTag={token:"</tag",isExpr:false},j_expr={token:"<tag>...</tag>",isExpr:true};function curTokContext(){return tokContext[tokContext.length-1]}function braceIsBlock(prevType){var parent;if(prevType===_colon&&(parent=curTokContext()).token=="{")return!parent.isExpr;if(prevType===_return)return newline.test(input.slice(lastEnd,tokStart));if(prevType===_else||prevType===_semi||prevType===_eof)return true;if(prevType==_braceL)return curTokContext()===b_stat;return!tokExprAllowed}function finishToken(type,val){tokEnd=tokPos;if(options.locations)tokEndLoc=curPosition();var prevType=tokType,preserveSpace=false;tokType=type;tokVal=val;if(type===_parenR||type===_braceR){var out=tokContext.pop();if(out===b_tmpl){preserveSpace=tokExprAllowed=true}else if(out===b_stat&&curTokContext()===f_expr){tokContext.pop();tokExprAllowed=false}else{tokExprAllowed=!(out&&out.isExpr)}}else if(type===_braceL){switch(curTokContext()){case j_oTag:tokContext.push(b_expr);break;case j_expr:tokContext.push(b_tmpl);break;default:tokContext.push(braceIsBlock(prevType)?b_stat:b_expr)}tokExprAllowed=true}else if(type===_dollarBraceL){tokContext.push(b_tmpl);tokExprAllowed=true}else if(type==_parenL){var statementParens=prevType===_if||prevType===_for||prevType===_with||prevType===_while;tokContext.push(statementParens?p_stat:p_expr);tokExprAllowed=true}else if(type==_incDec){}else if(type.keyword&&prevType==_dot){tokExprAllowed=false}else if(type==_function){if(curTokContext()!==b_stat){tokContext.push(f_expr)}tokExprAllowed=false}else if(type===_backQuote){if(curTokContext()===q_tmpl){tokContext.pop()}else{tokContext.push(q_tmpl);preserveSpace=true}tokExprAllowed=false}else if(type===_jsxTagStart){tokContext.push(j_expr);tokContext.push(j_oTag);tokExprAllowed=false}else if(type===_jsxTagEnd){var out=tokContext.pop();if(out===j_oTag&&prevType===_slash||out===j_cTag){tokContext.pop();preserveSpace=tokExprAllowed=curTokContext()===j_expr}else{preserveSpace=tokExprAllowed=true}}else if(type===_jsxText){preserveSpace=tokExprAllowed=true}else if(type===_slash&&prevType===_jsxTagStart){tokContext.length-=2;tokContext.push(j_cTag);tokExprAllowed=false}else{tokExprAllowed=type.beforeExpr}if(!preserveSpace)skipSpace()}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&curPosition();var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&curPosition())}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&curPosition();var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&curPosition())}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.playground&&next===63){tokPos+=2;return finishToken(_dotQuestion)}else if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokExprAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_modulo(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_modulo,1)}function readToken_mult(){var type=_star;var width=1;var next=input.charCodeAt(tokPos+1);if(options.ecmaVersion>=7&&next===42){width++;next=input.charCodeAt(tokPos+2);type=_exponent}if(next===61){width++;type=_assign}return finishOp(type,width)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(options.playground&&input.charCodeAt(tokPos+2)===61)return finishOp(_assign,3);return finishOp(code===124?_logicalOR:_logicalAND,2)}if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(!inType&&next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(!inType){if(tokExprAllowed&&code===60){++tokPos;return finishToken(_jsxTagStart)}if(code===62){var context=curTokContext();if(context===j_oTag||context===j_cTag){++tokPos;return finishToken(_jsxTagEnd)}}}if(next===61)size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR);case 63:++tokPos;return finishToken(_question);case 35:if(options.playground){++tokPos;return finishToken(_hash)}case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_paamayimNekudotayim)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_backQuote)}else{return false}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:return readToken_modulo();case 42:return readToken_mult();case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(){tokStart=tokPos;if(options.locations)tokStartLoc=curPosition();if(tokPos>=inputLen)return finishToken(_eof);var context=curTokContext();if(context===q_tmpl){return readTmplToken()}if(context===j_expr){return readJSXToken()}var code=input.charCodeAt(tokPos);if(context===j_oTag||context===j_cTag){if(isIdentifierStart(code))return readJSXWord()}else if(context===j_expr){return readJSXToken()}else{if(isIdentifierStart(code)||code===92)return readWord()}var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){var isJSX=curTokContext()===j_oTag;var out="",chunkStart=++tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote)break;if(ch===92&&!isJSX){out+=input.slice(chunkStart,tokPos);out+=readEscapedChar();chunkStart=tokPos}else if(ch===38&&isJSX){out+=input.slice(chunkStart,tokPos);out+=readJSXEntity();chunkStart=tokPos}else{if(isNewLine(ch)&&!isJSX)raise(tokStart,"Unterminated string constant");++tokPos}}out+=input.slice(chunkStart,tokPos++);return finishToken(_string,out)}function readTmplToken(){var out="",chunkStart=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated template");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123){if(tokPos===tokStart&&tokType===_template){if(ch===36){tokPos+=2;return finishToken(_dollarBraceL)}else{++tokPos;return finishToken(_backQuote)}}out+=input.slice(chunkStart,tokPos);return finishToken(_template,out)}if(ch===92){out+=input.slice(chunkStart,tokPos);out+=readEscapedChar();chunkStart=tokPos}else if(isNewLine(ch)){out+=input.slice(chunkStart,tokPos);++tokPos;if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;out+="\n"}else{out+=String.fromCharCode(ch)}if(options.locations){++tokCurLine;tokLineStart=tokPos}chunkStart=tokPos}else{++tokPos}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readJSXEntity(){var str="",count=0,entity;var ch=input[tokPos];if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=input[tokPos++];if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}return entity}function readJSXToken(){var out="",chunkStart=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated JSX contents");var ch=input.charCodeAt(tokPos);switch(ch){case 123:case 60:if(tokPos===tokStart){return getTokenFromCode(ch)}out+=input.slice(chunkStart,tokPos);return finishToken(_jsxText,out);case 38:out+=input.slice(chunkStart,tokPos);out+=readJSXEntity();chunkStart=tokPos;break;default:if(isNewLine(ch)){out+=input.slice(chunkStart,tokPos);
++tokPos;if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;out+="\n"}else{out+=String.fromCharCode(ch)}if(options.locations){++tokCurLine;tokLineStart=tokPos}chunkStart=tokPos}else{++tokPos}}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return"";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&"e!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word="",first=true,chunkStart=tokPos;while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)){++tokPos}else if(ch===92){containsEsc=true;word+=input.slice(chunkStart,tokPos);if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr;chunkStart=tokPos}else{break}first=false}return word+input.slice(chunkStart,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function readJSXWord(){var ch,start=tokPos;do{ch=input.charCodeAt(++tokPos)}while(isIdentifierChar(ch)||ch===45);return finishToken(_jsxName,input.slice(start,tokPos))}function next(){if(options.onToken)options.onToken(new Token);lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;if(tokType!==_num&&tokType!==_string)return;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new exports.Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new exports.Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function finishNodeAt(node,type,pos){if(options.locations){node.loc.end=pos[1];pos=pos[0]}node.type=type;node.end=pos;if(options.ranges)node.range[1]=pos;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function isContextual(name){return tokType===_name&&tokVal===name}function eatContextual(name){return tokVal===name&&eat(_name)}function expectContextual(name){if(!eatContextual(name))unexpected()}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node,isBinding){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"VirtualPropertyExpression":case"MemberExpression":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.kind!=="init")raise(prop.key.start,"Object pattern can't contain getter or setter");toAssignable(prop.value,isBinding)}break;case"ArrayExpression":node.type="ArrayPattern";toAssignableList(node.elements,isBinding);break;case"AssignmentExpression":if(node.operator==="="){node.type="AssignmentPattern"}else{raise(node.left.end,"Only '=' operator can be used for specifying default value.")}break;case"MemberExpression":if(!isBinding)break;default:raise(node.start,"Assigning to rvalue")}}return node}function toAssignableList(exprList,isBinding){if(exprList.length){for(var i=0;i<exprList.length-1;i++){toAssignable(exprList[i],isBinding)}var last=exprList[exprList.length-1];switch(last.type){case"RestElement":break;case"SpreadElement":last.type="RestElement";var arg=last.argument;toAssignable(arg,isBinding);if(arg.type!=="Identifier"&&arg.type!=="MemberExpression"&&arg.type!=="ArrayPattern")unexpected(arg.start);break;default:toAssignable(last,isBinding)}}return exprList}function parseSpread(refShorthandDefaultPos){var node=startNode();next();node.argument=parseMaybeAssign(refShorthandDefaultPos);return finishNode(node,"SpreadElement")}function parseRest(){var node=startNode();next();node.argument=tokType===_name||tokType===_bracketL?parseBindingAtom():unexpected();return finishNode(node,"RestElement")}function parseBindingAtom(){if(options.ecmaVersion<6)return parseIdent();switch(tokType){case _name:return parseIdent();case _bracketL:var node=startNode();next();node.elements=parseBindingList(_bracketR,true);return finishNode(node,"ArrayPattern");case _braceL:return parseObj(true);default:unexpected()}}function parseBindingList(close,allowEmpty){var elts=[],first=true;while(!eat(close)){first?first=false:expect(_comma);if(tokType===_ellipsis){elts.push(parseAssignableListItemTypes(parseRest()));expect(close);break}var elem;if(allowEmpty&&tokType===_comma){elem=null}else{var left=parseMaybeDefault();parseAssignableListItemTypes(left);elem=parseMaybeDefault(null,left)}elts.push(elem)}return elts}function parseAssignableListItemTypes(param){if(eat(_question)){param.optional=true}if(tokType===_colon){param.typeAnnotation=parseTypeAnnotation()}finishNode(param,param.type);return param}function parseMaybeDefault(startPos,left){startPos=startPos||storeCurrentPos();left=left||parseBindingAtom();if(!eat(_eq))return left;var node=startNodeAt(startPos);node.operator="=";node.left=left;node.right=parseMaybeAssign();return finishNode(node,"AssignmentPattern")}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break;case"RestElement":return checkFunctionParam(param.argument,nameHash)}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return;var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,(isBinding?"Binding ":"Assigning to ")+expr.name+" in strict mode");break;case"MemberExpression":if(isBinding)raise(expr.start,"Binding to member expression");break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++){var prop=expr.properties[i];if(prop.type==="Property")prop=prop.value;checkLVal(prop,isBinding)}break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"AssignmentPattern":checkLVal(expr.left);break;case"SpreadProperty":case"VirtualPropertyExpression":break;case"RestElement":checkLVal(expr.argument);break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement(true,true);node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}next();return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(declaration,topLevel){var starttype=tokType,node=startNode();switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _function:if(!declaration&&options.ecmaVersion>=6)unexpected();return parseFunctionStatement(node);case _class:if(!declaration)unexpected();return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _let:case _const:if(!declaration)unexpected();case _var:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:case _import:if(!topLevel&&!options.allowImportExportEverywhere)raise(tokStart,"'import' and 'export' may only appear at the top level");return starttype===_import?parseImport(node):parseExport(node);default:var maybeName=tokVal,expr=parseExpression();if(options.ecmaVersion>=7&&starttype===_name&&maybeName==="async"&&tokType===_function&&!canInsertSemicolon()){next();var func=parseFunctionStatement(node);func.async=true;return func}if(starttype===_name&&expr.type==="Identifier"){if(eat(_colon)){return parseLabeledStatement(node,maybeName,expr)}if(options.ecmaVersion>=7&&expr.name==="private"&&tokType===_name){return parsePrivate(node)}else if(expr.name==="declare"){if(tokType===_class||tokType===_name||tokType===_function||tokType===_var){return parseDeclare(node)}}else if(tokType===_name){if(expr.name==="interface"){return parseInterface(node)}else if(expr.name==="type"){return parseTypeAlias(node)}}}if(expr.type==="FunctionExpression"&&expr.async){if(expr.id){expr.type="FunctionDeclaration";return expr}else{unexpected(expr.start+"async function ".length)}}return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement(false);labels.pop();expect(_while);node.test=parseParenExpression();if(options.ecmaVersion>=6)eat(_semi);else semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&isContextual("of"))&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var refShorthandDefaultPos={start:0};var init=parseExpression(true,refShorthandDefaultPos);if(tokType===_in||options.ecmaVersion>=6&&isContextual("of")){toAssignable(init);checkLVal(init);return parseForIn(node,init)}else if(refShorthandDefaultPos.start){unexpected(refShorthandDefaultPos.start)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement(false);node.alternate=eat(_else)?parseStatement(false):null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected();cur.consequent.push(parseStatement(true))}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseBindingAtom();checkLVal(clause.param,true);expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement(false);labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement(false);return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement(true);labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement(true);node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement(false);labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement(false);labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=parseBindingAtom();checkLVal(decl.id,true);if(tokType===_colon){decl.id.typeAnnotation=parseTypeAnnotation();finishNode(decl.id,decl.id.type)}decl.init=eat(_eq)?parseMaybeAssign(noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn,refShorthandDefaultPos);if(tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn,refShorthandDefaultPos));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn,refShorthandDefaultPos,afterLeftParse){var failOnShorthandAssign;if(!refShorthandDefaultPos){refShorthandDefaultPos={start:0};failOnShorthandAssign=true}else{failOnShorthandAssign=false}var start=storeCurrentPos();var left=parseMaybeConditional(noIn,refShorthandDefaultPos);if(afterLeftParse)left=afterLeftParse(left,start);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;refShorthandDefaultPos.start=0;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}else if(failOnShorthandAssign&&refShorthandDefaultPos.start){unexpected(refShorthandDefaultPos.start)}return left}function parseMaybeConditional(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseExprOps(noIn,refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;if(eat(_question)){var node=startNodeAt(start);if(options.playground&&eat(_eq)){var left=node.left=toAssignable(expr);if(left.type!=="MemberExpression")raise(left.start,"You can only use member expressions in memoization assignment");node.right=parseMaybeAssign(noIn);node.operator="?=";return finishNode(node,"AssignmentExpression")}node.test=expr;node.consequent=parseMaybeAssign();expect(_colon);node.alternate=parseMaybeAssign(noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseMaybeUnary(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;return parseExprOp(expr,start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,op.rightAssociative?prec-1:prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(refShorthandDefaultPos){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate;node.operator=tokVal;node.prefix=true;next();node.argument=parseMaybeUnary();if(refShorthandDefaultPos&&refShorthandDefaultPos.start)unexpected(refShorthandDefaultPos.start);if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,update?"UpdateExpression":"UnaryExpression")}var start=storeCurrentPos();var expr=parseExprSubscripts(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseExprAtom(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;return parseSubscripts(expr,start)}function parseSubscripts(base,start,noCalls){if(options.playground&&eat(_hash)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return parseSubscripts(finishNode(node,"BindMemberExpression"),start,noCalls)}else if(eat(_paamayimNekudotayim)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);return parseSubscripts(finishNode(node,"VirtualPropertyExpression"),start,noCalls)}else if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_backQuote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(refShorthandDefaultPos){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _yield:if(inGenerator)return parseYield();case _name:var start=storeCurrentPos();var node=startNode();var id=parseIdent(tokType!==_name);if(options.ecmaVersion>=7){if(id.name==="async"){if(tokType===_parenL){next();var exprList;if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(eat(_arrow)){return parseArrowExpression(node,exprList,true)}else{node.callee=id;node.arguments=exprList;return parseSubscripts(finishNode(node,"CallExpression"),start)}}else if(tokType===_name){id=parseIdent();if(eat(_arrow)){return parseArrowExpression(node,[id],true)}return id}if(tokType===_function&&!canInsertSemicolon()){next();return parseFunction(node,false,true)}}else if(id.name==="await"){if(inAsync)return parseAwait(node)}}if(!canInsertSemicolon()&&eat(_arrow)){return parseArrowExpression(startNodeAt(start),[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _jsxText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:return parseParenAndDistinguishExpression();case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true,refShorthandDefaultPos);return finishNode(node,"ArrayExpression");case _braceL:return parseObj(false,refShorthandDefaultPos);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _backQuote:return parseTemplate();case _hash:return parseBindFunctionExpression();case _jsxTagStart:return parseJSXElement();default:unexpected()}}function parseBindFunctionExpression(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return finishNode(node,"BindFunctionExpression")}function parseParenAndDistinguishExpression(){var start=storeCurrentPos(),val;if(options.ecmaVersion>=6){next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(startNodeAt(start),true)}var innerStart=storeCurrentPos(),exprList=[],first=true;var refShorthandDefaultPos={start:0},spreadStart,innerParenStart,typeStart;var parseParenItem=function(node,start){if(tokType===_colon){var typeCastNode=startNodeAt(start);typeCastNode.expression=node;typeCastNode.typeAnnotation=parseTypeAnnotation();return finishNode(typeCastNode,"TypeCastExpression")}else{return node}};while(tokType!==_parenR){first?first=false:expect(_comma);if(tokType===_ellipsis){var spreadNodeStart=storeCurrentPos();spreadStart=tokStart;exprList.push(parseParenItem(parseRest(),spreadNodeStart));break}else{if(tokType===_parenL&&!innerParenStart){innerParenStart=tokStart}exprList.push(parseMaybeAssign(false,refShorthandDefaultPos,parseParenItem))}}var innerEnd=storeCurrentPos();expect(_parenR);if(!canInsertSemicolon()&&eat(_arrow)){if(innerParenStart)unexpected(innerParenStart);for(var i=0;i<exprList.length;i++){var listItem=exprList[i];if(listItem.type==="TypeCastExpression"){var expr=listItem.expression;expr.returnType=listItem.typeAnnotation;exprList[i]=expr}}return parseArrowExpression(startNodeAt(start),exprList)}if(!exprList.length)unexpected(lastStart);if(spreadStart)unexpected(spreadStart);if(refShorthandDefaultPos.start)unexpected(refShorthandDefaultPos.start);if(exprList.length>1){val=startNodeAt(innerStart);val.expressions=exprList;finishNodeAt(val,"SequenceExpression",innerEnd)}else{val=exprList[0]}}else{val=parseParenExpression()}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;return finishNode(par,"ParenthesizedExpression")}else{return val}}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false);else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplateElement(){var elem=startNode();elem.value={raw:input.slice(tokStart,tokEnd),cooked:tokVal};next();elem.tail=tokType===_backQuote;return finishNode(elem,"TemplateElement")}function parseTemplate(){var node=startNode();next();node.expressions=[];var curElt=parseTemplateElement();node.quasis=[curElt];while(!curElt.tail){expect(_dollarBraceL);node.expressions.push(parseExpression());expect(_braceR);node.quasis.push(curElt=parseTemplateElement())}next();return finishNode(node,"TemplateLiteral")}function parseObj(isPattern,refShorthandDefaultPos){var node=startNode(),first=true,propHash={};node.properties=[];next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),start,isGenerator=false,isAsync=false;if(options.ecmaVersion>=7&&tokType===_ellipsis){prop=parseSpread();prop.type="SpreadProperty";node.properties.push(prop);continue}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refShorthandDefaultPos){start=storeCurrentPos()}if(!isPattern){isGenerator=eat(_star)
}}if(options.ecmaVersion>=7&&isContextual("async")){var asyncId=parseIdent();if(tokType===_colon||tokType===_parenL){prop.key=asyncId}else{isAsync=true;parsePropertyName(prop)}}else{parsePropertyName(prop)}var typeParameters;if(isRelational("<")){typeParameters=parseTypeParameterDeclaration();if(tokType!==_parenL)unexpected()}if(eat(_colon)){prop.value=isPattern?parseMaybeDefault():parseMaybeAssign(false,refShorthandDefaultPos);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){if(isPattern)unexpected();prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set"||options.playground&&prop.key.name==="memo")&&(tokType!=_comma&&tokType!=_braceR)){if(isGenerator||isAsync||isPattern)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";if(isPattern){prop.value=parseMaybeDefault(start,prop.key)}else if(tokType===_eq&&refShorthandDefaultPos){if(!refShorthandDefaultPos.start)refShorthandDefaultPos.start=tokStart;prop.value=parseMaybeDefault(start,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else unexpected();prop.value.typeParameters=typeParameters;checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}return finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;if(options.ecmaVersion>=6){node.generator=false;node.expression=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseFunctionParams(node){expect(_parenL);node.params=parseBindingList(_parenR,false);if(tokType===_colon){node.returnType=parseTypeAnnotation()}}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);node.params=toAssignableList(params,true);parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseMaybeAssign();node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash)}}function parsePrivate(node){node.declarations=[];do{node.declarations.push(parseIdent())}while(eat(_comma));semicolon();return finishNode(node,"PrivateDeclaration")}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}node.superClass=eat(_extends)?parseExprSubscripts():null;if(node.superClass&&isRelational("<")){node.superTypeParameters=parseTypeParameterInstantiation()}if(isContextual("implements")){next();node.implements=parseClassImplements()}var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){if(eat(_semi))continue;var method=startNode();if(options.ecmaVersion>=7&&isContextual("private")){next();classBody.body.push(parsePrivate(method));continue}var isGenerator=eat(_star);var isAsync=false;parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="static"){if(isGenerator||isAsync)unexpected();method["static"]=true;isGenerator=eat(_star);parsePropertyName(method)}else{method["static"]=false}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="async"){isAsync=true;parsePropertyName(method)}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")||options.playground&&method.key.name==="memo"){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}var classProperty=false;if(tokType===_colon){method.typeAnnotation=parseTypeAnnotation();classProperty=true}if(options.playground&&eat(_eq)){method.value=parseMaybeAssign();classProperty=true}if(classProperty){semicolon();classBody.body.push(finishNode(method,"ClassProperty"))}else{var typeParameters;if(isRelational("<")){typeParameters=parseTypeParameterDeclaration()}method.value=parseMethod(isGenerator,isAsync);method.value.typeParameters=typeParameters;classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseClassImplements(){var implemented=[];do{var node=startNode();node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}implemented.push(finishNode(node,"ClassImplements"))}while(eat(_comma));return implemented}function parseExprList(close,allowTrailingComma,allowEmpty,refShorthandDefaultPos){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma){elts.push(null)}else{if(tokType===_ellipsis)elts.push(parseSpread(refShorthandDefaultPos));else elts.push(parseMaybeAssign(false,refShorthandDefaultPos))}}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||isContextual("async")||isContextual("type")){node.declaration=parseStatement(true);node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){var expr=parseMaybeAssign();if(expr.id){switch(expr.type){case"FunctionExpression":expr.type="FunctionDeclaration";break;case"ClassExpression":expr.type="ClassDeclaration";break}}node.declaration=expr;node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(eatContextual("from")){node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);node.name=eatContextual("as")?parseIdent(true):null;nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();node.isType=false;node.specifiers=[];var typeId;if(isContextual("type")){var start=storeCurrentPos();typeId=parseIdent();if(tokType===_name&&tokVal!=="from"||tokType===_braceL||tokType===_star){node.isType=true}else{node.specifiers.push(parseImportSpecifierDefault(typeId,start));eat(_comma)}}if(tokType===_string){if(typeId)unexpected(typeId.start);node.source=parseExprAtom()}else{if(!isContextual("from"))parseImportSpecifiers(node.specifiers);expectContextual("from");node.source=tokType===_string?parseExprAtom():unexpected()}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(nodes){var first=true;if(tokType===_name){var start=storeCurrentPos();var id=parseIdent();nodes.push(parseImportSpecifierDefault(id,start));if(!eat(_comma))return nodes}if(tokType===_star){var node=startNode();next();expectContextual("as");node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);node.name=eatContextual("as")?parseIdent():null;checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseImportSpecifierDefault(id,start){var node=startNodeAt(start);node.id=id;checkLVal(node.id,true);node.name=null;node["default"]=true;return finishNode(node,"ImportSpecifier")}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseMaybeAssign()}return finishNode(node,"YieldExpression")}function parseAwait(node){if(eat(_semi)||canInsertSemicolon()){unexpected()}node.all=eat(_star);node.argument=parseMaybeAssign(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=parseBindingAtom();checkLVal(block.left,true);expectContextual("of");block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedJSXName(object){if(object.type==="JSXIdentifier"){return object.name}if(object.type==="JSXNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="JSXMemberExpression"){return getQualifiedJSXName(object.object)+"."+getQualifiedJSXName(object.property)}}function parseJSXIdentifier(){var node=startNode();if(tokType===_jsxName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}next();return finishNode(node,"JSXIdentifier")}function parseJSXNamespacedName(){var start=storeCurrentPos();var name=parseJSXIdentifier();if(!eat(_colon))return name;var node=startNodeAt(start);node.namespace=name;node.name=parseJSXIdentifier();return finishNode(node,"JSXNamespacedName")}function parseJSXElementName(){var start=storeCurrentPos();var node=parseJSXNamespacedName();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseJSXIdentifier();node=finishNode(newNode,"JSXMemberExpression")}return node}function parseJSXAttributeValue(){switch(tokType){case _braceL:var node=parseJSXExpressionContainer();if(node.expression.type==="JSXEmptyExpression"){raise(node.start,"JSX attributes must only be assigned a non-empty "+"expression")}return node;case _jsxTagStart:return parseJSXElement();case _jsxText:case _string:return parseExprAtom();default:raise(tokStart,"JSX value should be either an expression or a quoted JSX text")}}function parseJSXEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"JSXEmptyExpression")}function parseJSXExpressionContainer(){var node=startNode();next();node.expression=tokType===_braceR?parseJSXEmptyExpression():parseExpression();expect(_braceR);return finishNode(node,"JSXExpressionContainer")}function parseJSXAttribute(){var node=startNode();if(eat(_braceL)){expect(_ellipsis);node.argument=parseMaybeAssign();expect(_braceR);return finishNode(node,"JSXSpreadAttribute")}node.name=parseJSXNamespacedName();node.value=eat(_eq)?parseJSXAttributeValue():null;return finishNode(node,"JSXAttribute")}function parseJSXOpeningElementAt(start){var node=startNodeAt(start);node.attributes=[];node.name=parseJSXElementName();while(tokType!==_slash&&tokType!==_jsxTagEnd){node.attributes.push(parseJSXAttribute())}node.selfClosing=eat(_slash);expect(_jsxTagEnd);return finishNode(node,"JSXOpeningElement")}function parseJSXClosingElementAt(start){var node=startNodeAt(start);node.name=parseJSXElementName();expect(_jsxTagEnd);return finishNode(node,"JSXClosingElement")}function parseJSXElementAt(start){var node=startNodeAt(start);var children=[];var openingElement=parseJSXOpeningElementAt(start);var closingElement=null;if(!openingElement.selfClosing){contents:for(;;){switch(tokType){case _jsxTagStart:start=storeCurrentPos();next();if(eat(_slash)){closingElement=parseJSXClosingElementAt(start);break contents}children.push(parseJSXElementAt(start));break;case _jsxText:children.push(parseExprAtom());break;case _braceL:children.push(parseJSXExpressionContainer());break;default:unexpected()}}if(getQualifiedJSXName(closingElement.name)!==getQualifiedJSXName(openingElement.name)){raise(closingElement.start,"Expected corresponding JSX closing tag for <"+getQualifiedJSXName(openingElement.name)+">")}}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"JSXElement")}function isRelational(op){return tokType===_relational&&tokVal===op}function expectRelational(op){if(isRelational(op)){next()}else{unexpected()}}function parseJSXElement(){var start=storeCurrentPos();next();return parseJSXElementAt(start)}function parseDeclareClass(node){next();parseInterfaceish(node,true);return finishNode(node,"DeclareClass")}function parseDeclareFunction(node){next();var id=node.id=parseIdent();var typeNode=startNode();var typeContainer=startNode();if(isRelational("<")){typeNode.typeParameters=parseTypeParameterDeclaration()}else{typeNode.typeParameters=null}expect(_parenL);var tmp=parseFunctionTypeParams();typeNode.params=tmp.params;typeNode.rest=tmp.rest;expect(_parenR);expect(_colon);typeNode.returnType=parseType();typeContainer.typeAnnotation=finishNode(typeNode,"FunctionTypeAnnotation");id.typeAnnotation=finishNode(typeContainer,"TypeAnnotation");finishNode(id,id.type);semicolon();return finishNode(node,"DeclareFunction")}function parseDeclare(node){if(tokType===_class){return parseDeclareClass(node)}else if(tokType===_function){return parseDeclareFunction(node)}else if(tokType===_var){return parseDeclareVariable(node)}else if(isContextual("module")){return parseDeclareModule(node)}else{unexpected()}}function parseDeclareVariable(node){next();node.id=parseTypeAnnotatableIdentifier();semicolon();return finishNode(node,"DeclareVariable")}function parseDeclareModule(node){next();if(tokType===_string){node.id=parseExprAtom()}else{node.id=parseIdent()}var bodyNode=node.body=startNode();var body=bodyNode.body=[];expect(_braceL);while(tokType!==_braceR){var node2=startNode();next();body.push(parseDeclare(node2))}expect(_braceR);finishNode(bodyNode,"BlockStatement");return finishNode(node,"DeclareModule")}function parseInterfaceish(node,allowStatic){node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}node.extends=[];if(eat(_extends)){do{node.extends.push(parseInterfaceExtends())}while(eat(_comma))}node.body=parseObjectType(allowStatic)}function parseInterfaceExtends(){var node=startNode();node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}return finishNode(node,"InterfaceExtends")}function parseInterface(node){parseInterfaceish(node,false);return finishNode(node,"InterfaceDeclaration")}function parseTypeAlias(node){node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}expect(_eq);node.right=parseType();semicolon();return finishNode(node,"TypeAlias")}function parseTypeParameterDeclaration(){var node=startNode();node.params=[];expectRelational("<");while(!isRelational(">")){node.params.push(parseIdent());if(!isRelational(">")){expect(_comma)}}expectRelational(">");return finishNode(node,"TypeParameterDeclaration")}function parseTypeParameterInstantiation(){var node=startNode(),oldInType=inType;node.params=[];inType=true;expectRelational("<");while(!isRelational(">")){node.params.push(parseType());if(!isRelational(">")){expect(_comma)}}expectRelational(">");inType=oldInType;return finishNode(node,"TypeParameterInstantiation")}function parseObjectPropertyKey(){return tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function parseObjectTypeIndexer(node,isStatic){node.static=isStatic;expect(_bracketL);node.id=parseObjectPropertyKey();expect(_colon);node.key=parseType();expect(_bracketR);expect(_colon);node.value=parseType();return finishNode(node,"ObjectTypeIndexer")}function parseObjectTypeMethodish(node){node.params=[];node.rest=null;node.typeParameters=null;if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}expect(_parenL);while(tokType===_name){node.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){node.rest=parseFunctionTypeParam()}expect(_parenR);expect(_colon);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}function parseObjectTypeMethod(start,isStatic,key){var node=startNodeAt(start);node.value=parseObjectTypeMethodish(startNodeAt(start));node.static=isStatic;node.key=key;node.optional=false;return finishNode(node,"ObjectTypeProperty")}function parseObjectTypeCallProperty(node,isStatic){var valueNode=startNode();node.static=isStatic;node.value=parseObjectTypeMethodish(valueNode);return finishNode(node,"ObjectTypeCallProperty")}function parseObjectType(allowStatic){var nodeStart=startNode();var node;var optional=false;var property;var propertyKey;var propertyTypeAnnotation;var token;var isStatic;nodeStart.callProperties=[];nodeStart.properties=[];nodeStart.indexers=[];expect(_braceL);while(tokType!==_braceR){var start=storeCurrentPos();node=startNode();if(allowStatic&&isContextual("static")){next();isStatic=true}if(tokType===_bracketL){nodeStart.indexers.push(parseObjectTypeIndexer(node,isStatic))}else if(tokType===_parenL||isRelational("<")){nodeStart.callProperties.push(parseObjectTypeCallProperty(node,allowStatic))}else{if(isStatic&&tokType===_colon){propertyKey=parseIdent()}else{propertyKey=parseObjectPropertyKey()}if(isRelational("<")||tokType===_parenL){nodeStart.properties.push(parseObjectTypeMethod(start,isStatic,propertyKey))}else{if(eat(_question)){optional=true}expect(_colon);node.key=propertyKey;node.value=parseType();node.optional=optional;node.static=isStatic;nodeStart.properties.push(finishNode(node,"ObjectTypeProperty"))}}if(!eat(_semi)&&tokType!==_braceR){unexpected()}}expect(_braceR);return finishNode(nodeStart,"ObjectTypeAnnotation")}function parseGenericType(start,id){var node=startNodeAt(start);node.typeParameters=null;node.id=id;while(eat(_dot)){var node2=startNodeAt(start);node2.qualification=node.id;node2.id=parseIdent();node.id=finishNode(node2,"QualifiedTypeIdentifier")}if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}return finishNode(node,"GenericTypeAnnotation")}function parseVoidType(){var node=startNode();expect(keywordTypes["void"]);return finishNode(node,"VoidTypeAnnotation")}function parseTypeofType(){var node=startNode();expect(keywordTypes["typeof"]);node.argument=parsePrimaryType();return finishNode(node,"TypeofTypeAnnotation")}function parseTupleType(){var node=startNode();node.types=[];expect(_bracketL);while(tokPos<inputLen&&tokType!==_bracketR){node.types.push(parseType());if(tokType===_bracketR)break;expect(_comma)}expect(_bracketR);return finishNode(node,"TupleTypeAnnotation")}function parseFunctionTypeParam(){var optional=false;var node=startNode();node.name=parseIdent();if(eat(_question)){optional=true}expect(_colon);node.optional=optional;node.typeAnnotation=parseType();return finishNode(node,"FunctionTypeParam")}function parseFunctionTypeParams(){var ret={params:[],rest:null};while(tokType===_name){ret.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){ret.rest=parseFunctionTypeParam()}return ret}function identToTypeAnnotation(start,node,id){switch(id.name){case"any":return finishNode(node,"AnyTypeAnnotation");case"bool":case"boolean":return finishNode(node,"BooleanTypeAnnotation");case"number":return finishNode(node,"NumberTypeAnnotation");case"string":return finishNode(node,"StringTypeAnnotation");default:return parseGenericType(start,id)}}function parsePrimaryType(){var typeIdentifier=null;var params=null;var returnType=null;var start=storeCurrentPos();var node=startNode();var rest=null;var tmp;var typeParameters;var token;var type;var isGroupedType=false;switch(tokType){case _name:return identToTypeAnnotation(start,node,parseIdent());case _braceL:return parseObjectType();case _bracketL:return parseTupleType();case _relational:if(tokVal==="<"){node.typeParameters=parseTypeParameterDeclaration();expect(_parenL);tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}case _parenL:next();var tmpId;if(tokType!==_parenR&&tokType!==_ellipsis){if(tokType===_name){}else{isGroupedType=true}}if(isGroupedType){if(tmpId&&_parenR){type=tmpId}else{type=parseType();expect(_parenR)}if(eat(_arrow)){raise(node,"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType")}return type}tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();node.typeParameters=null;return finishNode(node,"FunctionTypeAnnotation");case _string:node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"StringLiteralTypeAnnotation");default:if(tokType.keyword){switch(tokType.keyword){case"void":return parseVoidType();case"typeof":return parseTypeofType()}}}unexpected()}function parsePostfixType(){var node=startNode();var type=node.elementType=parsePrimaryType();if(tokType===_bracketL){expect(_bracketL);expect(_bracketR);return finishNode(node,"ArrayTypeAnnotation")}return type}function parsePrefixType(){var node=startNode();if(eat(_question)){node.typeAnnotation=parsePrefixType();return finishNode(node,"NullableTypeAnnotation")}return parsePostfixType()}function parseIntersectionType(){var node=startNode();var type=parsePrefixType();node.types=[type];while(eat(_bitwiseAND)){node.types.push(parsePrefixType())}return node.types.length===1?type:finishNode(node,"IntersectionTypeAnnotation")}function parseUnionType(){var node=startNode();var type=parseIntersectionType();node.types=[type];while(eat(_bitwiseOR)){node.types.push(parseIntersectionType())}return node.types.length===1?type:finishNode(node,"UnionTypeAnnotation")}function parseType(){var oldInType=inType;inType=true;var type=parseUnionType();inType=oldInType;return type}function parseTypeAnnotation(){var node=startNode();var oldInType=inType;inType=true;expect(_colon);node.typeAnnotation=parseType();inType=oldInType;return finishNode(node,"TypeAnnotation")}function parseTypeAnnotatableIdentifier(requireTypeAnnotation,canBeOptionalParam){var node=startNode();var ident=parseIdent();var isOptionalParam=false;if(canBeOptionalParam&&eat(_question)){expect(_question);isOptionalParam=true}if(requireTypeAnnotation||tokType===_colon){ident.typeAnnotation=parseTypeAnnotation();finishNode(ident,ident.type)}if(isOptionalParam){ident.optional=true;finishNode(ident,ident.type)}return ident}})},{}],2:[function(require,module,exports){(function(global){"use strict";var transform=module.exports=require("../transformation");transform.version=require("../../../package").version;transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5","module"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded";scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i=0;i<_scripts.length;++i){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../../package":319,"../transformation":44}],3:[function(require,module,exports){"use strict";module.exports=Buffer;var isBoolean=require("lodash/lang/isBoolean");var includes=require("lodash/collection/includes");var isNumber=require("lodash/lang/isNumber");var util=require("../util");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact||this.format.concise){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.space()};Buffer.prototype.space=function(){if(this.format.compact)return;if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.substr(0,this.buf.length-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(this.format.compact||this.format.concise){this.space();return}removeLast=removeLast||false;if(isNumber(i)){if(this.endsWith("{\n"))i--;if(this.endsWith(util.repeat(i,"\n")))return;while(i--){this._newline(removeLast)}return}if(isBoolean(i)){removeLast=i}this._newline(removeLast)};Buffer.prototype._newline=function(removeLast){if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this._removeSpacesAfterLastNewline();this._push("\n")};Buffer.prototype._removeSpacesAfterLastNewline=function(){var lastNewlineIndex=this.buf.lastIndexOf("\n");if(lastNewlineIndex===-1)return;var index=this.buf.length-1;while(index>lastNewlineIndex){if(this.buf[index]!==" "){break}index--}if(index===lastNewlineIndex){this.buf=this.buf.substring(0,index+1)}};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){var d=this.buf.length-str.length;return d>=0&&this.buf.lastIndexOf(str)===d};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var last=buf[buf.length-1];if(Array.isArray(cha)){return includes(cha,last)}else{return cha===last}}},{"../util":123,"lodash/collection/includes":197,"lodash/lang/isBoolean":268,"lodash/lang/isNumber":272}],4:[function(require,module,exports){"use strict";exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],5:[function(require,module,exports){"use strict";exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],6:[function(require,module,exports){"use strict";exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],7:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");var isNumber=require("lodash/lang/isNumber");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.push(" ");print(node.argument)};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.space();this.push("?");this.space();print(node.consequent);
this.space();this.push(":");this.space();print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.list(node.arguments);this.push(")")}};exports.SequenceExpression=function(node,print){print.list(node.expressions)};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");var separator=",";if(node._prettyCall){separator+="\n";this.newline();this.indent()}else{separator+=" "}print.list(node.arguments,{separator:separator});if(node._prettyCall){this.newline();this.dedent()}this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate||node.all){this.push("*")}if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentPattern=exports.AssignmentExpression=function(node,print){print(node.left);this.push(" ");this.push(node.operator);this.push(" ");print(node.right)};var SCIENTIFIC_NOTATION=/e/i;exports.MemberExpression=function(node,print){var obj=node.object;print(obj);if(!node.computed&&t.isMemberExpression(node.property)){throw new TypeError("Got a MemberExpression for MemberExpression property")}var computed=node.computed;if(t.isLiteral(node.property)&&isNumber(node.property.value)){computed=true}if(computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(obj)&&util.isInteger(obj.value)&&!SCIENTIFIC_NOTATION.test(obj.value.toString())){this.push(".")}this.push(".");print(node.property)}}},{"../../types":121,"../../util":123,"lodash/lang/isNumber":272}],8:[function(require,module,exports){"use strict";exports.AnyTypeAnnotation=exports.ArrayTypeAnnotation=exports.BooleanTypeAnnotation=exports.ClassProperty=exports.DeclareClass=exports.DeclareFunction=exports.DeclareModule=exports.DeclareVariable=exports.FunctionTypeAnnotation=exports.FunctionTypeParam=exports.GenericTypeAnnotation=exports.InterfaceExtends=exports.InterfaceDeclaration=exports.IntersectionTypeAnnotation=exports.NullableTypeAnnotation=exports.NumberTypeAnnotation=exports.StringLiteralTypeAnnotation=exports.StringTypeAnnotation=exports.TupleTypeAnnotation=exports.TypeofTypeAnnotation=exports.TypeAlias=exports.TypeAnnotation=exports.TypeParameterDeclaration=exports.TypeParameterInstantiation=exports.ObjectTypeAnnotation=exports.ObjectTypeCallProperty=exports.ObjectTypeIndexer=exports.ObjectTypeProperty=exports.QualifiedTypeIdentifier=exports.UnionTypeAnnotation=exports.TypeCastExpression=exports.VoidTypeAnnotation=function(){}},{}],9:[function(require,module,exports){"use strict";var t=require("../../types");var each=require("lodash/collection/each");exports.JSXAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.JSXIdentifier=function(node){this.push(node.name)};exports.JSXNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.JSXMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.JSXSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.JSXExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.JSXElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.JSXOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.push(" ");print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.JSXClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.JSXEmptyExpression=function(){}},{"../../types":121,"lodash/collection/each":194}],10:[function(require,module,exports){"use strict";var t=require("../../types");exports._params=function(node,print){this.push("(");print.list(node.params);this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.push(" ");print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");if(node.id){this.push(" ");print(node.id)}else{this.space()}this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":121}],11:[function(require,module,exports){"use strict";var t=require("../../types");var each=require("lodash/collection/each");exports.ImportSpecifier=function(node,print){if(t.isSpecifierDefault(node)){print(t.getSpecifierName(node))}else{return exports.ExportSpecifier.apply(this,arguments)}};exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}var isDefault=t.isSpecifierDefault(spec);if(!isDefault&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":121,"lodash/collection/each":194}],12:[function(require,module,exports){"use strict";var each=require("lodash/collection/each");each(["BindMemberExpression","BindFunctionExpression"],function(type){exports[type]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(type))}})},{"lodash/collection/each":194}],13:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(")");this.space();print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.space();this.keyword("else");if(this.format.format&&!t.isBlockStatement(node.alternate)){this.push(" ")}print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.push(" ");print(node.test)}this.push(";");if(node.update){this.push(" ");print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.push(" ");print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();if(node.handlers){print(node.handlers[0])}else{print(node.handler)}if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(")");this.space();this.push("{");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.newline();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");var hasInits=false;if(!t.isFor(parent)){for(var i=0;i<node.declarations.length;i++){if(node.declarations[i].init){hasInits=true}}}var sep=",";if(hasInits){sep+="\n"+util.repeat(node.kind.length+1)}else{sep+=" "}print.list(node.declarations,{separator:sep});if(!t.isFor(parent)){this.semicolon()}};exports.PrivateDeclaration=function(node,print){this.push("private ");print.join(node.declarations,{separator:", "});this.semicolon()};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.space();this.push("=");this.space();print(node.init)}else{print(node.id)}}},{"../../types":121,"../../util":123}],14:[function(require,module,exports){"use strict";var each=require("lodash/collection/each");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{"lodash/collection/each":194}],15:[function(require,module,exports){"use strict";var each=require("lodash/collection/each");exports.Identifier=function(node){this.push(node.name)};exports.RestElement=exports.SpreadElement=exports.SpreadProperty=function(node,print){this.push("...");print(node.argument)};exports.VirtualPropertyExpression=function(node,print){print(node.object);this.push("::");print(node.property)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.list(props,{indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(":");this.space();print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0&&!self.format.compact)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u000A\u000D\u2028\u2029]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="number"){this.push(val+"")}else if(type==="boolean"){this.push(val?"true":"false")}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{"lodash/collection/each":194}],16:[function(require,module,exports){"use strict";module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var detectIndent=require("detect-indent");var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var extend=require("lodash/object/extend");var merge=require("lodash/object/merge");var each=require("lodash/collection/each");var util=require("../util");var n=require("./node");var t=require("../types");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normalizeOptions(code,opts);this.opts=opts;this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normalizeOptions=function(code,opts){var style=" ";if(code){var indent=detectIndent(code).indent;if(indent&&indent!==" ")style=indent}return merge({parentheses:true,comments:opts.comments==null||opts.comments,compact:false,concise:false,indent:{adjustMultilineComment:true,style:style,base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),playground:require("./generators/playground"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),flow:require("./generators/flow"),base:require("./generators/base"),jsx:require("./generators/jsx")};each(CodeGenerator.generators,function(generator){extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);var comments=[];each(ast.comments,function(comment){if(!comment._displayed)comments.push(comment)});this._printComments(comments);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.list=function(items,opts){opts=opts||{};var sep=opts.separator||", ";if(self.format.compact)sep=",";opts.separator=sep;print.join(items,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";if(parent&&parent._compact){node._compact=true}var oldConcise=this.format.concise;if(node._compact){this.format.concise=true}var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null&&!node._ignoreUserWhitespace){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent);if(!self.buffer.get())lines=0}self.newline(lines)};if(this[node.type]){var needsNoLineTermParens=n.needsParensNoLineTerminator(node,parent);var needsParens=needsNoLineTermParens||n.needsParens(node,parent);if(needsParens)this.push("(");if(needsNoLineTermParens)this.indent();this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");this[node.type](node,this.buildPrint(node),parent);if(needsNoLineTermParens){this.newline();this.dedent()}if(needsParens)this.push(")");this.map.mark(node,"end");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node of type "+JSON.stringify(node.type)+" with constructor "+JSON.stringify(node&&node.constructor.name))}this.format.concise=oldConcise};CodeGenerator.prototype.printJoin=function(print,nodes,opts){if(!nodes||!nodes.length)return;opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;each(comments,function(comment){var skip=false;each(self.ast.comments,function(origComment){if(origComment.start===comment.start){if(origComment._displayed)skip=true;origComment._displayed=true;return false}});if(skip)return;self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":121,"../util":123,"./buffer":3,"./generators/base":4,"./generators/classes":5,"./generators/comprehensions":6,"./generators/expressions":7,"./generators/flow":8,"./generators/jsx":9,"./generators/methods":10,"./generators/modules":11,"./generators/playground":12,"./generators/statements":13,"./generators/template-literals":14,"./generators/types":15,"./node":17,"./position":20,"./source-map":21,"./whitespace":22,"detect-indent":177,"lodash/collection/each":194,"lodash/object/extend":281,"lodash/object/merge":285}],17:[function(require,module,exports){"use strict";module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var each=require("lodash/collection/each");var some=require("lodash/collection/some");var find=function(obj,node,parent){if(!obj)return;var result;var types=Object.keys(obj);for(var i=0;i<types.length;i++){var type=types[i];if(t.is(type,node)){var fn=obj[type];result=fn(node,parent);if(result!=null)break}}return result};function Node(node,parent){this.parent=parent;this.node=node}Node.isUserWhitespacable=function(node){return t.isUserWhitespacable(node)};Node.needsWhitespace=function(node,parent,type){if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.needsWhitespaceBefore=function(node,parent){return Node.needsWhitespace(node,parent,"before")};Node.needsWhitespaceAfter=function(node,parent){return Node.needsWhitespace(node,parent,"after")};Node.needsParens=function(node,parent){if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){if(t.isCallExpression(node))return true;var hasCall=some(node,function(val){return t.isCallExpression(val)});if(hasCall)return true}return find(parens,node,parent)};Node.needsParensNoLineTerminator=function(node,parent){if(!parent)return false;if(!node.leadingComments||!node.leadingComments.length){return false}if(t.isYieldExpression(parent)||t.isAwaitExpression(parent)){return true}if(t.isContinueStatement(parent)||t.isBreakStatement(parent)||t.isReturnStatement(parent)||t.isThrowStatement(parent)){return true}return false};each(Node,function(fn,key){Node.prototype[key]=function(){var args=new Array(arguments.length+2);args[0]=this.node;args[1]=this.parent;for(var i=0;i<args.length;i++){args[i+2]=arguments[i]}return Node[key].apply(null,args)}})},{"../../types":121,"./parentheses":18,"./whitespace":19,"lodash/collection/each":194,"lodash/collection/some":200}],18:[function(require,module,exports){"use strict";var t=require("../../types");var each=require("lodash/collection/each");var PRECEDENCE={};each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(tier,i){each(tier,function(op){PRECEDENCE[op]=i})});exports.UpdateExpression=function(node,parent){if(t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ObjectExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false};exports.Binary=function(node,parent){if((t.isCallExpression(parent)||t.isNewExpression(parent))&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)||t.isNewExpression(parent)){if(parent.callee===node){return true}}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":121,"lodash/collection/each":194}],19:[function(require,module,exports){"use strict";var t=require("../../types");var each=require("lodash/collection/each");var map=require("lodash/collection/map");var isNumber=require("lodash/lang/isNumber");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SpreadProperty:function(node,parent){return exports.before.nodes.Property(node,parent)},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1}},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{LogicalExpression:function(node){return t.isFunction(node.left)||t.isFunction(node.right)},AssignmentExpression:function(node){if(t.isFunction(node.right)){return 1}}},list:{VariableDeclaration:function(node){return map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};each({Function:1,Class:1,For:1,ArrayExpression:{after:1},ObjectExpression:{after:1},SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(isNumber(amounts)){amounts={after:amounts,before:amounts}}each([type].concat(t.FLIPPED_ALIAS_KEYS[type]||[]),function(type){each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})})},{"../../types":121,"lodash/collection/each":194,"lodash/collection/map":198,"lodash/lang/isNumber":272}],20:[function(require,module,exports){"use strict";module.exports=Position;function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){for(var i=0;i<str.length;i++){if(str[i]==="\n"){this.line++;this.column=0}else{this.column++}}};Position.prototype.unshift=function(str){for(var i=0;i<str.length;i++){if(str[i]==="\n"){this.line--}else{this.column--}}}},{}],21:[function(require,module,exports){"use strict";module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node,type){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc[type];map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original})}},{"../types":121,"source-map":307}],22:[function(require,module,exports){"use strict";module.exports=Whitespace;var sortBy=require("lodash/collection/sortBy");function getLookupIndex(i,base,max){i+=base;if(i>=max)i-=max;return i}function Whitespace(tokens,comments){this.tokens=sortBy(tokens.concat(comments),"start");this.used={};this._lastFoundIndex=0}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;var token;for(var j=0;j<tokens.length;j++){var i=getLookupIndex(j,this._lastFoundIndex,this.tokens.length);token=tokens[i];if(node.start===token.start){startToken=tokens[i-1];endToken=token;this._lastFoundIndex=i;break}}return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;var token;for(var j=0;j<tokens.length;j++){var i=getLookupIndex(j,this._lastFoundIndex,this.tokens.length);token=tokens[i];if(node.end===token.end){startToken=token;endToken=tokens[i+1];this._lastFoundIndex=i;break}}if(endToken&&endToken.type.type==="eof"){return 1}else{var lines=this.getNewlinesBetween(startToken,endToken);if(node.type==="Line"&&!lines){return 1}else{return lines}}};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){if(!endToken||!endToken.loc)return 0;var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(typeof this.used[line]==="undefined"){this.used[line]=true;lines++}}return lines}},{"lodash/collection/sortBy":201}],23:[function(require,module,exports){"use strict";module.exports=function cloneDeep(obj){var obj2={};if(!obj)return obj2;for(var key in obj){obj2[key]=obj[key]}return obj2}},{}],24:[function(require,module,exports){var supportsColor=require("supports-color");var tokenize=require("js-tokenizer");var chalk=require("chalk");var util=require("../util");var defs={string1:"red",string2:"red",punct:["white","bold"],curly:"green",parens:["blue","bold"],square:["yellow"],name:"white",keyword:["cyan"],number:"magenta",regexp:"magenta",comment1:"grey",comment2:"grey"};var highlight=function(text){var colorize=function(str,col){if(!col)return str;if(Array.isArray(col)){col.forEach(function(col){str=chalk[col](str)})}else{str=chalk[col](str)}return str};return tokenize(text,true).map(function(str){var type=tokenize.type(str);return colorize(str,defs[type])}).join("")};module.exports=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);if(supportsColor){lines=highlight(lines)}lines=lines.split(/\r\n|[\n\r\u2028\u2029]/);var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+util.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=util.repeat(gutter.length-2);str+="|"+util.repeat(colNumber)+"^"}return str}).join("\n")}},{"../util":123,chalk:165,"js-tokenizer":187,"supports-color":318}],25:[function(require,module,exports){module.exports=function(a,b){if(a.length===0)return b.length;if(b.length===0)return a.length;var matrix=[];var i;for(i=0;i<=b.length;i++){matrix[i]=[i]}var j;for(j=0;j<=a.length;j++){matrix[0][j]=j}for(i=1;i<=b.length;i++){for(j=1;j<=a.length;j++){if(b.charAt(i-1)==a.charAt(j-1)){matrix[i][j]=matrix[i-1][j-1]}else{matrix[i][j]=Math.min(matrix[i-1][j-1]+1,Math.min(matrix[i][j-1]+1,matrix[i-1][j]+1))}}}return matrix[b.length][a.length]}},{}],26:[function(require,module,exports){var t=require("../types");module.exports=function(ast,comments,tokens){if(ast&&ast.type==="Program"){return t.file(ast,comments||[],tokens||[])}else{throw new Error("Not a valid ast?")}}},{"../types":121}],27:[function(require,module,exports){"use strict";module.exports=function(){return Object.create(null)}},{}],28:[function(require,module,exports){var normalizeAst=require("./normalize-ast");var estraverse=require("estraverse");var codeFrame=require("./code-frame");var acorn=require("acorn-6to5");
module.exports=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowImportExportEverywhere:opts.allowImportExportEverywhere,allowReturnOutsideFunction:!opts._anal,ecmaVersion:opts.experimental?7:6,playground:opts.playground,strictMode:opts.strictMode,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=normalizeAst(ast,comments,tokens);if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=codeFrame(code,loc.line,loc.column+1);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}}},{"./code-frame":24,"./normalize-ast":26,"acorn-6to5":1,estraverse:180}],29:[function(require,module,exports){"use strict";module.exports=function toFastProperties(obj){function f(){}f.prototype=obj;return f;eval(obj)}},{}],30:[function(require,module,exports){var util=require("util");exports.messages={tailCallReassignmentDeopt:"Function reference has been reassigned so it's probably be dereferenced so we can't optimise this with confidence",JSXNamespacedTags:"Namespace tags are not supported. ReactJSX is not XML.",classesIllegalBareSuper:"Illegal use of bare super",classesIllegalSuperCall:"Direct super call is illegal in non-constructor, use super.$1() instead",classesIllegalConstructorKind:"Illegal kind for constructor method",scopeDuplicateDeclaration:"Duplicate declaration $1",undeclaredVariable:"Reference to undeclared variable $1",undeclaredVariableSuggestion:"Reference to undeclared variable $1 - did you mean $2?",settersInvalidParamLength:"Setters must have only one parameter",noAssignmentsInForHead:"No assignments allowed in for-in/of head",expectedMemberExpressionOrIdentifier:"Expected type MemeberExpression or Identifier",invalidParentForThisNode:"We don't know how to handle this node within the current parent - please open an issue",readOnly:"$1 is read-only",modulesIllegalExportName:"Illegal export $1",unknownForHead:"Unknown node type $1 in ForStatement",didYouMean:"Did you mean $1?"};exports.get=function(key){var msg=exports.messages[key];if(!msg)throw new ReferenceError("Unknown message `"+key+"`");var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i])}args=exports.parseArgs(args);return msg.replace(/\$(\d+)/g,function(str,i){return args[--i]})};exports.parseArgs=function(args){return args.map(function(val){if(val!=null&&val.inspect){return val.inspect()}else{try{return JSON.stringify(val)||val+""}catch(e){return util.inspect(val)}}})}},{util:164}],31:[function(require,module,exports){"use strict";var extend=require("lodash/object/extend");var t=require("./types");var estraverse=require("estraverse");extend(estraverse.VisitorKeys,t.VISITOR_KEYS);var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;def("File").bases("Node").build("program").field("program",def("Program"));def("AssignmentPattern").bases("Pattern").build("left","right").field("left",def("Pattern")).field("right",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));def("RestElement").bases("Pattern").build("argument").field("argument",def("expression"));def("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression")));def("PrivateDeclaration").bases("Declaration").build("declarations").field("declarations",[def("Identifier")]);def("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("arguments",[def("Expression")]);def("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);types.finalize()},{"./types":121,"ast-types":137,estraverse:180,"lodash/object/extend":281}],32:[function(require,module,exports){"use strict";module.exports=File;var SHEBANG_REGEX=/^\#\!.*/;var isFunction=require("lodash/lang/isFunction");var transform=require("./index");var generate=require("../generation");var defaults=require("lodash/object/defaults");var includes=require("lodash/collection/includes");var clone=require("../helpers/clone");var parse=require("../helpers/parse");var Scope=require("../traversal/scope");var util=require("../util");var path=require("path");var each=require("lodash/collection/each");var t=require("../types");function File(opts){this.dynamicImportedNoDefault=[];this.dynamicImportIds={};this.dynamicImported=[];this.dynamicImports=[];this.dynamicData={};this.data={};this.lastStatements=[];this.opts=this.normalizeOptions(opts);this.ast={};this.buildTransformers()}File.helpers=["inherits","defaults","prototype-properties","apply-constructor","tagged-template-literal","tagged-template-literal-loose","interop-require","to-array","to-consumable-array","sliced-to-array","object-without-properties","has-own","slice","bind","define-property","async-to-generator","interop-require-wildcard","typeof","extends","get","set","class-call-check","object-destructuring-empty","temporal-undefined","temporal-assert-defined","tail-call"];File.validOptions=["filename","filenameRelative","blacklist","whitelist","loose","optional","modules","sourceMap","sourceMapName","sourceFileName","sourceRoot","moduleRoot","moduleIds","comments","reactCompat","keepModuleIdExtensions","code","ast","format","playground","experimental","resolveModuleSource","runtime","auxilaryComment","ignore","only","extensions","accept"];File.prototype.normalizeOptions=function(opts){opts=clone(opts);for(var key in opts){if(key[0]!=="_"&&File.validOptions.indexOf(key)<0){throw new ReferenceError("Unknown option: "+key)}}defaults(opts,{keepModuleIdExtensions:false,resolveModuleSource:null,auxilaryComment:"",experimental:false,reactCompat:false,playground:false,whitespace:true,moduleIds:false,blacklist:[],whitelist:[],sourceMap:false,optional:[],comments:true,filename:"unknown",modules:"common",runtime:false,loose:[],code:true,ast:true});opts.filename=util.normalisePathSeparator(opts.filename);if(opts.sourceRoot){opts.sourceRoot=util.normalisePathSeparator(opts.sourceRoot)}opts.basename=path.basename(opts.filename,path.extname(opts.filename));opts.blacklist=util.arrayify(opts.blacklist);opts.whitelist=util.arrayify(opts.whitelist);opts.optional=util.arrayify(opts.optional);opts.loose=util.arrayify(opts.loose);if(includes(opts.loose,"all")||includes(opts.loose,true)){opts.loose=Object.keys(transform.transformers)}defaults(opts,{moduleRoot:opts.sourceRoot});defaults(opts,{sourceRoot:opts.moduleRoot});defaults(opts,{filenameRelative:opts.filename});defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.playground){opts.experimental=true}if(opts.runtime){this.set("runtimeIdentifier",t.identifier("to5Runtime"))}opts.blacklist=transform._ensureTransformerNames("blacklist",opts.blacklist);opts.whitelist=transform._ensureTransformerNames("whitelist",opts.whitelist);opts.optional=transform._ensureTransformerNames("optional",opts.optional);opts.loose=transform._ensureTransformerNames("loose",opts.loose);if(opts.reactCompat){opts.optional.push("reactCompat");console.error("The reactCompat option has been moved into the optional transformer "+"`reactCompat` - backwards compatibility will be removed in v4.0.0")}var ensureEnabled=function(key){var namespace=transform.transformerNamespaces[key];if(namespace==="es7")opts.experimental=true;if(namespace==="playground")opts.playground=true};each(opts.whitelist,ensureEnabled);each(opts.optional,ensureEnabled);return opts};File.prototype.isLoose=function(key){return includes(this.opts.loose,key)};File.prototype.buildTransformers=function(){var file=this;var transformers={};var secondaryStack=[];var stack=[];each(transform.transformers,function(transformer,key){var pass=transformers[key]=transformer.buildPass(file);if(pass.canRun(file)){stack.push(pass);if(transformer.secondPass){secondaryStack.push(pass)}if(transformer.manipulateOptions){transformer.manipulateOptions(file.opts,file)}}});this.transformerStack=stack.concat(secondaryStack);this.transformers=transformers};File.prototype.debug=function(msg){var parts=this.opts.filename;if(msg)parts+=": "+msg;util.debug(parts)};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=isFunction(type)?type:transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("Unknown module formatter type "+JSON.stringify(type))}return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.set=function(key,val){return this.data[key]=val};File.prototype.setDynamic=function(key,fn){this.dynamicData[key]=fn};File.prototype.get=function(key){var data=this.data[key];if(data){return data}else{var dynamic=this.dynamicData[key];if(dynamic){return this.set(key,dynamic())}}};File.prototype.addImport=function(source,name,noDefault){name=name||source;var id=this.dynamicImportIds[name];if(!id){id=this.dynamicImportIds[name]=this.scope.generateUidIdentifier(name);var specifiers=[t.importSpecifier(t.identifier("default"),id)];var declar=t.importDeclaration(specifiers,t.literal(source));declar._blockHoist=3;this.dynamicImported.push(declar);if(noDefault)this.dynamicImportedNoDefault.push(declar);this.moduleFormatter.importSpecifier(specifiers[0],declar,this.dynamicImports)}return id};File.prototype.isConsequenceExpressionStatement=function(node){return t.isExpressionStatement(node)&&this.lastStatements.indexOf(node)>=0};File.prototype.attachAuxilaryComment=function(node){var comment=this.opts.auxilaryComment;if(comment){node.leadingComments=node.leadingComments||[];node.leadingComments.push({type:"Line",value:" "+comment})}return node};File.prototype.addHelper=function(name){if(!includes(File.helpers,name)){throw new ReferenceError("Unknown helper "+name)}var program=this.ast.program;var declar=program._declarations&&program._declarations[name];if(declar)return declar.id;var runtime=this.get("runtimeIdentifier");if(runtime){name=t.identifier(t.toIdentifier(name));return t.memberExpression(runtime,name)}else{var ref=util.template(name);ref._compact=true;var uid=this.scope.generateUidIdentifier(name);this.scope.push({key:name,id:uid,init:ref});return uid}};File.prototype.logDeopt=function(){};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.addCode=function(code){code=(code||"")+"";this.code=code;return this.parseShebang(code)};File.prototype.parse=function(code){var self=this;code=this.addCode(code);var opts=this.opts;opts.allowImportExportEverywhere=this.isLoose("es6.modules");return parse(opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){this.debug();this.ast=ast;this.lastStatements=t.getLastStatements(ast.program);this.scope=new Scope(ast.program,ast,null,this);var modFormatter=this.moduleFormatter=this.getModuleFormatter(this.opts.modules);if(modFormatter.init&&this.transformers["es6.modules"].canRun()){modFormatter.init()}this.checkNode(ast);this.call("pre");each(this.transformerStack,function(pass){pass.transform()});this.call("post")};File.prototype.call=function(key){var stack=this.transformerStack;for(var i=0;i<stack.length;i++){var transformer=stack[i].transformer;if(transformer[key]){transformer[key](this)}}};var checkTransformerVisitor={enter:function(node,parent,scope,state){checkNode(state.stack,node,scope)}};var checkNode=function(stack,node,scope){each(stack,function(pass){if(pass.shouldRun)return;pass.checkNode(node,scope)})};File.prototype.checkNode=function(node,scope){var stack=this.transformerStack;scope=scope||this.scope;checkNode(stack,node,scope);scope.traverse(node,checkTransformerVisitor,{stack:stack})};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;var result={code:"",map:null,ast:null};if(opts.ast)result.ast=ast;if(!opts.code)return result;var _result=generate(ast,opts,this.code);result.code=_result.code;result.map=_result.map;if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map);result.map=null}return result}},{"../generation":16,"../helpers/clone":23,"../helpers/parse":28,"../traversal/scope":118,"../types":121,"../util":123,"./index":44,"lodash/collection/each":194,"lodash/collection/includes":197,"lodash/lang/isFunction":270,"lodash/object/defaults":280,path:147}],33:[function(require,module,exports){"use strict";var explode=require("./explode-assignable-expression");var t=require("../../types");module.exports=function(exports,opts){var isAssignment=function(node){return node.operator===opts.operator+"="};var buildAssignment=function(left,right){return t.assignmentExpression("=",left,right)};exports.ExpressionStatement=function(node,parent,scope,file){if(file.isConsequenceExpressionStatement(node))return;var expr=node.expression;if(!isAssignment(expr))return;var nodes=[];var exploded=explode(expr.left,nodes,file,scope,true);nodes.push(t.expressionStatement(buildAssignment(exploded.ref,opts.build(exploded.uid,expr.right))));return nodes};exports.AssignmentExpression=function(node,parent,scope,file){if(!isAssignment(node))return;var nodes=[];var exploded=explode(node.left,nodes,file,scope);nodes.push(buildAssignment(exploded.ref,opts.build(exploded.uid,node.right)));return t.toSequenceExpression(nodes,scope)};exports.BinaryExpression=function(node){if(node.operator!==opts.operator)return;return opts.build(node.left,node.right)}}},{"../../types":121,"./explode-assignable-expression":38}],34:[function(require,module,exports){"use strict";var t=require("../../types");module.exports=function build(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("let",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))}},{"../../types":121}],35:[function(require,module,exports){"use strict";var explode=require("./explode-assignable-expression");var t=require("../../types");module.exports=function(exports,opts){var buildAssignment=function(left,right){return t.assignmentExpression("=",left,right)};exports.ExpressionStatement=function(node,parent,scope,file){if(file.isConsequenceExpressionStatement(node))return;var expr=node.expression;if(!opts.is(expr,file))return;var nodes=[];var exploded=explode(expr.left,nodes,file,scope);nodes.push(t.ifStatement(opts.build(exploded.uid,file),t.expressionStatement(buildAssignment(exploded.ref,expr.right))));return nodes};exports.AssignmentExpression=function(node,parent,scope,file){if(!opts.is(node,file))return;var nodes=[];var exploded=explode(node.left,nodes,file,scope);nodes.push(t.logicalExpression("&&",opts.build(exploded.uid,file),buildAssignment(exploded.ref,node.right)));nodes.push(exploded.ref);return t.toSequenceExpression(nodes,scope)}}},{"../../types":121,"./explode-assignable-expression":38}],36:[function(require,module,exports){"use strict";var isString=require("lodash/lang/isString");var messages=require("../../messages");var esutils=require("esutils");var react=require("./react");var t=require("../../types");module.exports=function(exports,opts){exports.check=function(node){if(t.isJSX(node))return true;if(react.isCreateClass(node))return true;return false};exports.JSXIdentifier=function(node,parent){if(node.name==="this"&&t.isReferenced(node,parent)){return t.thisExpression()}else if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.JSXNamespacedName=function(node,parent,scope,file){throw file.errorWithNode(node,messages.get("JSXNamespacedTags"))};exports.JSXMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.JSXExpressionContainer=function(node){return node.expression};exports.JSXAttribute={exit:function(node){var value=node.value||t.literal(true);if(t.isLiteral(value)&&isString(value.value)){value.value=value.value.replace(/\n\s+/g," ")}return t.inherits(t.property("init",node.name,value),node)}};exports.JSXOpeningElement={exit:function(node,parent,scope,file){var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}var state={tagExpr:tagExpr,tagName:tagName,args:args};if(opts.pre){opts.pre(state)}var attribs=node.attributes;if(attribs.length){attribs=buildJSXOpeningElementAttributes(attribs,file)}else{attribs=t.literal(null)}args.push(attribs);if(opts.post){opts.post(state)}return state.call||t.callExpression(state.callee,args)}};var buildJSXOpeningElementAttributes=function(attribs,file){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(attribs.length){var prop=attribs.shift();if(t.isJSXSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){attribs=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}attribs=t.callExpression(file.addHelper("extends"),objs)}return attribs};exports.JSXElement={exit:function(node){var callExpr=node.openingElement;for(var i=0;i<node.children.length;i++){var child=node.children[i];if(t.isLiteral(child)&&typeof child.value==="string"){cleanJSXElementLiteralChild(child,callExpr.arguments);continue}else if(t.isJSXEmptyExpression(child)){continue}callExpr.arguments.push(child)}callExpr.arguments=flatten(callExpr.arguments);if(callExpr.arguments.length>=3){callExpr._prettyCall=true}return t.inherits(callExpr,node)}};var isStringLiteral=function(node){return t.isLiteral(node)&&isString(node.value)};var flatten=function(args){var flattened=[];var last;for(var i=0;i<args.length;i++){var arg=args[i];if(isStringLiteral(arg)&&isStringLiteral(last)){last.value+=arg.value}else{last=arg;flattened.push(arg)}}return flattened};var cleanJSXElementLiteralChild=function(child,args){var lines=child.value.split(/\r\n|\n|\r/);var lastNonEmptyLine=0;var i;for(i=0;i<lines.length;i++){if(lines[i].match(/[^ \t]/)){lastNonEmptyLine=i}}for(i=0;i<lines.length;i++){var line=lines[i];var isFirstLine=i===0;var isLastLine=i===lines.length-1;var isLastNonEmptyLine=i===lastNonEmptyLine;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){if(!isLastNonEmptyLine){trimmedLine+=" "}args.push(t.literal(trimmedLine))}}};var addDisplayName=function(id,call){var props=call.arguments[0].properties;var safe=true;for(var i=0;i<props.length;i++){var prop=props[i];if(t.isIdentifier(prop.key,{name:"displayName"})){safe=false;break}}if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.ExportDeclaration=function(node,parent,scope,file){if(node.default&&react.isCreateClass(node.declaration)){addDisplayName(file.opts.basename,node.declaration)}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)&&react.isCreateClass(right)){addDisplayName(left.name,right)}}}},{"../../messages":30,"../../types":121,"./react":40,esutils:184,"lodash/lang/isString":276}],37:[function(require,module,exports){var cloneDeep=require("lodash/lang/cloneDeep");var traverse=require("../../traversal");var clone=require("lodash/lang/clone");var each=require("lodash/collection/each");var has=require("lodash/object/has");var t=require("../../types");exports.push=function(mutatorMap,key,kind,computed,value){var alias;if(t.isIdentifier(key)){alias=key.name;if(computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(cloneDeep(key)))}var map;if(has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(computed){map._computed=true}map[kind]=value};exports.build=function(mutatorMap){var objExpr=t.objectExpression([]);each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);if(!map.get&&!map.set){map.writable=t.literal(true)}if(map.enumerable===false){delete map.enumerable}else{map.enumerable=t.literal(true)}map.configurable=t.literal(true);each(map,function(node,key){if(key[0]==="_")return;node=clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr}},{"../../traversal":116,"../../types":121,"lodash/collection/each":194,"lodash/lang/clone":264,"lodash/lang/cloneDeep":265,"lodash/object/has":282}],38:[function(require,module,exports){"use strict";var t=require("../../types");var getObjRef=function(node,nodes,file,scope){var ref;if(t.isIdentifier(node)){if(scope.hasBinding(node.name)){return node}else{ref=node}}else if(t.isMemberExpression(node)){ref=node.object;if(t.isIdentifier(ref)&&scope.hasGlobal(ref.name)){return ref}}else{throw new Error("We can't explode this node type "+node.type)}var temp=scope.generateUidBasedOnNode(ref);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,ref)]));return temp};var getPropRef=function(node,nodes,file,scope){var prop=node.property;var key=t.toComputedKey(node,prop);if(t.isLiteral(key))return key;var temp=scope.generateUidBasedOnNode(prop);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,prop)]));return temp};module.exports=function(node,nodes,file,scope,allowedSingleIdent){var obj;if(t.isIdentifier(node)&&allowedSingleIdent){obj=node}else{obj=getObjRef(node,nodes,file,scope)}var ref,uid;if(t.isIdentifier(node)){ref=node;uid=obj}else{var prop=getPropRef(node,nodes,file,scope);var computed=node.computed||t.isLiteral(prop);uid=ref=t.memberExpression(obj,prop,computed)}return{uid:uid,ref:ref}}},{"../../types":121}],39:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");var visitor={enter:function(node,parent,scope,state){if(!t.isIdentifier(node,{name:state.id}))return;if(!t.isReferenced(node,parent))return;var localDeclar=scope.getBindingIdentifier(state.id);if(localDeclar!==state.outerDeclar)return;state.selfReference=true;this.stop()}};exports.property=function(node,file,scope){var key=t.toComputedKey(node,node.key);if(!t.isLiteral(key))return node;var id=t.toIdentifier(key.value);key=t.identifier(id);var state={id:id,selfReference:false,outerDeclar:scope.getBindingIdentifier(id)};scope.traverse(node,visitor,state);var method=node.value;if(state.selfReference){var templateName="property-method-assignment-wrapper";if(method.generator)templateName+="-generator";node.value=util.template(templateName,{FUNCTION:method,FUNCTION_ID:key,FUNCTION_KEY:scope.generateUidIdentifier(id),WRAPPER_KEY:scope.generateUidIdentifier(id+"Wrapper")})}else{method.id=key}}},{"../../types":121,"../../util":123}],40:[function(require,module,exports){var t=require("../../types");var isCreateClassCallExpression=t.buildMatchMemberExpression("React.createClass");exports.isCreateClass=function(node){if(!node||!t.isCallExpression(node))return false;if(!isCreateClassCallExpression(node.callee))return false;var args=node.arguments;if(args.length!==1)return false;var first=args[0];if(!t.isObjectExpression(first))return false;return true};exports.isReactComponent=t.buildMatchMemberExpression("React.Component");exports.isCompatTag=function(tagName){return tagName&&/^[a-z]|\-/.test(tagName)}},{"../../types":121}],41:[function(require,module,exports){"use strict";var t=require("../../types");var visitor={enter:function(node){if(t.isFunction(node))this.skip();if(t.isAwaitExpression(node)){node.type="YieldExpression";if(node.all){node.all=false;node.argument=t.callExpression(t.memberExpression(t.identifier("Promise"),t.identifier("all")),[node.argument])}}}};module.exports=function(node,callId,scope){node.async=false;node.generator=true;scope.traverse(node,visitor);var call=t.callExpression(callId,[node]);var id=node.id;delete node.id;if(t.isFunctionDeclaration(node)){var declar=t.variableDeclaration("let",[t.variableDeclarator(id,call)]);declar._blockHoist=true;return declar}else{return call}}},{"../../types":121}],42:[function(require,module,exports){"use strict";module.exports=ReplaceSupers;var messages=require("../../messages");var t=require("../../types");function ReplaceSupers(opts,inClass){this.topLevelThisReference=opts.topLevelThisReference;this.methodNode=opts.methodNode;this.className=opts.className;this.superName=opts.superName;this.isStatic=opts.isStatic;this.hasSuper=false;this.inClass=inClass;this.isLoose=opts.isLoose;this.scope=opts.scope;this.file=opts.file}ReplaceSupers.prototype.setSuperProperty=function(property,value,isComputed,thisExpression){return t.callExpression(this.file.addHelper("set"),[t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getPrototypeOf")),[this.isStatic?this.className:t.memberExpression(this.className,t.identifier("prototype"))]),isComputed?property:t.literal(property.name),value,thisExpression])};ReplaceSupers.prototype.getSuperProperty=function(property,isComputed,thisExpression){return t.callExpression(this.file.addHelper("get"),[t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getPrototypeOf")),[this.isStatic?this.className:t.memberExpression(this.className,t.identifier("prototype"))]),isComputed?property:t.literal(property.name),thisExpression])};ReplaceSupers.prototype.replace=function(){this.traverseLevel(this.methodNode.value,true)};var visitor={enter:function(node,parent,scope,state){var topLevel=state.topLevel;var self=state.self;if(t.isFunction(node)&&!t.isArrowFunctionExpression(node)){self.traverseLevel(node,false);return this.skip()}if(t.isProperty(node,{method:true})||t.isMethodDefinition(node)){return this.skip()}var getThisReference=topLevel?t.thisExpression:self.getThisReference.bind(self);var callback=self.specHandle;if(self.isLoose)callback=self.looseHandle;return callback.call(self,getThisReference,node,parent)}};ReplaceSupers.prototype.traverseLevel=function(node,topLevel){var state={self:this,topLevel:topLevel};this.scope.traverse(node,visitor,state)};ReplaceSupers.prototype.getThisReference=function(){if(this.topLevelThisReference){return this.topLevelThisReference}else{var ref=this.topLevelThisReference=this.scope.generateUidIdentifier("this");this.methodNode.value.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(this.topLevelThisReference,t.thisExpression())]));return ref}};ReplaceSupers.prototype.getLooseSuperProperty=function(id,parent){var methodNode=this.methodNode;var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};ReplaceSupers.prototype.looseHandle=function(getThisReference,node,parent){if(t.isIdentifier(node,{name:"super"})){this.hasSuper=true;return this.getLooseSuperProperty(node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;this.hasSuper=true;t.appendToMemberExpression(callee,t.identifier("call"));node.arguments.unshift(getThisReference())}};ReplaceSupers.prototype.specHandle=function(getThisReference,node,parent){var methodNode=this.methodNode;var property;var computed;var args;var thisReference;if(isIllegalBareSuper(node,parent)){throw this.file.errorWithNode(node,messages.get("classesIllegalBareSuper"))}if(t.isCallExpression(node)){var callee=node.callee;if(isSuper(callee,node)){property=methodNode.key;computed=methodNode.computed;args=node.arguments;if(methodNode.key.name!=="constructor"||!this.inClass){var methodName=methodNode.key.name||"METHOD_NAME";throw this.file.errorWithNode(node,messages.get("classesIllegalSuperCall",methodName))}}else if(t.isMemberExpression(callee)&&isSuper(callee.object,callee)){property=callee.property;computed=callee.computed;args=node.arguments}}else if(t.isMemberExpression(node)&&isSuper(node.object,node)){property=node.property;computed=node.computed}else if(t.isAssignmentExpression(node)&&isSuper(node.left.object,node.left)&&methodNode.kind==="set"){this.hasSuper=true;return this.setSuperProperty(node.left.property,node.right,node.left.computed,getThisReference())}if(!property)return;this.hasSuper=true;thisReference=getThisReference();var superProperty=this.getSuperProperty(property,computed,thisReference);if(args){if(args.length===1&&t.isSpreadElement(args[0])){return t.callExpression(t.memberExpression(superProperty,t.identifier("apply")),[thisReference,args[0].argument])}else{return t.callExpression(t.memberExpression(superProperty,t.identifier("call")),[thisReference].concat(args))}}else{return superProperty}};var isIllegalBareSuper=function(node,parent){if(!isSuper(node,parent))return false;if(t.isMemberExpression(parent,{computed:false}))return false;if(t.isCallExpression(parent,{callee:node}))return false;return true};var isSuper=function(node,parent){return t.isIdentifier(node,{name:"super"})&&t.isReferenced(node,parent)}},{"../../messages":30,"../../types":121}],43:[function(require,module,exports){"use strict";var t=require("../../types");exports.has=function(node){var first=node.body[0];return t.isExpressionStatement(first)&&t.isLiteral(first.expression,{value:"use strict"})};exports.wrap=function(node,callback){var useStrictNode;if(exports.has(node)){useStrictNode=node.body.shift()}callback();if(useStrictNode){node.body.unshift(useStrictNode)}}},{"../../types":121}],44:[function(require,module,exports){"use strict";module.exports=transform;var normalizeAst=require("../helpers/normalize-ast");var Transformer=require("./transformer");var object=require("../helpers/object");var File=require("./file");var each=require("lodash/collection/each");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform.fromAst=function(ast,code,opts){ast=normalizeAst(ast);var file=new File(opts);file.addCode(code);file.transform(ast);return file.generate()};transform._ensureTransformerNames=function(type,rawKeys){var keys=[];for(var i=0;i<rawKeys.length;i++){var key=rawKeys[i];var deprecatedKey=transform.deprecatedTransformerMap[key];if(deprecatedKey){console.error("The transformer "+key+" has been renamed to "+deprecatedKey+" in v3.0.0 - backwards compatibilty will be removed 4.0.0");rawKeys.push(deprecatedKey)
}else if(transform.transformers[key]){keys.push(key)}else if(transform.namespaces[key]){keys=keys.concat(transform.namespaces[key])}else{throw new ReferenceError("Unknown transformer "+key+" specified in "+type+" - "+"transformer key names have been changed in 3.0.0 see "+"the changelog for more info "+"https://github.com/6to5/6to5/blob/master/CHANGELOG.md#300")}}return keys};transform.transformerNamespaces=object();transform.transformers=object();transform.namespaces=object();transform.deprecatedTransformerMap=require("./transformers/deprecated");transform.moduleFormatters=require("./modules");var rawTransformers=require("./transformers");each(rawTransformers,function(transformer,key){var namespace=key.split(".")[0];transform.namespaces[namespace]=transform.namespaces[namespace]||[];transform.namespaces[namespace].push(key);transform.transformerNamespaces[key]=namespace;transform.transformers[key]=new Transformer(key,transformer)})},{"../helpers/normalize-ast":26,"../helpers/object":27,"./file":32,"./modules":53,"./transformer":58,"./transformers":84,"./transformers/deprecated":59,"lodash/collection/each":194}],45:[function(require,module,exports){"use strict";module.exports=DefaultFormatter;var messages=require("../../messages");var extend=require("lodash/object/extend");var object=require("../../helpers/object");var util=require("../../util");var t=require("../../types");function DefaultFormatter(file){this.scope=file.scope;this.file=file;this.ids=object();this.hasNonDefaultExports=false;this.hasLocalExports=false;this.hasLocalImports=false;this.localImportOccurences=object();this.localExports=object();this.localImports=object();this.getLocalExports();this.getLocalImports();this.remapAssignments()}DefaultFormatter.prototype.doDefaultExportInterop=function(node){return node.default&&!this.noInteropRequireExport&&!this.hasNonDefaultExports};DefaultFormatter.prototype.bumpImportOccurences=function(node){var source=node.source.value;var occurs=this.localImportOccurences;occurs[source]=occurs[source]||0;occurs[source]+=node.specifiers.length};var exportsVisitor={enter:function(node,parent,scope,formatter){var declar=node&&node.declaration;if(t.isExportDeclaration(node)){formatter.hasLocalImports=true;if(declar&&t.isStatement(declar)){extend(formatter.localExports,t.getBindingIdentifiers(declar))}if(!node.default){formatter.hasNonDefaultExports=true}if(node.source){formatter.bumpImportOccurences(node)}}}};DefaultFormatter.prototype.getLocalExports=function(){this.file.scope.traverse(this.file.ast,exportsVisitor,this)};var importsVisitor={enter:function(node,parent,scope,formatter){if(t.isImportDeclaration(node)){formatter.hasLocalImports=true;extend(formatter.localImports,t.getBindingIdentifiers(node));formatter.bumpImportOccurences(node)}}};DefaultFormatter.prototype.getLocalImports=function(){this.file.scope.traverse(this.file.ast,importsVisitor,this)};var remapVisitor={enter:function(node,parent,scope,formatter){if(t.isUpdateExpression(node)&&formatter.isLocalReference(node.argument,scope)){this.skip();var assign=t.assignmentExpression(node.operator[0]+"=",node.argument,t.literal(1));var remapped=formatter.remapExportAssignment(assign);if(t.isExpressionStatement(parent)||node.prefix){return remapped}var nodes=[];nodes.push(remapped);var operator;if(node.operator==="--"){operator="+"}else{operator="-"}nodes.push(t.binaryExpression(operator,node.argument,t.literal(1)));return t.sequenceExpression(nodes)}if(t.isAssignmentExpression(node)&&formatter.isLocalReference(node.left,scope)){this.skip();return formatter.remapExportAssignment(node)}}};DefaultFormatter.prototype.remapAssignments=function(){if(this.hasLocalImports){this.file.scope.traverse(this.file.ast,remapVisitor,this)}};DefaultFormatter.prototype.isLocalReference=function(node){var localImports=this.localImports;return t.isIdentifier(node)&&localImports[node.name]&&localImports[node.name]!==node};DefaultFormatter.prototype.remapExportAssignment=function(node){return t.assignmentExpression("=",node.left,t.assignmentExpression(node.operator,t.memberExpression(t.identifier("exports"),node.left),node.right))};DefaultFormatter.prototype.isLocalReference=function(node,scope){var localExports=this.localExports;var name=node.name;return t.isIdentifier(node)&&localExports[name]&&localExports[name]===scope.getBindingIdentifier(name)};DefaultFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}if(!opts.keepModuleIdExtensions){filenameRelative=filenameRelative.replace(/\.(\w*?)$/,"")}moduleName+=filenameRelative;moduleName=moduleName.replace(/\\/g,"/");return moduleName};DefaultFormatter.prototype._pushStatement=function(ref,nodes){if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}return ref};DefaultFormatter.prototype._hoistExport=function(declar,assign,priority){if(t.isFunctionDeclaration(declar)){assign._blockHoist=priority||2}return assign};DefaultFormatter.prototype.getExternalReference=function(node,nodes){var ids=this.ids;var id=node.source.value;if(ids[id]){return ids[id]}else{return this.ids[id]=this._getExternalReference(node,nodes)}};DefaultFormatter.prototype.checkExportIdentifier=function(node){if(t.isIdentifier(node,{name:"__esModule"})){throw this.file.errorWithNode(node,messages.get("modulesIllegalExportName",node.name))}};DefaultFormatter.prototype.exportSpecifier=function(specifier,node,nodes){if(node.source){var ref=this.getExternalReference(node,nodes);if(t.isExportBatchSpecifier(specifier)){nodes.push(this.buildExportsWildcard(ref,node))}else{if(t.isSpecifierDefault(specifier)&&!this.noInteropRequireExport){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}else{ref=t.memberExpression(ref,t.getSpecifierId(specifier))}nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier),ref,node))}}else{nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier),specifier.id,node))}};DefaultFormatter.prototype.buildExportsWildcard=function(objectIdentifier){return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"),[t.identifier("exports"),t.callExpression(this.file.addHelper("interop-require-wildcard"),[objectIdentifier])]))};DefaultFormatter.prototype.buildExportsAssignment=function(id,init){this.checkExportIdentifier(id);return util.template("exports-assign",{VALUE:init,KEY:id},true)};DefaultFormatter.prototype.exportDeclaration=function(node,nodes){var declar=node.declaration;var id=declar.id;if(node.default){id=t.identifier("default")}var assign;if(t.isVariableDeclaration(declar)){for(var i=0;i<declar.declarations.length;i++){var decl=declar.declarations[i];decl.init=this.buildExportsAssignment(decl.id,decl.init,node).expression;var newDeclar=t.variableDeclaration(declar.kind,[decl]);if(i===0)t.inherits(newDeclar,declar);nodes.push(newDeclar)}}else{var ref=declar;if(t.isFunctionDeclaration(declar)||t.isClassDeclaration(declar)){ref=declar.id;nodes.push(declar)}assign=this.buildExportsAssignment(id,ref,node);nodes.push(assign);this._hoistExport(declar,assign)}}},{"../../helpers/object":27,"../../messages":30,"../../types":121,"../../util":123,"lodash/object/extend":281}],46:[function(require,module,exports){"use strict";var util=require("../../util");module.exports=function(Parent){var Constructor=function(){this.noInteropRequireExport=true;Parent.apply(this,arguments)};util.inherits(Constructor,Parent);return Constructor}},{"../../util":123}],47:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./amd"))},{"./_strict":46,"./amd":48}],48:[function(require,module,exports){"use strict";module.exports=AMDFormatter;var DefaultFormatter=require("./_default");var CommonFormatter=require("./common");var includes=require("lodash/collection/includes");var values=require("lodash/object/values");var util=require("../../util");var t=require("../../types");function AMDFormatter(){CommonFormatter.apply(this,arguments)}util.inherits(AMDFormatter,DefaultFormatter);AMDFormatter.prototype.init=CommonFormatter.prototype.init;AMDFormatter.prototype.buildDependencyLiterals=function(){var names=[];for(var name in this.ids){names.push(t.literal(name))}return names};AMDFormatter.prototype.transform=function(program){var body=program.body;var names=[t.literal("exports")];if(this.passModuleArg)names.push(t.literal("module"));names=names.concat(this.buildDependencyLiterals());names=t.arrayExpression(names);var params=values(this.ids);if(this.passModuleArg)params.unshift(t.identifier("module"));params.unshift(t.identifier("exports"));var container=t.functionExpression(null,params,t.blockStatement(body));var defineArgs=[names,container];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var call=t.callExpression(t.identifier("define"),defineArgs);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){if(this.file.opts.moduleIds){return DefaultFormatter.prototype.getModuleName.apply(this,arguments)}else{return null}};AMDFormatter.prototype._getExternalReference=function(node){return this.scope.generateUidIdentifier(node.source.value)};AMDFormatter.prototype.importDeclaration=function(node){this.getExternalReference(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var ref=this.getExternalReference(node);if(includes(this.file.dynamicImportedNoDefault,node)){this.ids[node.source.value]=ref}else if(t.isImportBatchSpecifier(specifier)){}else if(!includes(this.file.dynamicImported,node)&&t.isSpecifierDefault(specifier)&&!this.noInteropRequireImport){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}else{ref=t.memberExpression(ref,t.getSpecifierId(specifier),false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportDeclaration=function(node){if(this.doDefaultExportInterop(node)){this.passModuleArg=true}CommonFormatter.prototype.exportDeclaration.apply(this,arguments)}},{"../../types":121,"../../util":123,"./_default":45,"./common":51,"lodash/collection/includes":197,"lodash/object/values":286}],49:[function(require,module,exports){"use strict";module.exports=CommonStandardFormatter;var CommonStrictFormatter=require("./common-strict");var util=require("../../util");function CommonStandardFormatter(){this.noInteropRequireImport=true;CommonStrictFormatter.apply(this,arguments)}util.inherits(CommonStandardFormatter,CommonStrictFormatter)},{"../../util":123,"./common-strict":50}],50:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./common"))},{"./_strict":46,"./common":51}],51:[function(require,module,exports){"use strict";module.exports=CommonJSFormatter;var DefaultFormatter=require("./_default");var includes=require("lodash/collection/includes");var util=require("../../util");var t=require("../../types");function CommonJSFormatter(){DefaultFormatter.apply(this,arguments)}util.inherits(CommonJSFormatter,DefaultFormatter);CommonJSFormatter.prototype.init=function(){var file=this.file;var scope=file.scope;scope.rename("module");if(!this.noInteropRequireImport&&this.hasNonDefaultExports){file.ast.program.body.push(util.template("exports-module-declaration",true))}};CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var ref=this.getExternalReference(node,nodes);if(t.isSpecifierDefault(specifier)){if(!includes(this.file.dynamicImportedNoDefault,node)){if(this.noInteropRequireImport||includes(this.file.dynamicImported,node)){ref=t.memberExpression(ref,t.identifier("default"))}else{ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,ref)]))}else{if(specifier.type==="ImportBatchSpecifier"){if(!this.noInteropRequireImport){ref=t.callExpression(this.file.addHelper("interop-require-wildcard"),[ref])}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,ref)]))}else{nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.memberExpression(ref,t.getSpecifierId(specifier)))]))}}};CommonJSFormatter.prototype.importDeclaration=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source},true))};CommonJSFormatter.prototype.exportDeclaration=function(node,nodes){if(this.doDefaultExportInterop(node)){var declar=node.declaration;var assign=util.template("exports-default-assign",{VALUE:this._pushStatement(declar,nodes)},true);if(t.isFunctionDeclaration(declar)){assign._blockHoist=3}nodes.push(assign);return}DefaultFormatter.prototype.exportDeclaration.apply(this,arguments)};CommonJSFormatter.prototype._getExternalReference=function(node,nodes){var source=node.source.value;var call=t.callExpression(t.identifier("require"),[node.source]);if(this.localImportOccurences[source]>1){var uid=this.scope.generateUidIdentifier(source);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(uid,call)]));return uid}else{return call}}},{"../../types":121,"../../util":123,"./_default":45,"lodash/collection/includes":197}],52:[function(require,module,exports){"use strict";module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.exportDeclaration=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.importDeclaration=IgnoreFormatter.prototype.importSpecifier=IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":121}],53:[function(require,module,exports){module.exports={commonStandard:require("./common-standard"),commonStrict:require("./common-strict"),amdStrict:require("./amd-strict"),umdStrict:require("./umd-strict"),common:require("./common"),system:require("./system"),ignore:require("./ignore"),amd:require("./amd"),umd:require("./umd")}},{"./amd":48,"./amd-strict":47,"./common":51,"./common-standard":49,"./common-strict":50,"./ignore":52,"./system":54,"./umd":56,"./umd-strict":55}],54:[function(require,module,exports){"use strict";module.exports=SystemFormatter;var DefaultFormatter=require("./_default");var AMDFormatter=require("./amd");var useStrict=require("../helpers/use-strict");var util=require("../../util");var t=require("../../types");var last=require("lodash/array/last");var each=require("lodash/collection/each");var map=require("lodash/collection/map");function SystemFormatter(file){this.exportIdentifier=file.scope.generateUidIdentifier("export");this.noInteropRequireExport=true;this.noInteropRequireImport=true;DefaultFormatter.apply(this,arguments)}util.inherits(SystemFormatter,AMDFormatter);SystemFormatter.prototype.init=function(){};SystemFormatter.prototype._addImportSource=function(node,exportNode){node._importSource=exportNode.source&&exportNode.source.value;return node};SystemFormatter.prototype.buildExportsWildcard=function(objectIdentifier,node){var leftIdentifier=this.scope.generateUidIdentifier("key");var valIdentifier=t.memberExpression(objectIdentifier,leftIdentifier,true);var left=t.variableDeclaration("var",[t.variableDeclarator(leftIdentifier)]);var right=objectIdentifier;var block=t.blockStatement([t.expressionStatement(this.buildExportCall(leftIdentifier,valIdentifier))]);return this._addImportSource(t.forInStatement(left,right,block),node)};SystemFormatter.prototype.buildExportsAssignment=function(id,init,node){var call=this.buildExportCall(t.literal(id.name),init,true);return this._addImportSource(call,node)};SystemFormatter.prototype.remapExportAssignment=function(node){return this.buildExportCall(t.literal(node.left.name),node)};SystemFormatter.prototype.buildExportCall=function(id,init,isStatement){var call=t.callExpression(this.exportIdentifier,[id,init]);if(isStatement){return t.expressionStatement(call)}else{return call}};SystemFormatter.prototype.importSpecifier=function(specifier,node,nodes){AMDFormatter.prototype.importSpecifier.apply(this,arguments);this._addImportSource(last(nodes),node)};var runnerSettersVisitor={enter:function(node,parent,scope,state){if(node._importSource===state.source){if(t.isVariableDeclaration(node)){each(node.declarations,function(declar){state.hoistDeclarators.push(t.variableDeclarator(declar.id));state.nodes.push(t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init)))})}else{state.nodes.push(node)}this.remove()}}};SystemFormatter.prototype.buildRunnerSetters=function(block,hoistDeclarators){var scope=this.file.scope;return t.arrayExpression(map(this.ids,function(uid,source){var state={source:source,nodes:[],hoistDeclarators:hoistDeclarators};scope.traverse(block,runnerSettersVisitor,state);return t.functionExpression(null,[uid],t.blockStatement(state.nodes))}))};var hoistVariablesVisitor={enter:function(node,parent,scope,hoistDeclarators){if(t.isFunction(node)){return this.skip()}if(t.isVariableDeclaration(node)){if(node.kind!=="var"&&!t.isProgram(parent)){return}if(node._blockHoist)return;var nodes=[];for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];hoistDeclarators.push(t.variableDeclarator(declar.id));if(declar.init){var assign=t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init));nodes.push(assign)}}if(t.isFor(parent)){if(parent.left===node){return node.declarations[0].id}if(parent.init===node){return t.toSequenceExpression(nodes,scope)}}return nodes}}};var hoistFunctionsVisitor={enter:function(node,parent,scope,handlerBody){if(t.isFunction(node))this.skip();if(t.isFunctionDeclaration(node)||node._blockHoist){handlerBody.push(node);this.remove()}}};SystemFormatter.prototype.transform=function(program){var hoistDeclarators=[];var moduleName=this.getModuleName();var moduleNameLiteral=t.literal(moduleName);var block=t.blockStatement(program.body);var runner=util.template("system",{MODULE_NAME:moduleNameLiteral,MODULE_DEPENDENCIES:t.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(block,hoistDeclarators),EXECUTE:t.functionExpression(null,[],block)},true);var handlerBody=runner.expression.arguments[2].body.body;if(!moduleName)runner.expression.arguments.shift();var returnStatement=handlerBody.pop();this.file.scope.traverse(block,hoistVariablesVisitor,hoistDeclarators);if(hoistDeclarators.length){var hoistDeclar=t.variableDeclaration("var",hoistDeclarators);hoistDeclar._blockHoist=true;handlerBody.unshift(hoistDeclar)}this.file.scope.traverse(block,hoistFunctionsVisitor,handlerBody);handlerBody.push(returnStatement);if(useStrict.has(block)){handlerBody.unshift(block.body.shift())}program.body=[runner]}},{"../../types":121,"../../util":123,"../helpers/use-strict":43,"./_default":45,"./amd":48,"lodash/array/last":190,"lodash/collection/each":194,"lodash/collection/map":198}],55:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./umd"))},{"./_strict":46,"./umd":56}],56:[function(require,module,exports){"use strict";module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var values=require("lodash/object/values");function UMDFormatter(){AMDFormatter.apply(this,arguments)}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(program){var body=program.body;var names=[];for(var name in this.ids){names.push(t.literal(name))}var ids=values(this.ids);var args=[t.identifier("exports")];if(this.passModuleArg)args.push(t.identifier("module"));args=args.concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var defineArgs=[t.literal("exports")];if(this.passModuleArg)defineArgs.push(t.literal("module"));defineArgs=defineArgs.concat(names);defineArgs=[t.arrayExpression(defineArgs)];var testExports=util.template("test-exports");var testModule=util.template("test-module");var commonTests=this.passModuleArg?t.logicalExpression("&&",testExports,testModule):testExports;var commonArgs=[t.identifier("exports")];if(this.passModuleArg)commonArgs.push(t.identifier("module"));commonArgs=commonArgs.concat(names.map(function(name){return t.callExpression(t.identifier("require"),[name])}));var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:defineArgs,COMMON_TEST:commonTests,COMMON_ARGUMENTS:commonArgs});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":121,"../../util":123,"./amd":48,"lodash/object/values":286}],57:[function(require,module,exports){module.exports=TransformerPass;var includes=require("lodash/collection/includes");function TransformerPass(file,transformer){this.transformer=transformer;this.shouldRun=!transformer.check;this.handlers=transformer.handlers;this.file=file}TransformerPass.prototype.canRun=function(){var transformer=this.transformer;var opts=this.file.opts;var key=transformer.key;if(key[0]==="_")return true;var blacklist=opts.blacklist;if(blacklist.length&&includes(blacklist,key))return false;var whitelist=opts.whitelist;if(whitelist.length)return includes(whitelist,key);if(transformer.optional&&!includes(opts.optional,key))return false;if(transformer.experimental&&!opts.experimental)return false;if(transformer.playground&&!opts.playground)return false;return true};TransformerPass.prototype.checkNode=function(node){var check=this.transformer.check;if(check){return this.shouldRun=check(node)}else{return true}};TransformerPass.prototype.transform=function(){if(!this.shouldRun)return;var file=this.file;file.debug("Running transformer "+this.transformer.key);file.scope.traverse(file.ast,this.handlers,file)}},{"lodash/collection/includes":197}],58:[function(require,module,exports){"use strict";module.exports=Transformer;var TransformerPass=require("./transformer-pass");var isFunction=require("lodash/lang/isFunction");var traverse=require("../traversal");var isObject=require("lodash/lang/isObject");var clone=require("../helpers/clone");var each=require("lodash/collection/each");function Transformer(key,transformer,opts){transformer=clone(transformer);var take=function(key){var val=transformer[key];delete transformer[key];return val};this.manipulateOptions=take("manipulateOptions");this.check=take("check");this.post=take("post");this.pre=take("pre");this.experimental=!!take("experimental");this.playground=!!take("playground");this.secondPass=!!take("secondPass");this.optional=!!take("optional");this.handlers=this.normalize(transformer);this.opts=opts||{};this.key=key}Transformer.prototype.normalize=function(transformer){var self=this;if(isFunction(transformer)){transformer={ast:transformer}}traverse.explode(transformer);each(transformer,function(fns,type){if(type[0]==="_"){self[type]=fns;return}if(type==="enter"||type==="exit")return;if(isFunction(fns))fns={enter:fns};if(!isObject(fns))return;if(!fns.enter)fns.enter=function(){};if(!fns.exit)fns.exit=function(){};transformer[type]=fns});return transformer};Transformer.prototype.buildPass=function(file){return new TransformerPass(file,this)}},{"../helpers/clone":23,"../traversal":116,"./transformer-pass":57,"lodash/collection/each":194,"lodash/lang/isFunction":270,"lodash/lang/isObject":273}],59:[function(require,module,exports){module.exports={specNoForInOfAssignment:"validation.noForInOfAssignment",specSetters:"validation.setters",specBlockScopedFunctions:"spec.blockScopedFunctions",malletOperator:"playground.malletOperator",methodBinding:"playground.methodBinding",memoizationOperator:"playground.memoizationOperator",objectGetterMemoization:"playground.objectGetterMemoization",modules:"es6.modules",propertyNameShorthand:"es6.properties.shorthand",arrayComprehension:"es7.comprehensions",generatorComprehension:"es7.comprehensions",arrowFunctions:"es6.arrowFunctions",classes:"es6.classes",objectSpread:"es7.objectRestSpread","es7.objectSpread":"es7.objectRestSpread",exponentiationOperator:"es7.exponentiationOperator",spread:"es6.spread",templateLiterals:"es6.templateLiterals",propertyMethodAssignment:"es6.properties.shorthand",computedPropertyNames:"es6.properties.computed",defaultParameters:"es6.parameters.default",restParameters:"es6.parameters.rest",destructuring:"es6.destructuring",forOf:"es6.forOf",unicodeRegex:"es6.unicodeRegex",abstractReferences:"es7.abstractReferences",constants:"es6.constants",letScoping:"es6.letScoping",blockScopingTDZ:"es6.blockScopingTDZ",generators:"regenerator",protoToAssign:"spec.protoToAssign",typeofSymbol:"spec.typeofSymbol",coreAliasing:"selfContained",undefinedToVoid:"spec.undefinedToVoid",undeclaredVariableCheck:"validation.undeclaredVariableCheck",specPropertyLiterals:"es3.propertyLiterals",specMemberExpressionLiterals:"es3.memberExpressionLiterals","minification.propertyLiterals":"es3.propertyLiterals","minification.memberExpressionLiterals":"es3.memberExpressionLiterals"}},{}],60:[function(require,module,exports){"use strict";var t=require("../../../types");exports.MemberExpression=function(node){var prop=node.property;if(node.computed&&t.isLiteral(prop)&&t.isValidIdentifier(prop.value)){node.property=t.identifier(prop.value);node.computed=false}else if(!node.computed&&t.isIdentifier(prop)&&!t.isValidIdentifier(prop.name)){node.property=t.literal(prop.name);node.computed=true}}},{"../../../types":121}],61:[function(require,module,exports){"use strict";var t=require("../../../types");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&t.isValidIdentifier(key.value)){node.key=t.identifier(key.value);node.computed=false}else if(!node.computed&&t.isIdentifier(key)&&!t.isValidIdentifier(key.name)){node.key=t.literal(key.name)}}},{"../../../types":121}],62:[function(require,module,exports){"use strict";var defineMap=require("../../helpers/define-map");var t=require("../../../types");exports.check=function(node){return t.isProperty(node)&&(node.kind==="get"||node.kind==="set")};exports.ObjectExpression=function(node){var mutatorMap={};var hasAny=false;node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){hasAny=true;defineMap.push(mutatorMap,prop.key,prop.kind,prop.computed,prop.value);return false}else{return true}});if(!hasAny)return;return t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("defineProperties")),[node,defineMap.build(mutatorMap)])}},{"../../../types":121,"../../helpers/define-map":37}],63:[function(require,module,exports){"use strict";var t=require("../../../types");exports.check=t.isArrowFunctionExpression;exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction="arrow";node.expression=false;node.type="FunctionExpression";return node}},{"../../../types":121}],64:[function(require,module,exports){"use strict";var t=require("../../../types");var visitor={enter:function(node,parent,scope,state){if(!t.isReferencedIdentifier(node,parent))return;var declared=state.letRefs[node.name];if(!declared)return;if(scope.getBindingIdentifier(node.name)!==declared)return;var assert=t.callExpression(state.file.addHelper("temporal-assert-defined"),[node,t.literal(node.name),state.file.addHelper("temporal-undefined")]);this.skip();if(t.isAssignmentExpression(parent)||t.isUpdateExpression(parent)){if(parent._ignoreBlockScopingTDZ)return;this.parentPath.replaceNode(t.sequenceExpression([assert,parent]))}else{return t.logicalExpression("&&",assert,node)}}};exports.optional=true;exports.Loop=exports.Program=exports.BlockStatement=function(node,parent,scope,file){var letRefs=node._letReferences;if(!letRefs)return;var state={letRefs:letRefs,file:file};scope.traverse(node,visitor,state)}},{"../../../types":121}],65:[function(require,module,exports){"use strict";var traverse=require("../../../traversal");var object=require("../../../helpers/object");var util=require("../../../util");var t=require("../../../types");var values=require("lodash/object/values");var extend=require("lodash/object/extend");exports.check=function(node){return t.isVariableDeclaration(node)&&(node.kind==="let"||node.kind==="const")};var isLet=function(node,parent){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;if(isLetInitable(node,parent)){for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];declar.init=declar.init||t.identifier("undefined")}}node._let=true;node.kind="var";return true};var isLetInitable=function(node,parent){return!t.isFor(parent)||t.isFor(parent)&&parent.left!==node};var isVar=function(node,parent){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node,parent)};var standardizeLets=function(declars){for(var i=0;i<declars.length;i++){delete declars[i]._let}};exports.VariableDeclaration=function(node,parent,scope,file){if(!isLet(node,parent))return;if(isLetInitable(node)&&file.transformers["es6.blockScopingTDZ"].canRun()){var nodes=[node];for(var i=0;i<node.declarations.length;i++){var decl=node.declarations[i];if(decl.init){var assign=t.assignmentExpression("=",decl.id,decl.init);assign._ignoreBlockScopingTDZ=true;nodes.push(t.expressionStatement(assign))}decl.init=file.addHelper("temporal-undefined")}node._blockHoist=2;return nodes}};exports.Loop=function(node,parent,scope,file){var init=node.left||node.init;if(isLet(init,node)){t.ensureBlock(node);node.body._letDeclarators=[init]}var blockScoping=new BlockScoping(node,node.body,parent,scope,file);blockScoping.run()};exports.Program=exports.BlockStatement=function(block,parent,scope,file){if(!t.isLoop(parent)){var blockScoping=new BlockScoping(false,block,parent,scope,file);blockScoping.run()}};function BlockScoping(loopParent,block,parent,scope,file){this.loopParent=loopParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.outsideLetReferences=object();this.hasLetReferences=false;this.letReferences=block._letReferences=object();this.body=[]}BlockScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;var needsClosure=this.getLetReferences();if(t.isFunction(this.parent)||t.isProgram(this.block))return;if(!this.hasLetReferences)return;if(needsClosure){this.wrapClosure()}else{this.remap()}};function replace(node,parent,scope,remaps){if(!t.isReferencedIdentifier(node,parent))return;var remap=remaps[node.name];if(!remap)return;var ownBinding=scope.getBindingIdentifier(node.name);if(ownBinding===remap.binding){node.name=remap.uid}else{if(this)this.skip()}}var replaceVisitor={enter:replace};function traverseReplace(node,parent,scope,remaps){replace(node,parent,scope,remaps);scope.traverse(node,replaceVisitor,remaps)}BlockScoping.prototype.remap=function(){var hasRemaps=false;var letRefs=this.letReferences;var scope=this.scope;var remaps=object();for(var key in letRefs){var ref=letRefs[key];if(scope.parentHasBinding(key)||scope.hasGlobal(key)){var uid=scope.generateUidIdentifier(ref.name).name;ref.name=uid;hasRemaps=true;remaps[key]=remaps[uid]={binding:ref,uid:uid}}}if(!hasRemaps)return;var loopParent=this.loopParent;if(loopParent){traverseReplace(loopParent.right,loopParent,scope,remaps);traverseReplace(loopParent.test,loopParent,scope,remaps);traverseReplace(loopParent.update,loopParent,scope,remaps)}scope.traverse(this.block,replaceVisitor,remaps)};BlockScoping.prototype.wrapClosure=function(){var block=this.block;var outsideRefs=this.outsideLetReferences;if(this.loopParent){for(var name in outsideRefs){var id=outsideRefs[name];if(this.scope.hasGlobal(id.name)){delete outsideRefs[id.name];delete this.letReferences[id.name];this.scope.rename(id.name);
this.letReferences[id.name]=id;outsideRefs[id.name]=id}}}this.has=this.checkLoop();this.hoistVarDeclarations();var params=values(outsideRefs);var fn=t.functionExpression(null,params,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var call=t.callExpression(fn,params);var ret=this.scope.generateUidIdentifier("ret");var hasYield=traverse.hasType(fn.body,this.scope,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}var hasAsync=traverse.hasType(fn.body,this.scope,"AwaitExpression",t.FUNCTION_TYPES);if(hasAsync){fn.async=true;call=t.awaitExpression(call,true)}this.build(ret,call)};var letReferenceFunctionVisitor={enter:function(node,parent,scope,state){if(!t.isReferencedIdentifier(node,parent))return;if(scope.hasOwnBinding(node.name))return;if(!state.letReferences[node.name])return;state.closurify=true}};var letReferenceBlockVisitor={enter:function(node,parent,scope,state){if(t.isFunction(node)){scope.traverse(node,letReferenceFunctionVisitor,state);return this.skip()}}};BlockScoping.prototype.getLetReferences=function(){var block=this.block;var declarators=block._letDeclarators||[];var declar;for(var i=0;i<declarators.length;i++){declar=declarators[i];extend(this.outsideLetReferences,t.getBindingIdentifiers(declar))}if(block.body){for(i=0;i<block.body.length;i++){declar=block.body[i];if(isLet(declar,block)){declarators=declarators.concat(declar.declarations)}}}for(i=0;i<declarators.length;i++){declar=declarators[i];var keys=t.getBindingIdentifiers(declar);extend(this.letReferences,keys);this.hasLetReferences=true}if(!this.hasLetReferences)return;standardizeLets(declarators);var state={letReferences:this.letReferences,closurify:false};this.scope.traverse(this.block,letReferenceBlockVisitor,state);return state.closurify};var loopNodeTo=function(node){if(t.isBreakStatement(node)){return"break"}else if(t.isContinueStatement(node)){return"continue"}};var loopVisitor={enter:function(node,parent,scope,state){var replace;if(t.isLoop(node)){state.ignoreLabeless=true;scope.traverse(node,loopVisitor,state);state.ignoreLabeless=false}if(t.isFunction(node)||t.isLoop(node)){return this.skip()}var loopText=loopNodeTo(node);if(loopText){if(node.label){if(state.innerLabels.indexOf(node.label.name)>=0){return}loopText=loopText+"|"+node.label.name}else{if(state.ignoreLabeless)return;if(t.isBreakStatement(node)&&t.isSwitchCase(parent))return}state.hasBreakContinue=true;state.map[loopText]=node;replace=t.literal(loopText)}if(t.isReturnStatement(node)){state.hasReturn=true;replace=t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))])}if(replace){replace=t.returnStatement(replace);return t.inherits(replace,node)}}};var loopLabelVisitor={enter:function(node,parent,scope,state){if(t.isLabeledStatement(node)){state.innerLabels.push(node.label.name)}}};BlockScoping.prototype.checkLoop=function(){var state={hasBreakContinue:false,ignoreLabeless:false,innerLabels:[],hasReturn:false,isLoop:!!this.loopParent,map:{}};this.scope.traverse(this.block,loopLabelVisitor,state);this.scope.traverse(this.block,loopVisitor,state);return state};var hoistVarDeclarationsVisitor={enter:function(node,parent,scope,self){if(t.isForStatement(node)){if(isVar(node.init,node)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left,node)){node.left=node.left.declarations[0].id}}else if(isVar(node,parent)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return this.skip()}}};BlockScoping.prototype.hoistVarDeclarations=function(){traverse(this.block,hoistVarDeclarationsVisitor,this.scope,this)};BlockScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];if(!declar.init)continue;var expr=t.assignmentExpression("=",declar.id,declar.init);replace.push(t.inherits(expr,declar))}return replace};BlockScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreakContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};BlockScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var loopParent=this.loopParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreakContinue){if(!loopParent){throw new Error("Has no loop parent but we're trying to reassign breaks "+"and continues, something is going wrong here.")}for(var key in has.map){cases.push(t.switchCase(t.literal(key),[has.map[key]]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../../helpers/object":27,"../../../traversal":116,"../../../types":121,"../../../util":123,"lodash/object/extend":281,"lodash/object/values":286}],66:[function(require,module,exports){"use strict";var ReplaceSupers=require("../../helpers/replace-supers");var nameMethod=require("../../helpers/name-method");var defineMap=require("../../helpers/define-map");var messages=require("../../../messages");var util=require("../../../util");var t=require("../../../types");exports.check=t.isClass;exports.ClassDeclaration=function(node,parent,scope,file){return new ClassTransformer(node,file,scope,true).run()};exports.ClassExpression=function(node,parent,scope,file){if(!node.id){if(t.isProperty(parent)&&parent.value===node&&!parent.computed&&t.isIdentifier(parent.key)){node.id=parent.key}if(t.isVariableDeclarator(parent)&&t.isIdentifier(parent.id)){node.id=parent.id}}return new ClassTransformer(node,file,scope,false).run()};function ClassTransformer(node,file,scope,isStatement){this.isStatement=isStatement;this.scope=scope;this.node=node;this.file=file;this.hasInstanceMutators=false;this.hasStaticMutators=false;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||scope.generateUidIdentifier("class");this.superName=node.superClass||t.identifier("Function");this.hasSuper=!!node.superClass;this.isLoose=file.isLoose("es6.classes")}ClassTransformer.prototype.run=function(){var superName=this.superName;var className=this.className;var file=this.file;var body=this.body=[];var constructorBody=t.blockStatement([t.expressionStatement(t.callExpression(file.addHelper("class-call-check"),[t.thisExpression(),className]))]);var constructor;if(this.node.id){constructor=t.functionDeclaration(className,[],constructorBody);body.push(constructor)}else{constructor=t.functionExpression(null,[],constructorBody);body.push(t.variableDeclaration("var",[t.variableDeclarator(className,constructor)]))}this.constructor=constructor;var closureParams=[];var closureArgs=[];if(this.hasSuper){closureArgs.push(superName);if(!t.isIdentifier(superName)){superName=this.scope.generateUidBasedOnNode(superName,this.file)}closureParams.push(superName);this.superName=superName;body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"),[className,superName])))}this.buildBody();t.inheritsComments(body[0],this.node);var init;if(body.length===1){init=t.toExpression(constructor)}else{body.push(t.returnStatement(className));init=t.callExpression(t.functionExpression(null,closureParams,t.blockStatement(body)),closureArgs)}if(this.isStatement){return t.variableDeclaration("let",[t.variableDeclarator(className,init)])}else{return init}};ClassTransformer.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;for(var i=0;i<classBody.length;i++){var node=classBody[i];if(t.isMethodDefinition(node)){var replaceSupers=new ReplaceSupers({methodNode:node,className:this.className,superName:this.superName,isStatic:node.static,isLoose:this.isLoose,scope:this.scope,file:this.file},true);replaceSupers.replace();if(node.key.name==="constructor"){this.pushConstructor(node)}else{this.pushMethod(node)}}else if(t.isPrivateDeclaration(node)){this.closure=true;body.unshift(node)}else if(t.isClassProperty(node)){this.pushProperty(node)}}if(!this.hasConstructor&&this.hasSuper&&!t.isFalsyExpression(superName)){var helperName="class-super-constructor-call";if(this.isLoose)helperName+="-loose";constructor.body.body.push(util.template(helperName,{CLASS_NAME:className,SUPER_NAME:this.superName},true))}var instanceProps;var staticProps;if(this.hasInstanceMutators){instanceProps=defineMap.build(this.instanceMutatorMap)}if(this.hasStaticMutators){staticProps=defineMap.build(this.staticMutatorMap)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addHelper("prototype-properties"),args)))}};ClassTransformer.prototype.pushMethod=function(node){var methodName=node.key;var kind=node.kind;if(kind===""){nameMethod.property(node,this.file,this.scope);if(this.isLoose){var className=this.className;if(!node.static)className=t.memberExpression(className,t.identifier("prototype"));methodName=t.memberExpression(className,methodName,node.computed);var expr=t.expressionStatement(t.assignmentExpression("=",methodName,node.value));t.inheritsComments(expr,node);this.body.push(expr);return}kind="value"}var mutatorMap=this.instanceMutatorMap;if(node.static){this.hasStaticMutators=true;mutatorMap=this.staticMutatorMap}else{this.hasInstanceMutators=true}defineMap.push(mutatorMap,methodName,kind,node.computed,node);defineMap.push(mutatorMap,methodName,"enumerable",node.computed,false)};ClassTransformer.prototype.pushProperty=function(node){if(!node.value)return;var key;if(node.static){key=t.memberExpression(this.className,node.key);this.body.push(t.expressionStatement(t.assignmentExpression("=",key,node.value)))}else{key=t.memberExpression(t.thisExpression(),node.key);this.constructor.body.body.unshift(t.expressionStatement(t.assignmentExpression("=",key,node.value)))}};ClassTransformer.prototype.pushConstructor=function(method){if(method.kind){throw this.file.errorWithNode(method,messages.get("classesIllegalConstructorKind"))}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct._ignoreUserWhitespace=true;construct.params=fn.params;construct.body.body=construct.body.body.concat(fn.body.body)}},{"../../../messages":30,"../../../types":121,"../../../util":123,"../../helpers/define-map":37,"../../helpers/name-method":39,"../../helpers/replace-supers":42}],67:[function(require,module,exports){"use strict";var messages=require("../../../messages");var t=require("../../../types");exports.check=function(node){return t.isVariableDeclaration(node,{kind:"const"})};var visitor={enter:function(node,parent,scope,state){if(t.isAssignmentExpression(node)||t.isUpdateExpression(node)){var ids=t.getBindingIdentifiers(node);for(var name in ids){var id=ids[name];var constant=state.constants[name];if(!constant)continue;var constantIdentifier=constant.identifier;if(id===constantIdentifier)continue;if(!scope.bindingIdentifierEquals(name,constantIdentifier))continue;throw state.file.errorWithNode(id,messages.get("readOnly",name))}}else if(t.isScope(node,parent)){this.skip()}}};exports.Scopable=function(node,parent,scope,file){scope.traverse(node,visitor,{constants:scope.getAllBindingsOfKind("const"),file:file})};exports.VariableDeclaration=function(node){if(node.kind==="const")node.kind="let"}},{"../../../messages":30,"../../../types":121}],68:[function(require,module,exports){"use strict";var messages=require("../../../messages");var t=require("../../../types");exports.check=t.isPattern;function DestructuringTransformer(opts){this.blockHoist=opts.blockHoist;this.operator=opts.operator;this.nodes=opts.nodes;this.scope=opts.scope;this.file=opts.file;this.kind=opts.kind}DestructuringTransformer.prototype.buildVariableAssignment=function(id,init){var op=this.operator;if(t.isMemberExpression(id))op="=";var node;if(op){node=t.expressionStatement(t.assignmentExpression(op,id,init))}else{node=t.variableDeclaration(this.kind,[t.variableDeclarator(id,init)])}node._blockHoist=this.blockHoist;return node};DestructuringTransformer.prototype.buildVariableDeclaration=function(id,init){var declar=t.variableDeclaration("var",[t.variableDeclarator(id,init)]);declar._blockHoist=this.blockHoist;return declar};DestructuringTransformer.prototype.push=function(elem,parentId){if(t.isObjectPattern(elem)){this.pushObjectPattern(elem,parentId)}else if(t.isArrayPattern(elem)){this.pushArrayPattern(elem,parentId)}else if(t.isAssignmentPattern(elem)){this.pushAssignmentPattern(elem,parentId)}else{this.nodes.push(this.buildVariableAssignment(elem,parentId))}};DestructuringTransformer.prototype.pushAssignmentPattern=function(pattern,parentId){var tempParentId=this.scope.generateUidBasedOnNode(parentId);var declar=t.variableDeclaration("var",[t.variableDeclarator(tempParentId,parentId)]);declar._blockHoist=this.blockHoist;this.nodes.push(declar);this.nodes.push(this.buildVariableAssignment(pattern.left,t.conditionalExpression(t.binaryExpression("===",tempParentId,t.identifier("undefined")),pattern.right,tempParentId)))};DestructuringTransformer.prototype.pushObjectSpread=function(pattern,parentId,prop,i){var keys=[];for(var i2=0;i2<pattern.properties.length;i2++){var prop2=pattern.properties[i2];if(i2>=i)break;if(t.isSpreadProperty(prop2))continue;var key=prop2.key;if(t.isIdentifier(key)){key=t.literal(prop2.key.name)}keys.push(key)}keys=t.arrayExpression(keys);var value=t.callExpression(this.file.addHelper("object-without-properties"),[parentId,keys]);this.nodes.push(this.buildVariableAssignment(prop.argument,value))};DestructuringTransformer.prototype.pushObjectProperty=function(prop,parentId){if(t.isLiteral(prop.key))prop.computed=true;var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key,prop.computed);if(t.isPattern(pattern2)){this.push(pattern2,patternId2)}else{this.nodes.push(this.buildVariableAssignment(pattern2,patternId2))}};DestructuringTransformer.prototype.pushObjectPattern=function(pattern,parentId){if(!pattern.properties.length){this.nodes.push(t.expressionStatement(t.callExpression(this.file.addHelper("object-destructuring-empty"),[parentId])))}if(pattern.properties.length>1&&t.isMemberExpression(parentId)){var temp=this.scope.generateUidBasedOnNode(parentId,this.file);this.nodes.push(this.buildVariableDeclaration(temp,parentId));parentId=temp}for(var i=0;i<pattern.properties.length;i++){var prop=pattern.properties[i];if(t.isSpreadProperty(prop)){this.pushObjectSpread(pattern,parentId,prop,i)}else{this.pushObjectProperty(prop,parentId)}}};var hasRest=function(pattern){for(var i=0;i<pattern.elements.length;i++){if(t.isRestElement(pattern.elements[i])){return true}}return false};DestructuringTransformer.prototype.pushArrayPattern=function(pattern,parentId){if(!pattern.elements)return;var count=!hasRest(pattern)&&pattern.elements.length;var toArray=this.scope.toArray(parentId,count);var _parentId=this.scope.generateUidBasedOnNode(parentId);this.nodes.push(this.buildVariableDeclaration(_parentId,toArray));parentId=_parentId;this.scope.assignTypeGeneric(parentId.name,"Array");for(var i=0;i<pattern.elements.length;i++){var elem=pattern.elements[i];if(!elem)continue;var newPatternId;if(t.isRestElement(elem)){newPatternId=this.scope.toArray(parentId);if(i>0){newPatternId=t.callExpression(t.memberExpression(newPatternId,t.identifier("slice")),[t.literal(i)])}elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true)}this.push(elem,newPatternId)}};DestructuringTransformer.prototype.init=function(pattern,parentId){if(!t.isArrayExpression(parentId)&&!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=this.scope.generateUidBasedOnNode(parentId);this.nodes.push(this.buildVariableDeclaration(key,parentId));parentId=key}this.push(pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,scope,file){var left=node.left;if(t.isPattern(left)){var temp=scope.generateUidIdentifier("ref");node.left=t.variableDeclaration("var",[t.variableDeclarator(temp)]);t.ensureBlock(node);node.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(left,temp)]));return}if(!t.isVariableDeclaration(left))return;var pattern=left.declarations[0].id;if(!t.isPattern(pattern))return;var key=scope.generateUidIdentifier("ref");node.left=t.variableDeclaration(left.kind,[t.variableDeclarator(key,null)]);var nodes=[];var destructuring=new DestructuringTransformer({kind:left.kind,file:file,scope:scope,nodes:nodes});destructuring.init(pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,scope,file){var nodes=[];var hasDestructuringTransformer=false;node.params=node.params.map(function(pattern,i){if(!t.isPattern(pattern))return pattern;hasDestructuringTransformer=true;var parentId=scope.generateUidIdentifier("ref");var destructuring=new DestructuringTransformer({blockHoist:node.params.length-i,nodes:nodes,scope:scope,file:file,kind:"var"});destructuring.init(pattern,parentId);return parentId});if(!hasDestructuringTransformer)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.CatchClause=function(node,parent,scope,file){var pattern=node.param;if(!t.isPattern(pattern))return;var ref=scope.generateUidIdentifier("ref");node.param=ref;var nodes=[];var destructuring=new DestructuringTransformer({kind:"let",file:file,scope:scope,nodes:nodes});destructuring.init(pattern,ref);node.body.body=nodes.concat(node.body.body);return node};exports.ExpressionStatement=function(node,parent,scope,file){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;if(file.isConsequenceExpressionStatement(node))return;var nodes=[];var ref=scope.generateUidIdentifier("ref");nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));var destructuring=new DestructuringTransformer({operator:expr.operator,file:file,scope:scope,nodes:nodes});destructuring.init(expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,scope,file){if(!t.isPattern(node.left))return;var ref=scope.generateUidIdentifier("temp");scope.push({key:ref.name,id:ref});var nodes=[];nodes.push(t.assignmentExpression("=",ref,node.right));var destructuring=new DestructuringTransformer({operator:node.operator,file:file,scope:scope,nodes:nodes});destructuring.init(node.left,ref);nodes.push(ref);return t.toSequenceExpression(nodes,scope)};var variableDeclarationhasPattern=function(node){for(var i=0;i<node.declarations.length;i++){if(t.isPattern(node.declarations[i].id)){return true}}return false};exports.VariableDeclaration=function(node,parent,scope,file){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;if(!variableDeclarationhasPattern(node))return;var nodes=[];var declar;for(var i=0;i<node.declarations.length;i++){declar=node.declarations[i];var patternId=declar.init;var pattern=declar.id;var destructuring=new DestructuringTransformer({nodes:nodes,scope:scope,kind:node.kind,file:file});if(t.isPattern(pattern)&&patternId){destructuring.init(pattern,patternId);if(+i!==node.declarations.length-1){t.inherits(nodes[nodes.length-1],declar)}}else{nodes.push(t.inherits(destructuring.buildVariableAssignment(declar.id,declar.init),declar))}}if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){declar=null;for(i=0;i<nodes.length;i++){node=nodes[i];declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,messages.get("invalidParentForThisNode"))}declar.declarations=declar.declarations.concat(node.declarations)}return declar}return nodes}},{"../../../messages":30,"../../../types":121}],69:[function(require,module,exports){"use strict";var messages=require("../../../messages");var util=require("../../../util");var t=require("../../../types");exports.check=t.isForOfStatement;exports.ForOfStatement=function(node,parent,scope,file){var callback=spec;if(file.isLoose("es6.forOf"))callback=loose;var build=callback(node,parent,scope,file);var declar=build.declar;var loop=build.loop;var block=loop.body;t.inheritsComments(loop,node);t.ensureBlock(node);if(declar){block.body.push(declar)}block.body=block.body.concat(node.body.body);t.inherits(loop,node);loop._scopeInfo=node._scopeInfo;return loop};var loose=function(node,parent,scope,file){var left=node.left;var declar,id;if(t.isIdentifier(left)||t.isPattern(left)){id=left}else if(t.isVariableDeclaration(left)){id=scope.generateUidIdentifier("ref");declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,id)])}else{throw file.errorWithNode(left,messages.get("unknownForHead",left.type))}var loop=util.template("for-of-loose",{LOOP_OBJECT:scope.generateUidIdentifier("iterator"),IS_ARRAY:scope.generateUidIdentifier("isArray"),OBJECT:node.right,INDEX:scope.generateUidIdentifier("i"),ID:id});if(!declar){loop.body.body.shift()}return{declar:declar,loop:loop}};var spec=function(node,parent,scope,file){var left=node.left;var declar;var stepKey=scope.generateUidIdentifier("step");var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)||t.isPattern(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,messages.get("unknownForHead",left.type))}var loop=util.template("for-of",{ITERATOR_KEY:scope.generateUidIdentifier("iterator"),STEP_KEY:stepKey,OBJECT:node.right});return{declar:declar,loop:loop}}},{"../../../messages":30,"../../../types":121,"../../../util":123}],70:[function(require,module,exports){"use strict";var t=require("../../../types");exports.check=require("../internal/modules").check;exports.ImportDeclaration=function(node,parent,scope,file){var nodes=[];if(node.specifiers.length){for(var i=0;i<node.specifiers.length;i++){file.moduleFormatter.importSpecifier(node.specifiers[i],node,nodes,parent)}}else{file.moduleFormatter.importDeclaration(node,nodes,parent)}if(nodes.length===1){nodes[0]._blockHoist=node._blockHoist}return nodes};exports.ExportDeclaration=function(node,parent,scope,file){var nodes=[];var i;if(node.declaration){if(t.isVariableDeclaration(node.declaration)){var declar=node.declaration.declarations[0];declar.init=declar.init||t.identifier("undefined")}file.moduleFormatter.exportDeclaration(node,nodes,parent)}else if(node.specifiers){for(i=0;i<node.specifiers.length;i++){file.moduleFormatter.exportSpecifier(node.specifiers[i],node,nodes,parent)}}if(node._blockHoist){for(i=0;i<nodes.length;i++){nodes[i]._blockHoist=node._blockHoist}}return nodes}},{"../../../types":121,"../internal/modules":90}],71:[function(require,module,exports){"use strict";var ReplaceSupers=require("../../helpers/replace-supers");var t=require("../../../types");exports.check=function(node){return t.isIdentifier(node,{name:"super"})};exports.Property=function(node,parent,scope,file){if(!node.method)return;var value=node.value;var thisExpr=scope.generateUidIdentifier("this");var replaceSupers=new ReplaceSupers({topLevelThisReference:thisExpr,methodNode:node,className:thisExpr,isStatic:true,scope:scope,file:file});replaceSupers.replace();if(replaceSupers.hasSuper){value.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(thisExpr,t.thisExpression())]))}}},{"../../../types":121,"../../helpers/replace-supers":42}],72:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.check=function(node){return t.isFunction(node)&&hasDefaults(node)};var hasDefaults=function(node){for(var i=0;i<node.params.length;i++){if(!t.isIdentifier(node.params[i]))return true}return false};var iifeVisitor={enter:function(node,parent,scope,state){if(!t.isReferencedIdentifier(node,parent))return;if(!state.scope.hasOwnBinding(node.name))return;if(state.scope.bindingIdentifierEquals(node.name,node))return;state.iife=true;this.stop()}};exports.Function=function(node,parent,scope,file){if(!hasDefaults(node))return;t.ensureBlock(node);var body=[];var argsIdentifier=t.identifier("arguments");argsIdentifier._ignoreAliasFunctions=true;var lastNonDefaultParam=0;var state={iife:false,scope:scope};var pushDefNode=function(left,right,i){var defNode=util.template("default-parameter",{VARIABLE_NAME:left,DEFAULT_VALUE:right,ARGUMENT_KEY:t.literal(i),ARGUMENTS:argsIdentifier},true);file.checkNode(defNode);defNode._blockHoist=node.params.length-i;body.push(defNode)};for(var i=0;i<node.params.length;i++){var param=node.params[i];if(!t.isAssignmentPattern(param)){if(!t.isRestElement(param)){lastNonDefaultParam=i+1}if(!t.isIdentifier(param)){scope.traverse(param,iifeVisitor,state)}if(file.transformers["es6.blockScopingTDZ"].canRun()){pushDefNode(param,t.identifier("undefined"),i)}continue}var left=param.left;var right=param.right;var placeholder=scope.generateUidIdentifier("x");placeholder._isDefaultPlaceholder=true;node.params[i]=placeholder;if(!state.iife){if(t.isIdentifier(right)&&scope.hasOwnBinding(right.name)){state.iife=true}else{scope.traverse(right,iifeVisitor,state)}}pushDefNode(left,right,i)}node.params=node.params.slice(0,lastNonDefaultParam);if(state.iife){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}}},{"../../../types":121,"../../../util":123}],73:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.check=t.isRestElement;var hasRest=function(node){return t.isRestElement(node.params[node.params.length-1])};exports.Function=function(node,parent,scope){if(!hasRest(node))return;var rest=node.params.pop().argument;var argsId=t.identifier("arguments");argsId._ignoreAliasFunctions=true;var start=t.literal(node.params.length);var key=scope.generateUidIdentifier("key");var len=scope.generateUidIdentifier("len");var arrKey=key;var arrLen=len;if(node.params.length){arrKey=t.binaryExpression("-",key,start);arrLen=t.conditionalExpression(t.binaryExpression(">",len,start),t.binaryExpression("-",len,start),t.literal(0))}if(t.isPattern(rest)){var pattern=rest;rest=scope.generateUidIdentifier("ref");var restDeclar=t.variableDeclaration("var",[t.variableDeclarator(pattern,rest)]);restDeclar._blockHoist=node.params.length+1;node.body.body.unshift(restDeclar)}scope.assignTypeGeneric(rest.name,"Array");var loop=util.template("rest",{ARGUMENTS:argsId,ARRAY_KEY:arrKey,ARRAY_LEN:arrLen,START:start,ARRAY:rest,KEY:key,LEN:len});loop._blockHoist=node.params.length+1;node.body.body.unshift(loop)}},{"../../../types":121,"../../../util":123}],74:[function(require,module,exports){"use strict";var t=require("../../../types");exports.check=function(node){return t.isProperty(node)&&node.computed};exports.ObjectExpression=function(node,parent,scope,file){var hasComputed=false;for(var i=0;i<node.properties.length;i++){hasComputed=t.isProperty(node.properties[i],{computed:true,kind:"init"});if(hasComputed)break}if(!hasComputed)return;var initProps=[];var objId=scope.generateUidBasedOnNode(parent);var body=[];var container=t.functionExpression(null,[],t.blockStatement(body));container._aliasFunction=true;var callback=spec;if(file.isLoose("es6.properties.computed"))callback=loose;var result=callback(node,body,objId,initProps,file);if(result)return result;body.unshift(t.variableDeclaration("var",[t.variableDeclarator(objId,t.objectExpression(initProps))]));body.push(t.returnStatement(objId));return t.callExpression(container,[])};var loose=function(node,body,objId){for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];body.push(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,prop.computed),prop.value)))}};var spec=function(node,body,objId,initProps,file){var props=node.properties;var prop,key;for(var i=0;i<props.length;i++){prop=props[i];if(prop.kind!=="init")continue;key=prop.key;if(!prop.computed&&t.isIdentifier(key)){prop.key=t.literal(key.name)}}var broken=false;for(i=0;i<props.length;i++){prop=props[i];if(prop.computed){broken=true}if(prop.kind!=="init"||!broken||t.isLiteral(t.toComputedKey(prop,prop.key),{value:"__proto__"})){initProps.push(prop);props[i]=null}}for(i=0;i<props.length;i++){prop=props[i];if(!prop)continue;key=prop.key;var bodyNode;if(prop.computed&&t.isMemberExpression(key)&&t.isIdentifier(key.object,{name:"Symbol"})){bodyNode=t.assignmentExpression("=",t.memberExpression(objId,key,true),prop.value)}else{bodyNode=t.callExpression(file.addHelper("define-property"),[objId,key,prop.value])}body.push(t.expressionStatement(bodyNode))}if(body.length===1){var first=body[0].expression;if(t.isCallExpression(first)){first.arguments[0]=t.objectExpression(initProps);return first}}}},{"../../../types":121}],75:[function(require,module,exports){"use strict";var nameMethod=require("../../helpers/name-method");var t=require("../../../types");var clone=require("lodash/lang/clone");exports.check=function(node){return t.isProperty(node)&&(node.method||node.shorthand)};exports.Property=function(node,parent,scope,file){if(node.method){node.method=false;nameMethod.property(node,file,scope)}if(node.shorthand){node.shorthand=false;node.key=t.removeComments(clone(node.key))}}},{"../../../types":121,"../../helpers/name-method":39,"lodash/lang/clone":264}],76:[function(require,module,exports){"use strict";var includes=require("lodash/collection/includes");var t=require("../../../types");exports.check=t.isSpreadElement;var getSpreadLiteral=function(spread,scope){return scope.toArray(spread.argument,true)};var hasSpread=function(nodes){for(var i=0;i<nodes.length;i++){if(t.isSpreadElement(nodes[i])){return true}}return false};var build=function(props,scope){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};for(var i=0;i<props.length;i++){var prop=props[i];if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop,scope))}else{_props.push(prop)}}push();return nodes};exports.ArrayExpression=function(node,parent,scope){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements,scope);var first=nodes.shift();if(!t.isArrayExpression(first)){nodes.unshift(first);first=t.arrayExpression([])}return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node,parent,scope){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.identifier("undefined");node.arguments=[];var nodes;if(args.length===1&&args[0].argument.name==="arguments"){nodes=[args[0].argument]}else{nodes=build(args,scope)}var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){var temp=scope.generateTempBasedOnNode(callee.object);if(temp){callee.object=t.assignmentExpression("=",temp,callee.object);contextLiteral=temp}else{contextLiteral=callee.object}t.appendToMemberExpression(callee,t.identifier("apply"))}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))
}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,scope,file){var args=node.arguments;if(!hasSpread(args))return;var nativeType=t.isIdentifier(node.callee)&&includes(t.NATIVE_TYPE_NAMES,node.callee.name);var nodes=build(args,scope);if(nativeType){nodes.unshift(t.arrayExpression([t.literal(null)]))}var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}if(nativeType){return t.newExpression(t.callExpression(t.memberExpression(file.addHelper("bind"),t.identifier("apply")),[node.callee,args]),[])}else{return t.callExpression(file.addHelper("apply-constructor"),[node.callee,args])}}},{"../../../types":121,"lodash/collection/includes":197}],77:[function(require,module,exports){"use strict";var reduceRight=require("lodash/collection/reduceRight");var messages=require("../../../messages");var flatten=require("lodash/array/flatten");var util=require("../../../util");var map=require("lodash/collection/map");var t=require("../../../types");function returnBlock(expr){return t.blockStatement([t.returnStatement(expr)])}function TailCallTransformer(node,scope,file){this.hasTailRecursion=false;this.needsArguments=false;this.setsArguments=false;this.needsThis=false;this.ownerId=node.id;this.vars=[];this.scope=scope;this.file=file;this.node=node}TailCallTransformer.prototype.getArgumentsId=function(){return this.argumentsId=this.argumentsId||this.scope.generateUidIdentifier("arguments")};TailCallTransformer.prototype.getThisId=function(){return this.thisId=this.thisId||this.scope.generateUidIdentifier("this")};TailCallTransformer.prototype.getLeftId=function(){return this.leftId=this.leftId||this.scope.generateUidIdentifier("left")};TailCallTransformer.prototype.getFunctionId=function(){return this.functionId=this.functionId||this.scope.generateUidIdentifier("function")};TailCallTransformer.prototype.getParams=function(){var params=this.params;if(!params){params=this.node.params;this.paramDecls=[];for(var i=0;i<params.length;i++){var param=params[i];if(!param._isDefaultPlaceholder){this.paramDecls.push(t.variableDeclarator(param,params[i]=this.scope.generateUidIdentifier("x")))}}}return this.params=params};TailCallTransformer.prototype.hasDeopt=function(){var ownerIdInfo=this.scope.getBindingInfo(this.ownerId.name);return ownerIdInfo&&ownerIdInfo.reassigned};TailCallTransformer.prototype.run=function(){var scope=this.scope;var node=this.node;var ownerId=this.ownerId;if(!ownerId)return;scope.traverse(node,firstPass,this);if(!this.hasTailRecursion)return;if(this.hasDeopt()){this.file.logDeopt(node,messages.get("tailCallReassignmentDeopt"));return}scope.traverse(node,secondPass,this);if(!this.needsThis||!this.needsArguments){scope.traverse(node,thirdPass,this)}var body=t.ensureBlock(node).body;if(this.vars.length>0){var declarations=flatten(map(this.vars,function(decl){return decl.declarations},this));var statement=reduceRight(declarations,function(expr,decl){return t.assignmentExpression("=",decl.id,expr)},t.identifier("undefined"));body.unshift(t.expressionStatement(statement))}var paramDecls=this.paramDecls;if(paramDecls.length>0){body.unshift(t.variableDeclaration("var",paramDecls))}node.body=util.template("tail-call-body",{THIS_ID:this.thisId,ARGUMENTS_ID:this.argumentsId,FUNCTION_ID:this.getFunctionId(),BLOCK:node.body});var topVars=[];if(this.needsThis){topVars.push(t.variableDeclarator(this.getThisId(),t.thisExpression()))}if(this.needsArguments||this.setsArguments){var decl=t.variableDeclarator(this.getArgumentsId());if(this.needsArguments){decl.init=t.identifier("arguments")}topVars.push(decl)}var leftId=this.leftId;if(leftId){topVars.push(t.variableDeclarator(leftId))}if(topVars.length>0){node.body.body.unshift(t.variableDeclaration("var",topVars))}};TailCallTransformer.prototype.subTransform=function(node){if(!node)return;var handler=this["subTransform"+node.type];if(handler)return handler.call(this,node)};TailCallTransformer.prototype.subTransformConditionalExpression=function(node){var callConsequent=this.subTransform(node.consequent);var callAlternate=this.subTransform(node.alternate);if(!callConsequent&&!callAlternate){return}node.type="IfStatement";node.consequent=callConsequent?t.toBlock(callConsequent):returnBlock(node.consequent);if(callAlternate){node.alternate=t.isIfStatement(callAlternate)?callAlternate:t.toBlock(callAlternate)}else{node.alternate=returnBlock(node.alternate)}return[node]};TailCallTransformer.prototype.subTransformLogicalExpression=function(node){var callRight=this.subTransform(node.right);if(!callRight)return;var leftId=this.getLeftId();var testExpr=t.assignmentExpression("=",leftId,node.left);if(node.operator==="&&"){testExpr=t.unaryExpression("!",testExpr)}return[t.ifStatement(testExpr,returnBlock(leftId))].concat(callRight)};TailCallTransformer.prototype.subTransformSequenceExpression=function(node){var seq=node.expressions;var lastCall=this.subTransform(seq[seq.length-1]);if(!lastCall){return}if(--seq.length===1){node=seq[0]}return[t.expressionStatement(node)].concat(lastCall)};TailCallTransformer.prototype.subTransformCallExpression=function(node){var callee=node.callee,thisBinding,args;if(t.isMemberExpression(callee,{computed:false})&&t.isIdentifier(callee.property)){switch(callee.property.name){case"call":args=t.arrayExpression(node.arguments.slice(1));break;case"apply":args=node.arguments[1]||t.identifier("undefined");break;default:return}thisBinding=node.arguments[0];callee=callee.object}if(!t.isIdentifier(callee)||!this.scope.bindingIdentifierEquals(callee.name,this.ownerId)){return}this.hasTailRecursion=true;if(this.hasDeopt())return;var body=[];if(!t.isThisExpression(thisBinding)){body.push(t.expressionStatement(t.assignmentExpression("=",this.getThisId(),thisBinding||t.identifier("undefined"))))}if(!args){args=t.arrayExpression(node.arguments)}var argumentsId=this.getArgumentsId();var params=this.getParams();body.push(t.expressionStatement(t.assignmentExpression("=",argumentsId,args)));var i,param;if(t.isArrayExpression(args)){var elems=args.elements;for(i=0;i<elems.length&&i<params.length;i++){param=params[i];var elem=elems[i]||(elems[i]=t.identifier("undefined"));if(!param._isDefaultPlaceholder){elems[i]=t.assignmentExpression("=",param,elem)}}}else{this.setsArguments=true;for(i=0;i<params.length;i++){param=params[i];if(!param._isDefaultPlaceholder){body.push(t.expressionStatement(t.assignmentExpression("=",param,t.memberExpression(argumentsId,t.literal(i),true))))}}}body.push(t.continueStatement(this.getFunctionId()));return body};var firstPass={enter:function(node,parent,scope,state){if(t.isIfStatement(node)){if(t.isReturnStatement(node.alternate)){t.ensureBlock(node,"alternate")}if(t.isReturnStatement(node.consequent)){t.ensureBlock(node,"consequent")}}else if(t.isReturnStatement(node)){this.skip();return state.subTransform(node.argument)}else if(t.isTryStatement(parent)){if(node===parent.block){this.skip()}else if(parent.finalizer&&node!==parent.finalizer){this.skip()}}else if(t.isFunction(node)){this.skip()}else if(t.isVariableDeclaration(node)){this.skip();state.vars.push(node)}}};var secondPass={enter:function(node,parent,scope,state){if(t.isThisExpression(node)){state.needsThis=true;return state.getThisId()}else if(t.isReferencedIdentifier(node,parent,{name:"arguments"})){state.needsArguments=true;return state.getArgumentsId()}else if(t.isFunction(node)){this.skip();if(t.isFunctionDeclaration(node)){node=t.variableDeclaration("var",[t.variableDeclarator(node.id,t.toExpression(node))]);node._blockHoist=2;return node}}}};var thirdPass={enter:function(node,parent,scope,state){if(!t.isExpressionStatement(node))return;var expr=node.expression;if(!t.isAssignmentExpression(expr))return;if(!state.needsThis&&expr.left===state.getThisId()){this.remove()}else if(!state.needsArguments&&expr.left===state.getArgumentsId()&&t.isArrayExpression(expr.right)){return map(expr.right.elements,function(elem){return t.expressionStatement(elem)})}}};exports.Function=function(node,parent,scope,file){var tailCall=new TailCallTransformer(node,scope,file);tailCall.run()}},{"../../../messages":30,"../../../types":121,"../../../util":123,"lodash/array/flatten":189,"lodash/collection/map":198,"lodash/collection/reduceRight":199}],78:[function(require,module,exports){"use strict";var t=require("../../../types");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.check=function(node){return t.isTemplateLiteral(node)||t.isTaggedTemplateExpression(node)};exports.TaggedTemplateExpression=function(node,parent,scope,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];for(var i=0;i<quasi.quasis.length;i++){var elem=quasi.quasis[i];strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))}strings=t.arrayExpression(strings);raw=t.arrayExpression(raw);var templateName="tagged-template-literal";if(file.isLoose("es6.templateLiterals"))templateName+="-loose";args.push(t.callExpression(file.addHelper(templateName),[strings,raw]));args=args.concat(quasi.expressions);return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];var i;for(i=0;i<node.quasis.length;i++){var elem=node.quasis[i];nodes.push(t.literal(elem.value.cooked));var expr=node.expressions.shift();if(expr)nodes.push(expr)}if(nodes.length>1){var last=nodes[nodes.length-1];if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());for(i=0;i<nodes.length;i++){root=buildBinaryExpression(root,nodes[i])}return root}else{return nodes[0]}}},{"../../../types":121}],79:[function(require,module,exports){"use strict";var rewritePattern=require("regexpu/rewrite-pattern");var pull=require("lodash/array/pull");var t=require("../../../types");exports.check=function(node){return t.isLiteral(node)&&node.regex&&node.regex.flags.indexOf("u")>=0};exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(regex.flags.indexOf("u")<0)return;pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{"../../../types":121,"lodash/array/pull":191,"regexpu/rewrite-pattern":306}],80:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.experimental=true;var container=function(parent,call,ret,file){if(t.isExpressionStatement(parent)&&!file.isConsequenceExpressionStatement(parent)){return call}else{var exprs=[];if(t.isSequenceExpression(call)){exprs=call.expressions}else{exprs.push(call)}exprs.push(ret);return t.sequenceExpression(exprs)}};exports.AssignmentExpression=function(node,parent,scope,file){var left=node.left;if(!t.isVirtualPropertyExpression(left))return;var value=node.right;var temp;if(!t.isExpressionStatement(parent)){temp=scope.generateTempBasedOnNode(node.right);if(temp)value=temp}if(node.operator!=="="){value=t.binaryExpression(node.operator[0],util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object}),value)}var call=util.template("abstract-expression-set",{PROPERTY:left.property,OBJECT:left.object,VALUE:value});if(temp){call=t.sequenceExpression([t.assignmentExpression("=",temp,node.right),call])}return container(parent,call,value,file)};exports.UnaryExpression=function(node,parent,scope,file){var arg=node.argument;if(!t.isVirtualPropertyExpression(arg))return;if(node.operator!=="delete")return;var call=util.template("abstract-expression-delete",{PROPERTY:arg.property,OBJECT:arg.object});return container(parent,call,t.literal(true),file)};exports.CallExpression=function(node,parent,scope){var callee=node.callee;if(!t.isVirtualPropertyExpression(callee))return;var temp=scope.generateTempBasedOnNode(callee.object);var call=util.template("abstract-expression-call",{PROPERTY:callee.property,OBJECT:temp||callee.object});call.arguments=call.arguments.concat(node.arguments);if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,callee.object),call])}else{return call}};exports.VirtualPropertyExpression=function(node){return util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object})};exports.PrivateDeclaration=function(node){return t.variableDeclaration("const",node.declarations.map(function(id){return t.variableDeclarator(id,t.newExpression(t.identifier("WeakMap"),[]))}))}},{"../../../types":121,"../../../util":123}],81:[function(require,module,exports){"use strict";var buildComprehension=require("../../helpers/build-comprehension");var traverse=require("../../../traversal");var util=require("../../../util");var t=require("../../../types");exports.experimental=true;exports.ComprehensionExpression=function(node,parent,scope,file){var callback=array;if(node.generator)callback=generator;return callback(node,parent,scope,file)};var generator=function(node){var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);container._aliasFunction=true;body.push(buildComprehension(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])};var array=function(node,parent,scope,file){var uid=scope.generateUidBasedOnNode(parent,file);var container=util.template("array-comprehension-container",{KEY:uid});container.callee._aliasFunction=true;var block=container.callee.body;var body=block.body;if(traverse.hasType(node,scope,"YieldExpression",t.FUNCTION_TYPES)){container.callee.generator=true;container=t.yieldExpression(container,true)}var returnStatement=body.pop();body.push(buildComprehension(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container}},{"../../../traversal":116,"../../../types":121,"../../../util":123,"../../helpers/build-comprehension":34}],82:[function(require,module,exports){"use strict";exports.experimental=true;var build=require("../../helpers/build-binary-assignment-operator-transformer");var t=require("../../../types");var MATH_POW=t.memberExpression(t.identifier("Math"),t.identifier("pow"));build(exports,{operator:"**",build:function(left,right){return t.callExpression(MATH_POW,[left,right])}})},{"../../../types":121,"../../helpers/build-binary-assignment-operator-transformer":33}],83:[function(require,module,exports){"use strict";var t=require("../../../types");exports.experimental=true;exports.manipulateOptions=function(opts){if(opts.whitelist.length)opts.whitelist.push("es6.destructuring")};var hasSpread=function(node){for(var i=0;i<node.properties.length;i++){if(t.isSpreadProperty(node.properties[i])){return true}}return false};exports.ObjectExpression=function(node,parent,scope,file){if(!hasSpread(node))return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(t.isSpreadProperty(prop)){push();args.push(prop.argument)}else{props.push(prop)}}push();if(!t.isObjectExpression(args[0])){args.unshift(t.objectExpression([]))}return t.callExpression(file.addHelper("extends"),args)}},{"../../../types":121}],84:[function(require,module,exports){module.exports={useStrict:require("./other/use-strict"),"validation.undeclaredVariableCheck":require("./validation/undeclared-variable-check"),"validation.noForInOfAssignment":require("./validation/no-for-in-of-assignment"),"validation.setters":require("./validation/setters"),"validation.react":require("./validation/react"),"spec.blockScopedFunctions":require("./spec/block-scoped-functions"),"playground.malletOperator":require("./playground/mallet-operator"),"playground.methodBinding":require("./playground/method-binding"),"playground.memoizationOperator":require("./playground/memoization-operator"),"playground.objectGetterMemoization":require("./playground/object-getter-memoization"),reactCompat:require("./other/react-compat"),flow:require("./other/flow"),react:require("./other/react"),_modules:require("./internal/modules"),"es7.comprehensions":require("./es7/comprehensions"),"es6.arrowFunctions":require("./es6/arrow-functions"),"es6.classes":require("./es6/classes"),asyncToGenerator:require("./other/async-to-generator"),bluebirdCoroutines:require("./other/bluebird-coroutines"),"es6.objectSuper":require("./es6/object-super"),"es7.objectRestSpread":require("./es7/object-rest-spread"),"es7.exponentiationOperator":require("./es7/exponentiation-operator"),"es6.templateLiterals":require("./es6/template-literals"),"es5.properties.mutators":require("./es5/properties.mutators"),"es6.properties.shorthand":require("./es6/properties.shorthand"),"es6.properties.computed":require("./es6/properties.computed"),"es6.forOf":require("./es6/for-of"),"es6.unicodeRegex":require("./es6/unicode-regex"),"es7.abstractReferences":require("./es7/abstract-references"),"es6.constants":require("./es6/constants"),"es6.parameters.rest":require("./es6/parameters.rest"),"es6.spread":require("./es6/spread"),"es6.parameters.default":require("./es6/parameters.default"),"es6.destructuring":require("./es6/destructuring"),"es6.blockScoping":require("./es6/block-scoping"),"es6.blockScopingTDZ":require("./es6/block-scoping-tdz"),"es6.tailCall":require("./es6/tail-call"),regenerator:require("./other/regenerator"),selfContained:require("./other/self-contained"),"es6.modules":require("./es6/modules"),_blockHoist:require("./internal/block-hoist"),"spec.protoToAssign":require("./spec/proto-to-assign"),_declarations:require("./internal/declarations"),_aliasFunctions:require("./internal/alias-functions"),"spec.typeofSymbol":require("./spec/typeof-symbol"),"spec.undefinedToVoid":require("./spec/undefined-to-void"),_moduleFormatter:require("./internal/module-formatter"),"es3.propertyLiterals":require("./es3/property-literals"),"es3.memberExpressionLiterals":require("./es3/member-expression-literals"),"minification.removeDebugger":require("./minification/remove-debugger"),"minification.removeConsoleCalls":require("./minification/remove-console-calls"),"minification.deadCodeElimination":require("./minification/dead-code-elimination"),"minification.renameLocalVariables":require("./minification/rename-local-variables"),_cleanUp:require("./internal/cleanup")}},{"./es3/member-expression-literals":60,"./es3/property-literals":61,"./es5/properties.mutators":62,"./es6/arrow-functions":63,"./es6/block-scoping":65,"./es6/block-scoping-tdz":64,"./es6/classes":66,"./es6/constants":67,"./es6/destructuring":68,"./es6/for-of":69,"./es6/modules":70,"./es6/object-super":71,"./es6/parameters.default":72,"./es6/parameters.rest":73,"./es6/properties.computed":74,"./es6/properties.shorthand":75,"./es6/spread":76,"./es6/tail-call":77,"./es6/template-literals":78,"./es6/unicode-regex":79,"./es7/abstract-references":80,"./es7/comprehensions":81,"./es7/exponentiation-operator":82,"./es7/object-rest-spread":83,"./internal/alias-functions":85,"./internal/block-hoist":86,"./internal/cleanup":87,"./internal/declarations":88,"./internal/module-formatter":89,"./internal/modules":90,"./minification/dead-code-elimination":91,"./minification/remove-console-calls":92,"./minification/remove-debugger":93,"./minification/rename-local-variables":94,"./other/async-to-generator":95,"./other/bluebird-coroutines":96,"./other/flow":97,"./other/react":99,"./other/react-compat":98,"./other/regenerator":100,"./other/self-contained":101,"./other/use-strict":102,"./playground/mallet-operator":103,"./playground/memoization-operator":104,"./playground/method-binding":105,"./playground/object-getter-memoization":106,"./spec/block-scoped-functions":107,"./spec/proto-to-assign":108,"./spec/typeof-symbol":109,"./spec/undefined-to-void":110,"./validation/no-for-in-of-assignment":111,"./validation/react":112,"./validation/setters":113,"./validation/undeclared-variable-check":114}],85:[function(require,module,exports){"use strict";var t=require("../../../types");var functionChildrenVisitor={enter:function(node,parent,scope,state){if(t.isFunction(node)&&!node._aliasFunction){return this.skip()}if(node._ignoreAliasFunctions)return this.skip();var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=state.getArgumentsId}else if(t.isThisExpression(node)){getId=state.getThisId}else{return}if(t.isReferenced(node,parent))return getId()}};var functionVisitor={enter:function(node,parent,scope,state){if(!node._aliasFunction){if(t.isFunction(node)){return this.skip()}else{return}}scope.traverse(node,functionChildrenVisitor,state);return this.skip()}};var go=function(getBody,node,scope){var argumentsId;var thisId;var state={getArgumentsId:function(){return argumentsId=argumentsId||scope.generateUidIdentifier("arguments")},getThisId:function(){return thisId=thisId||scope.generateUidIdentifier("this")}};scope.traverse(node,functionVisitor,state);var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.thisExpression())}};exports.Program=function(node,parent,scope){go(function(){return node.body},node,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,scope){go(function(){t.ensureBlock(node);return node.body.body},node,scope)}},{"../../../types":121}],86:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var groupBy=require("lodash/collection/groupBy");var flatten=require("lodash/array/flatten");var values=require("lodash/object/values");exports.BlockStatement=exports.Program={exit:function(node){var hasChange=false;for(var i=0;i<node.body.length;i++){var bodyNode=node.body[i];if(bodyNode&&bodyNode._blockHoist!=null)hasChange=true}if(!hasChange)return;useStrict.wrap(node,function(){var nodePriorities=groupBy(node.body,function(bodyNode){var priority=bodyNode._blockHoist;if(priority==null)priority=1;if(priority===true)priority=2;return priority});node.body=flatten(values(nodePriorities).reverse())})}}},{"../../helpers/use-strict":43,"lodash/array/flatten":189,"lodash/collection/groupBy":196,"lodash/object/values":286}],87:[function(require,module,exports){exports.SequenceExpression=function(node){if(node.expressions.length===1){return node.expressions[0]}}},{}],88:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var t=require("../../../types");exports.secondPass=true;exports.BlockStatement=exports.Program=function(node,parent,scope,file){if(!node._declarations)return;var kinds={};var kind;useStrict.wrap(node,function(){for(var i in node._declarations){var declar=node._declarations[i];kind=declar.kind||"var";var declarNode=t.variableDeclarator(declar.id,declar.init);if(declar.init){node.body.unshift(file.attachAuxilaryComment(t.variableDeclaration(kind,[declarNode])))}else{kinds[kind]=kinds[kind]||[];kinds[kind].push(declarNode)}}for(kind in kinds){node.body.unshift(file.attachAuxilaryComment(t.variableDeclaration(kind,kinds[kind])))}});node._declarations=null}},{"../../../types":121,"../../helpers/use-strict":43}],89:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");exports.Program=function(program,parent,scope,file){if(!file.transformers["es6.modules"].canRun())return;useStrict.wrap(program,function(){program.body=file.dynamicImports.concat(program.body)});if(file.moduleFormatter.transform){file.moduleFormatter.transform(program)}}},{"../../helpers/use-strict":43}],90:[function(require,module,exports){"use strict";var t=require("../../../types");var resolveModuleSource=function(node,parent,scope,file){var resolveModuleSource=file.opts.resolveModuleSource;if(node.source&&resolveModuleSource){node.source.value=resolveModuleSource(node.source.value)}};exports.check=function(node){return t.isImportDeclaration(node)||t.isExportDeclaration(node)};exports.ImportDeclaration=resolveModuleSource;exports.ExportDeclaration=function(node,parent,scope){resolveModuleSource.apply(null,arguments);var declar=node.declaration;if(node.default){if(t.isClassDeclaration(declar)){node.declaration=declar.id;return[declar,node]}else if(t.isClassExpression(declar)){var temp=scope.generateUidIdentifier("default");declar=t.variableDeclaration("var",[t.variableDeclarator(temp,declar)]);node.declaration=temp;return[declar,node]}else if(t.isFunctionDeclaration(declar)){node._blockHoist=2;node.declaration=declar.id;return[declar,node]}}else{if(t.isFunctionDeclaration(declar)){node.specifiers=[t.importSpecifier(declar.id,declar.id)];node.declaration=null;node._blockHoist=2;return[declar,node]}}}},{"../../../types":121}],91:[function(require,module,exports){var t=require("../../../types");exports.optional=true;exports.ExpressionStatement=function(node){var expr=node.expression;if(t.isLiteral(expr)||t.isIdentifier(node)&&t.hasBinding(node.name)){this.remove()}};exports.IfStatement={exit:function(node){var consequent=node.consequent;var alternate=node.alternate;var test=node.test;if(t.isLiteral(test)&&test.value){return consequent}if(t.isFalsyExpression(test)){if(alternate){return alternate}else{return this.remove()}}if(t.isBlockStatement(alternate)&&!alternate.body.length){alternate=node.alternate=null}if(t.blockStatement(consequent)&&!consequent.body.length&&t.isBlockStatement(alternate)&&alternate.body.length){node.consequent=node.alternate;node.alternate=null;node.test=t.unaryExpression("!",test,true)}}}},{"../../../types":121}],92:[function(require,module,exports){"use strict";var t=require("../../../types");var isConsole=t.buildMatchMemberExpression("console",true);exports.optional=true;exports.CallExpression=function(node,parent){if(isConsole(node.callee)){if(t.isExpressionStatement(parent)){this.parentPath.remove()}else{this.remove()}}}},{"../../../types":121}],93:[function(require,module,exports){var t=require("../../../types");exports.optional=true;exports.ExpressionStatement=function(node){if(t.isIdentifier(node.expression,{name:"debugger"})){this.remove()}}},{"../../../types":121}],94:[function(require,module,exports){exports.optional=true;exports.Scopable=function(){}},{}],95:[function(require,module,exports){"use strict";var remapAsyncToGenerator=require("../../helpers/remap-async-to-generator");var bluebirdCoroutines=require("./bluebird-coroutines");exports.optional=true;exports.manipulateOptions=bluebirdCoroutines.manipulateOptions;exports.Function=function(node,parent,scope,file){if(!node.async||node.generator)return;return remapAsyncToGenerator(node,file.addHelper("async-to-generator"),scope)}},{"../../helpers/remap-async-to-generator":41,"./bluebird-coroutines":96}],96:[function(require,module,exports){"use strict";var remapAsyncToGenerator=require("../../helpers/remap-async-to-generator");var t=require("../../../types");exports.manipulateOptions=function(opts){opts.experimental=true;opts.blacklist.push("regenerator")};exports.optional=true;exports.Function=function(node,parent,scope,file){if(!node.async||node.generator)return;return remapAsyncToGenerator(node,t.memberExpression(file.addImport("bluebird",null,true),t.identifier("coroutine")),scope)}},{"../../../types":121,"../../helpers/remap-async-to-generator":41}],97:[function(require,module,exports){var t=require("../../../types");exports.TypeCastExpression=function(node){return node.expression};exports.ImportDeclaration=function(node){if(node.isType)this.remove()};exports.ExportDeclaration=function(node){if(t.isTypeAlias(node.declaration))this.remove()}},{"../../../types":121}],98:[function(require,module,exports){"use strict";var react=require("../../helpers/react");var t=require("../../../types");exports.manipulateOptions=function(opts){opts.blacklist.push("react")};exports.optional=true;require("../../helpers/build-react-transformer")(exports,{pre:function(state){state.callee=state.tagExpr},post:function(state){if(react.isCompatTag(state.tagName)){state.call=t.callExpression(t.memberExpression(t.memberExpression(t.identifier("React"),t.identifier("DOM")),state.tagExpr,t.isLiteral(state.tagExpr)),state.args)}}})},{"../../../types":121,"../../helpers/build-react-transformer":36,"../../helpers/react":40}],99:[function(require,module,exports){"use strict";var react=require("../../helpers/react");var t=require("../../../types");require("../../helpers/build-react-transformer")(exports,{pre:function(state){var tagName=state.tagName;var args=state.args;if(react.isCompatTag(tagName)){args.push(t.literal(tagName))}else{args.push(state.tagExpr)}},post:function(state){state.callee=t.memberExpression(t.identifier("React"),t.identifier("createElement"))}})},{"../../../types":121,"../../helpers/build-react-transformer":36,"../../helpers/react":40}],100:[function(require,module,exports){"use strict";var regenerator=require("regenerator-6to5");var t=require("../../../types");exports.check=function(node){return t.isFunction(node)&&(node.async||node.generator)};exports.Program={enter:function(ast){regenerator.transform(ast);this.stop()}}},{"../../../types":121,"regenerator-6to5":298}],101:[function(require,module,exports){"use strict";var includes=require("lodash/collection/includes");var util=require("../../../util");var core=require("core-js/library");var has=require("lodash/object/has");var t=require("../../../types");var isSymboliterator=t.buildMatchMemberExpression("Symbol.iterator");var coreHas=function(node){return node.name!=="_"&&has(core,node.name)};var ALIASABLE_CONSTRUCTORS=["Symbol","Promise","Map","WeakMap","Set","WeakSet"];var astVisitor={enter:function(node,parent,scope,file){var prop;if(t.isMemberExpression(node)&&t.isReferenced(node,parent)){var obj=node.object;prop=node.property;if(!t.isReferenced(obj,node))return;if(!node.computed&&coreHas(obj)&&has(core[obj.name],prop.name)&&!scope.getBindingIdentifier(obj.name)){this.skip();return t.prependToMemberExpression(node,file.get("coreIdentifier"))}}else if(t.isReferencedIdentifier(node,parent)&&!t.isMemberExpression(parent)&&includes(ALIASABLE_CONSTRUCTORS,node.name)&&!scope.getBindingIdentifier(node.name)){return t.memberExpression(file.get("coreIdentifier"),node)}else if(t.isCallExpression(node)){var callee=node.callee;if(node.arguments.length)return false;if(!t.isMemberExpression(callee))return false;if(!callee.computed)return false;prop=callee.property;if(!isSymboliterator(prop))return false;return util.template("corejs-iterator",{CORE_ID:file.get("coreIdentifier"),VALUE:callee.object})}else if(t.isBinaryExpression(node)){if(node.operator!=="in")return;var left=node.left;if(!isSymboliterator(left))return;return util.template("corejs-is-iterator",{CORE_ID:file.get("coreIdentifier"),VALUE:node.right})}}};exports.optional=true;exports.manipulateOptions=function(opts){if(opts.whitelist.length)opts.whitelist.push("es6.modules")};exports.Program=function(node,parent,scope,file){scope.traverse(node,astVisitor,file)};exports.pre=function(file){file.setDynamic("runtimeIdentifier",function(){return file.addImport("6to5-runtime/helpers","to5Helpers")});file.setDynamic("coreIdentifier",function(){return file.addImport("6to5-runtime/core-js","core")});file.setDynamic("regeneratorIdentifier",function(){return file.addImport("6to5-runtime/regenerator","regeneratorRuntime")})};exports.Identifier=function(node,parent,scope,file){if(t.isReferencedIdentifier(node,parent,{name:"regeneratorRuntime"})){return file.get("regeneratorIdentifier")}}},{"../../../types":121,"../../../util":123,"core-js/library":173,"lodash/collection/includes":197,"lodash/object/has":282}],102:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var t=require("../../../types");exports.Program=function(program){if(!useStrict.has(program)){program.body.unshift(t.expressionStatement(t.literal("use strict")))}};exports.FunctionDeclaration=exports.FunctionExpression=function(){this.skip()};exports.ThisExpression=function(){return t.identifier("undefined")
}},{"../../../types":121,"../../helpers/use-strict":43}],103:[function(require,module,exports){"use strict";var messages=require("../../../messages");var build=require("../../helpers/build-conditional-assignment-operator-transformer");var t=require("../../../types");exports.playground=true;build(exports,{is:function(node,file){var is=t.isAssignmentExpression(node)&&node.operator==="||=";if(is){var left=node.left;if(!t.isMemberExpression(left)&&!t.isIdentifier(left)){throw file.errorWithNode(left,messages.get("expectedMemberExpressionOrIdentifier"))}return true}},build:function(node){return t.unaryExpression("!",node,true)}})},{"../../../messages":30,"../../../types":121,"../../helpers/build-conditional-assignment-operator-transformer":35}],104:[function(require,module,exports){"use strict";var build=require("../../helpers/build-conditional-assignment-operator-transformer");var t=require("../../../types");exports.playground=true;build(exports,{is:function(node){var is=t.isAssignmentExpression(node)&&node.operator==="?=";if(is)t.assertMemberExpression(node.left);return is},build:function(node,file){return t.unaryExpression("!",t.callExpression(t.memberExpression(file.addHelper("has-own"),t.identifier("call")),[node.object,node.property]),true)}})},{"../../../types":121,"../../helpers/build-conditional-assignment-operator-transformer":35}],105:[function(require,module,exports){"use strict";var t=require("../../../types");exports.playground=true;exports.BindMemberExpression=function(node,parent,scope){var object=node.object;var prop=node.property;var temp=scope.generateTempBasedOnNode(node.object);if(temp)object=temp;var call=t.callExpression(t.memberExpression(t.memberExpression(object,prop),t.identifier("bind")),[object].concat(node.arguments));if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,node.object),call])}else{return call}};exports.BindFunctionExpression=function(node,parent,scope){var buildCall=function(args){var param=scope.generateUidIdentifier("val");return t.functionExpression(null,[param],t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(param,node.callee),args))]))};var temp=scope.generateTemp("args");return t.sequenceExpression([t.assignmentExpression("=",temp,t.arrayExpression(node.arguments)),buildCall(node.arguments.map(function(node,i){return t.memberExpression(temp,t.literal(i),true)}))])}},{"../../../types":121}],106:[function(require,module,exports){"use strict";var t=require("../../../types");exports.playground=true;var visitor={enter:function(node,parent,scope,state){if(t.isFunction(node))return this.skip();if(t.isReturnStatement(node)&&node.argument){node.argument=t.memberExpression(t.callExpression(state.file.addHelper("define-property"),[t.thisExpression(),state.key,node.argument]),state.key,true)}}};exports.Property=exports.MethodDefinition=function(node,parent,scope,file){if(node.kind!=="memo")return;node.kind="get";var value=node.value;t.ensureBlock(value);var key=node.key;if(t.isIdentifier(key)&&!node.computed){key=t.literal(key.name)}var state={key:key,file:file};scope.traverse(value,visitor,state);return node}},{"../../../types":121}],107:[function(require,module,exports){"use strict";var t=require("../../../types");exports.BlockStatement=function(node,parent,scope,file){if(t.isFunction(parent)&&parent.body===node||t.isExportDeclaration(parent)){return}for(var i=0;i<node.body.length;i++){var func=node.body[i];if(!t.isFunctionDeclaration(func))continue;var declar=t.variableDeclaration("let",[t.variableDeclarator(func.id,t.toExpression(func))]);declar._blockHoist=2;func.id=null;node.body[i]=declar;file.checkNode(declar)}}},{"../../../types":121}],108:[function(require,module,exports){"use strict";var t=require("../../../types");var pull=require("lodash/array/pull");var isProtoKey=function(node){return t.isLiteral(t.toComputedKey(node,node.key),{value:"__proto__"})};var isProtoAssignmentExpression=function(node){var left=node.left;return t.isMemberExpression(left)&&t.isLiteral(t.toComputedKey(left,left.property),{value:"__proto__"})};var buildDefaultsCallExpression=function(expr,ref,file){return t.expressionStatement(t.callExpression(file.addHelper("defaults"),[ref,expr.right]))};exports.optional=true;exports.secondPass=true;exports.AssignmentExpression=function(node,parent,scope,file){if(!isProtoAssignmentExpression(node))return;var nodes=[];var left=node.left.object;var temp=scope.generateTempBasedOnNode(node.left.object);nodes.push(t.expressionStatement(t.assignmentExpression("=",temp,left)));nodes.push(buildDefaultsCallExpression(node,temp,file));if(temp)nodes.push(temp);return t.toSequenceExpression(nodes)};exports.ExpressionStatement=function(node,parent,scope,file){var expr=node.expression;if(!t.isAssignmentExpression(expr,{operator:"="}))return;if(isProtoAssignmentExpression(expr)){return buildDefaultsCallExpression(expr,expr.left.object,file)}};exports.ObjectExpression=function(node,parent,scope,file){var proto;for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(isProtoKey(prop)){proto=prop.value;pull(node.properties,prop)}}if(proto){var args=[t.objectExpression([]),proto];if(node.properties.length)args.push(node);return t.callExpression(file.addHelper("extends"),args)}}},{"../../../types":121,"lodash/array/pull":191}],109:[function(require,module,exports){"use strict";var t=require("../../../types");exports.optional=true;exports.UnaryExpression=function(node,parent,scope,file){this.skip();if(node.operator==="typeof"){var call=t.callExpression(file.addHelper("typeof"),[node.argument]);if(t.isIdentifier(node.argument)){var undefLiteral=t.literal("undefined");return t.conditionalExpression(t.binaryExpression("===",t.unaryExpression("typeof",node.argument),undefLiteral),undefLiteral,call)}else{return call}}}},{"../../../types":121}],110:[function(require,module,exports){"use strict";var t=require("../../../types");exports.optional=true;exports.Identifier=function(node,parent){if(node.name==="undefined"&&t.isReferenced(node,parent)){return t.unaryExpression("void",t.literal(0),true)}}},{"../../../types":121}],111:[function(require,module,exports){"use strict";var messages=require("../../../messages");var t=require("../../../types");exports.check=t.isFor;exports.ForInStatement=exports.ForOfStatement=function(node,parent,scope,file){var left=node.left;if(t.isVariableDeclaration(left)){var declar=left.declarations[0];if(declar.init)throw file.errorWithNode(declar,messages.get("noAssignmentsInForHead"))}}},{"../../../messages":30,"../../../types":121}],112:[function(require,module,exports){var messages=require("../../../messages");var t=require("../../../types");var check=function(source,file){if(t.isLiteral(source)){var name=source.value;var lower=name.toLowerCase();if(lower==="react"&&name!==lower){throw file.errorWithNode(source,messages.get("didYouMean","react"))}}};exports.CallExpression=function(node,parent,scope,file){if(t.isIdentifier(node.callee,{name:"require"})&&node.arguments.length===1){check(node.arguments[0],file)}};exports.ImportDeclaration=exports.ExportDeclaration=function(node,parent,scope,file){check(node.source,file)}},{"../../../messages":30,"../../../types":121}],113:[function(require,module,exports){"use strict";var messages=require("../../../messages");exports.check=function(node){return node.kind==="set"};exports.MethodDefinition=exports.Property=function(node,parent,scope,file){if(node.kind==="set"&&node.value.params.length!==1){throw file.errorWithNode(node.value,messages.get("settersInvalidParamLength"))}}},{"../../../messages":30}],114:[function(require,module,exports){"use strict";var levenshtein=require("../../../helpers/levenshtein");var messages=require("../../../messages");var t=require("../../../types");exports.optional=true;exports.Identifier=function(node,parent,scope,file){if(!t.isReferenced(node,parent))return;if(scope.hasBinding(node.name))return;var bindings=scope.getAllBindings();var closest;var shortest=-1;for(var name in bindings){var distance=levenshtein(node.name,name);if(distance<=0||distance>3)continue;if(distance<=shortest)continue;closest=name;shortest=distance}var msg;if(closest){msg=messages.get("undeclaredVariableSuggestion",node.name,closest)}else{msg=messages.get("undeclaredVariable",node.name)}throw file.errorWithNode(node,msg,ReferenceError)}},{"../../../helpers/levenshtein":25,"../../../messages":30,"../../../types":121}],115:[function(require,module,exports){"use strict";module.exports=TraversalContext;var TraversalPath=require("./path");var flatten=require("lodash/array/flatten");var compact=require("lodash/array/compact");function TraversalContext(scope,opts,state,parentPath){this.shouldFlatten=false;this.parentPath=parentPath;this.scope=scope;this.state=state;this.opts=opts}TraversalContext.prototype.flatten=function(){this.shouldFlatten=true};TraversalContext.prototype.visitNode=function(node,obj,key){var iteration=new TraversalPath(this,node,obj,key);return iteration.visit()};TraversalContext.prototype.visit=function(node,key){var nodes=node[key];if(!nodes)return;if(!Array.isArray(nodes)){return this.visitNode(node,node,key)}if(nodes.length===0){return}for(var i=0;i<nodes.length;i++){if(nodes[i]&&this.visitNode(node,nodes,i)){return true}}if(this.shouldFlatten){node[key]=flatten(node[key]);if(key==="body"){node[key]=compact(node[key])}}}},{"./path":117,"lodash/array/compact":188,"lodash/array/flatten":189}],116:[function(require,module,exports){"use strict";module.exports=traverse;var TraversalContext=require("./context");var includes=require("lodash/collection/includes");var t=require("../types");function traverse(parent,opts,scope,state){if(!parent)return;if(!opts.noScope&&!scope){if(parent.type!=="Program"&&parent.type!=="File"){throw new Error("Must pass a scope unless traversing a Program/File got a "+parent.type+" node")}}if(!opts)opts={};if(!opts.enter)opts.enter=function(){};if(!opts.exit)opts.exit=function(){};if(Array.isArray(parent)){for(var i=0;i<parent.length;i++){traverse.node(parent[i],opts,scope,state)}}else{traverse.node(parent,opts,scope,state)}}traverse.node=function(node,opts,scope,state,parentPath){var keys=t.VISITOR_KEYS[node.type];if(!keys)return;var context=new TraversalContext(scope,opts,state,parentPath);for(var i=0;i<keys.length;i++){if(context.visit(node,keys[i])){return}}};function clearNode(node){node._declarations=null;node.extendedRange=null;node._scopeInfo=null;node.tokens=null;node.range=null;node.start=null;node.end=null;node.loc=null;node.raw=null;if(Array.isArray(node.trailingComments)){clearComments(node.trailingComments)}if(Array.isArray(node.leadingComments)){clearComments(node.leadingComments)}}var clearVisitor={noScope:true,enter:clearNode};function clearComments(comments){for(var i=0;i<comments.length;i++){clearNode(comments[i])}}traverse.removeProperties=function(tree){clearNode(tree);traverse(tree,clearVisitor);return tree};traverse.explode=function(obj){for(var type in obj){var fns=obj[type];var aliases=t.FLIPPED_ALIAS_KEYS[type];if(aliases){for(var i=0;i<aliases.length;i++){obj[aliases[i]]=fns}}}return obj};function hasBlacklistedType(node,parent,scope,state){if(node.type===state.type){state.has=true;this.skip()}}traverse.hasType=function(tree,scope,type,blacklistTypes){if(includes(blacklistTypes,tree.type))return false;if(tree.type===type)return true;var state={has:false,type:type};traverse(tree,{blacklist:blacklistTypes,enter:hasBlacklistedType},scope,state);return state.has}},{"../types":121,"./context":115,"lodash/collection/includes":197}],117:[function(require,module,exports){"use strict";module.exports=TraversalPath;var traverse=require("./index");var includes=require("lodash/collection/includes");var Scope=require("./scope");var t=require("../types");function TraversalPath(context,parent,obj,key){this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false;this.parentPath=context.parentPath;this.context=context;this.state=this.context.state;this.opts=this.context.opts;this.key=key;this.obj=obj;this.parent=parent;this.scope=TraversalPath.getScope(this.getNode(),parent,context.scope);this.state=context.state}TraversalPath.prototype.remove=function(){this.shouldRemove=true;this.shouldSkip=true};TraversalPath.prototype.skip=function(){this.shouldSkip=true};TraversalPath.prototype.stop=function(){this.shouldStop=true;this.shouldSkip=true};TraversalPath.prototype.flatten=function(){this.context.flatten()};TraversalPath.getScope=function(node,parent,scope){var ourScope=scope;if(t.isScope(node,parent)){ourScope=new Scope(node,parent,scope)}return ourScope};TraversalPath.prototype.maybeRemove=function(){if(this.shouldRemove){this.setNode(null);this.flatten()}};TraversalPath.prototype.setNode=function(val){return this.obj[this.key]=val};TraversalPath.prototype.getNode=function(){return this.obj[this.key]};TraversalPath.prototype.replaceNode=function(replacement){var isArray=Array.isArray(replacement);var inheritTo=replacement;if(isArray)inheritTo=replacement[0];if(inheritTo)t.inheritsComments(inheritTo,this.getNode());this.setNode(replacement);var file=this.scope&&this.scope.file;if(file){if(isArray){for(var i=0;i<replacement.length;i++){file.checkNode(replacement[i],this.scope)}}else{file.checkNode(replacement,this.scope)}}if(isArray){if(includes(t.STATEMENT_OR_BLOCK_KEYS,this.key)&&!t.isBlockStatement(this.obj)){t.ensureBlock(this.obj,this.key)}this.flatten()}};TraversalPath.prototype.call=function(key){var node=this.getNode();if(!node)return;var opts=this.opts;var fn=opts[key]||opts;if(opts[node.type])fn=opts[node.type][key]||fn;var replacement=fn.call(this,node,this.parent,this.scope,this.state);if(replacement){this.replaceNode(replacement);node=replacement}this.maybeRemove();return node};TraversalPath.prototype.visit=function(){var opts=this.opts;var node=this.getNode();if(opts.blacklist&&opts.blacklist.indexOf(node.type)>-1){return}this.call("enter");if(this.shouldSkip){return this.shouldStop}node=this.getNode();if(Array.isArray(node)){for(var i=0;i<node.length;i++){traverse.node(node[i],opts,this.scope,this.state,this)}}else{traverse.node(node,opts,this.scope,this.state,this);this.call("exit")}return this.shouldStop}},{"../types":121,"./index":116,"./scope":118,"lodash/collection/includes":197}],118:[function(require,module,exports){"use strict";module.exports=Scope;var includes=require("lodash/collection/includes");var traverse=require("./index");var defaults=require("lodash/object/defaults");var messages=require("../messages");var globals=require("globals");var flatten=require("lodash/array/flatten");var extend=require("lodash/object/extend");var object=require("../helpers/object");var each=require("lodash/collection/each");var t=require("../types");function Scope(block,parentBlock,parent,file){this.parent=parent;this.file=parent?parent.file:file;this.parentBlock=parentBlock;this.block=block;this.crawl()}Scope.globals=flatten([globals.builtin,globals.browser,globals.node].map(Object.keys));Scope.prototype.traverse=function(node,opts,state){traverse(node,opts,this,state)};Scope.prototype.generateTemp=function(name){var id=this.generateUidIdentifier(name||"temp");this.push({key:id.name,id:id});return id};Scope.prototype.generateUidIdentifier=function(name){var id=t.identifier(this.generateUid(name));this.getFunctionParent().registerBinding("uid",id);return id};Scope.prototype.generateUid=function(name){name=t.toIdentifier(name).replace(/^_+/,"");var uid;var i=0;do{uid=this._generateUid(name,i);i++}while(this.hasBinding(uid)||this.hasGlobal(uid));return uid};Scope.prototype._generateUid=function(name,i){var id=name;if(i>1)id+=i;return"_"+id};Scope.prototype.generateUidBasedOnNode=function(parent){var node=parent;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}else if(t.isProperty(node)){node=node.key}var parts=[];var add=function(node){if(t.isMemberExpression(node)){add(node.object);add(node.property)}else if(t.isIdentifier(node)){parts.push(node.name)}else if(t.isLiteral(node)){parts.push(node.value)}else if(t.isCallExpression(node)){add(node.callee)}};add(node);var id=parts.join("$");id=id.replace(/^_/,"")||"ref";return this.generateUidIdentifier(id)};Scope.prototype.generateTempBasedOnNode=function(node){if(t.isIdentifier(node)&&this.hasBinding(node.name)){return null}var id=this.generateUidBasedOnNode(node);this.push({key:id.name,id:id});return id};Scope.prototype.checkBlockScopedCollisions=function(kind,name,id){var local=this.getOwnBindingInfo(name);if(!local)return;if(kind==="param")return;if(kind==="hoisted"&&local.kind==="let")return;if(local.kind==="let"||local.kind==="const"||local.kind==="module"){throw this.file.errorWithNode(id,messages.get("scopeDuplicateDeclaration",name),TypeError)}};Scope.prototype.rename=function(oldName,newName){newName=newName||this.generateUidIdentifier(oldName).name;var info=this.getBindingInfo(oldName);if(!info)return;var binding=info.identifier;var scope=info.scope;scope.traverse(scope.block,{enter:function(node,parent,scope){if(t.isReferencedIdentifier(node,parent)&&node.name===oldName){node.name=newName}else if(t.isDeclaration(node)){var ids=t.getBindingIdentifiers(node);for(var name in ids){if(name===oldName)ids[name].name=newName}}else if(t.isScope(node,parent)){if(!scope.bindingIdentifierEquals(oldName,binding)){this.skip()}}}});this.clearOwnBinding(oldName);scope.bindings[newName]=info;binding.name=newName};Scope.prototype.inferType=function(node){var target;if(t.isVariableDeclarator(node)){target=node.init}if(t.isArrayExpression(target)){return t.genericTypeAnnotation(t.identifier("Array"))}if(t.isObjectExpression(target)){return}if(t.isLiteral(target)){return}if(t.isCallExpression(target)&&t.isIdentifier(target.callee)){var funcInfo=this.getBindingInfo(target.callee.name);if(funcInfo){var funcNode=funcInfo.node;return!funcInfo.reassigned&&t.isFunction(funcNode)&&node.returnType}}if(t.isIdentifier(target)){return}};Scope.prototype.isTypeGeneric=function(name,genericName){var info=this.getBindingInfo(name);if(!info)return false;var type=info.typeAnnotation;return t.isGenericTypeAnnotation(type)&&t.isIdentifier(type.id,{name:genericName})};Scope.prototype.assignTypeGeneric=function(name,type){this.assignType(name,t.genericTypeAnnotation(t.identifier(type)))};Scope.prototype.assignType=function(name,type){var info=this.getBindingInfo(name);if(!info)return;info.identifier.typeAnnotation=info.typeAnnotation=type};Scope.prototype.getTypeAnnotation=function(name,id,node){var info={annotation:null,inferred:false};var type;if(id.typeAnnotation){type=id.typeAnnotation}if(!type){info.inferred=true;type=this.inferType(node)}if(type){if(t.isTypeAnnotation(type))type=type.typeAnnotation;info.annotation=type}return info};Scope.prototype.toArray=function(node,i){var file=this.file;if(t.isIdentifier(node)&&this.isTypeGeneric(node.name,"Array")){return node}if(t.isArrayExpression(node)){return node}if(t.isIdentifier(node,{name:"arguments"})){return t.callExpression(t.memberExpression(file.addHelper("slice"),t.identifier("call")),[node])}var helperName="to-array";var args=[node];if(i===true){helperName="to-consumable-array"}else if(i){args.push(t.literal(i));helperName="sliced-to-array"}return t.callExpression(file.addHelper(helperName),args)};Scope.prototype.clearOwnBinding=function(name){delete this.bindings[name]};Scope.prototype.registerDeclaration=function(node){if(t.isFunctionDeclaration(node)){this.registerBinding("hoisted",node)}else if(t.isVariableDeclaration(node)){for(var i=0;i<node.declarations.length;i++){this.registerBinding(node.kind,node.declarations[i])}}else if(t.isClassDeclaration(node)){this.registerBinding("let",node)}else if(t.isImportDeclaration(node)||t.isExportDeclaration(node)){this.registerBinding("module",node)}else{this.registerBinding("unknown",node)}};Scope.prototype.registerBindingReassignment=function(node){var ids=t.getBindingIdentifiers(node);for(var name in ids){var info=this.getBindingInfo(name);if(info){info.reassigned=true;if(info.typeAnnotationInferred){info.typeAnnotation=null}}}};Scope.prototype.registerBinding=function(kind,node){if(!kind)throw new ReferenceError("no `kind`");var ids=t.getBindingIdentifiers(node);for(var name in ids){var id=ids[name];this.checkBlockScopedCollisions(kind,name,id);var typeInfo=this.getTypeAnnotation(name,id,node);this.bindings[name]={typeAnnotationInferred:typeInfo.inferred,typeAnnotation:typeInfo.annotation,reassigned:false,identifier:id,scope:this,node:node,kind:kind}}};Scope.prototype.registerVariableDeclaration=function(declar){var declars=declar.declarations;for(var i=0;i<declars.length;i++){this.registerBinding(declars[i],declar.kind)}};var functionVariableVisitor={enter:function(node,parent,scope,state){if(t.isFor(node)){each(t.FOR_INIT_KEYS,function(key){var declar=node[key];if(t.isVar(declar))state.scope.registerBinding("var",declar)})}if(t.isFunction(node))return this.skip();if(state.blockId&&node===state.blockId)return;if(t.isBlockScoped(node))return;if(t.isExportDeclaration(node)&&t.isDeclaration(node.declaration))return;if(t.isDeclaration(node))state.scope.registerDeclaration(node)}};Scope.prototype.addGlobal=function(node){this.globals[node.name]=node};Scope.prototype.hasGlobal=function(name){var scope=this;do{if(scope.globals[name])return true}while(scope=scope.parent);return false};var programReferenceVisitor={enter:function(node,parent,scope,state){if(t.isReferencedIdentifier(node,parent)&&!scope.hasBinding(node.name)){state.addGlobal(node)}else if(t.isLabeledStatement(node)){state.addGlobal(node)}else if(t.isAssignmentExpression(node)||t.isUpdateExpression(node)||t.isUnaryExpression(node)&&node.operator==="delete"){scope.registerBindingReassignment(node)}}};var blockVariableVisitor={enter:function(node,parent,scope,state){if(t.isFunctionDeclaration(node)||t.isBlockScoped(node)){state.registerDeclaration(node)}else if(t.isScope(node,parent)){this.skip()}}};Scope.prototype.crawl=function(){var block=this.block;var i;var info=block._scopeInfo;if(info){extend(this,info);return}info=block._scopeInfo={bindings:object(),globals:object()};extend(this,info);if(t.isLoop(block)){for(i=0;i<t.FOR_INIT_KEYS.length;i++){var node=block[t.FOR_INIT_KEYS[i]];if(t.isBlockScoped(node))this.registerBinding("let",node)}if(t.isBlockStatement(block.body)){block=block.body}}if(t.isFunctionExpression(block)&&block.id){if(!t.isProperty(this.parentBlock,{method:true})){this.registerBinding("var",block.id)}}if(t.isFunction(block)){for(i=0;i<block.params.length;i++){this.registerBinding("param",block.params[i])}this.traverse(block.body,blockVariableVisitor,this)}if(t.isBlockStatement(block)||t.isProgram(block)){this.traverse(block,blockVariableVisitor,this)}if(t.isCatchClause(block)){this.registerBinding("let",block.param)}if(t.isComprehensionExpression(block)){this.registerBinding("let",block)}if(t.isProgram(block)||t.isFunction(block)){this.traverse(block,functionVariableVisitor,{blockId:block.id,scope:this})}if(t.isProgram(block)){this.traverse(block,programReferenceVisitor,this)}};Scope.prototype.push=function(opts){var block=this.block;if(t.isFor(block)||t.isCatchClause(block)||t.isFunction(block)){t.ensureBlock(block);block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){block._declarations=block._declarations||{};block._declarations[opts.key]={kind:opts.kind,id:opts.id,init:opts.init}}else{throw new TypeError("cannot add a declaration here in node type "+block.type)}};Scope.prototype.getFunctionParent=function(){var scope=this;while(scope.parent&&!t.isFunction(scope.block)){scope=scope.parent}return scope};Scope.prototype.getAllBindings=function(){var ids=object();var scope=this;do{defaults(ids,scope.bindings);scope=scope.parent}while(scope);return ids};Scope.prototype.getAllBindingsOfKind=function(kind){var ids=object();var scope=this;do{for(var name in scope.bindings){var binding=scope.bindings[name];if(binding.kind===kind)ids[name]=binding}scope=scope.parent}while(scope);return ids};Scope.prototype.bindingIdentifierEquals=function(name,node){return this.getBindingIdentifier(name)===node};Scope.prototype.getBindingInfo=function(name){var scope=this;do{var binding=scope.getOwnBindingInfo(name);if(binding)return binding}while(scope=scope.parent)};Scope.prototype.getOwnBindingInfo=function(name){return this.bindings[name]};Scope.prototype.getBindingIdentifier=function(name){var info=this.getBindingInfo(name);return info&&info.identifier};Scope.prototype.getOwnBindingIdentifier=function(name){var binding=this.bindings[name];return binding&&binding.identifier};Scope.prototype.hasOwnBinding=function(name){return!!this.getOwnBindingInfo(name)};Scope.prototype.hasBinding=function(name){if(!name)return false;if(this.hasOwnBinding(name))return true;if(this.parentHasBinding(name))return true;if(includes(Scope.globals,name))return true;return false};Scope.prototype.parentHasBinding=function(name){return this.parent&&this.parent.hasBinding(name)}},{"../helpers/object":27,"../messages":30,"../types":121,"./index":116,globals:186,"lodash/array/flatten":189,"lodash/collection/each":194,"lodash/collection/includes":197,"lodash/object/defaults":280,"lodash/object/extend":281}],119:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While","Scopable"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While","Scopable"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],PrivateDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scopable","Function","Expression"],FunctionDeclaration:["Statement","Declaration","Scopable","Function"],FunctionExpression:["Scopable","Function","Expression"],ImportSpecifier:["ModuleSpecifier"],ExportSpecifier:["ModuleSpecifier"],BlockStatement:["Statement","Scopable"],Program:["Scopable"],CatchClause:["Scopable"],LogicalExpression:["Binary","Expression"],BinaryExpression:["Binary","Expression"],UnaryExpression:["UnaryLike","Expression"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class","Expression"],ForOfStatement:["Statement","For","Scopable","Loop"],ForInStatement:["Statement","For","Scopable","Loop"],ForStatement:["Statement","For","Scopable","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],AssignmentPattern:["Pattern"],Property:["UserWhitespacable"],JSXElement:["UserWhitespacable","Expression"],ArrayExpression:["Expression"],AssignmentExpression:["Expression"],AwaitExpression:["Expression"],BindFunctionExpression:["Expression"],BindMemberExpression:["Expression"],CallExpression:["Expression"],ComprehensionExpression:["Expression","Scopable"],ConditionalExpression:["Expression"],Identifier:["Expression"],Literal:["Expression"],MemberExpression:["Expression"],NewExpression:["Expression"],ObjectExpression:["Expression"],SequenceExpression:["Expression"],TaggedTemplateExpression:["Expression"],ThisExpression:["Expression"],UpdateExpression:["Expression"],VirtualPropertyExpression:["Expression"],JSXEmptyExpression:["Expression"],JSXMemberExpression:["Expression"],YieldExpression:["Expression"],JSXAttribute:["JSX"],JSXClosingElement:["JSX"],JSXElement:["JSX"],JSXEmptyExpression:["JSX"],JSXExpressionContainer:["JSX"],JSXIdentifier:["JSX"],JSXMemberExpression:["JSX"],JSXNamespacedName:["JSX"],JSXOpeningElement:["JSX"],JSXSpreadAttribute:["JSX"]}},{}],120:[function(require,module,exports){module.exports={ArrayExpression:{elements:null},ArrowFunctionExpression:{params:null,body:null},AssignmentExpression:{operator:null,left:null,right:null},BinaryExpression:{operator:null,left:null,right:null},BlockStatement:{body:null},CallExpression:{callee:null,arguments:null},ConditionalExpression:{test:null,consequent:null,alternate:null},ExpressionStatement:{expression:null},File:{program:null,comments:null,tokens:null},FunctionExpression:{id:null,params:null,body:null,generator:false},FunctionDeclaration:{id:null,params:null,body:null,generator:false},GenericTypeAnnotation:{id:null,typeParameters:null},Identifier:{name:null},IfStatement:{test:null,consequent:null,alternate:null},ImportDeclaration:{specifiers:null,source:null},ImportSpecifier:{id:null,name:null},Literal:{value:null},LogicalExpression:{operator:null,left:null,right:null},MemberExpression:{object:null,property:null,computed:false},MethodDefinition:{key:null,value:null,computed:false,"static":false,kind:null},NewExpression:{callee:null,arguments:null},ObjectExpression:{properties:null},Program:{body:null},Property:{kind:null,key:null,value:null,computed:false},ReturnStatement:{argument:null},SequenceExpression:{expressions:null},ThrowExpression:{argument:null},UnaryExpression:{operator:null,argument:null,prefix:null},VariableDeclaration:{kind:null,declarations:null},VariableDeclarator:{id:null,init:null},WithStatement:{object:null,body:null},YieldExpression:{argument:null,delegate:null}}},{}],121:[function(require,module,exports){"use strict";var toFastProperties=require("../helpers/to-fast-properties");var isString=require("lodash/lang/isString");var compact=require("lodash/array/compact");var esutils=require("esutils");var object=require("../helpers/object");var each=require("lodash/collection/each");var uniq=require("lodash/array/uniq");var t=exports;function registerType(type,skipAliasCheck){var is=t["is"+type]=function(node,opts){return t.is(type,node,opts,skipAliasCheck)};t["assert"+type]=function(node,opts){opts=opts||{};if(!is(node,opts)){throw new Error("Expected type "+JSON.stringify(type)+" with option "+JSON.stringify(opts))}}}t.STATEMENT_OR_BLOCK_KEYS=["consequent","body"];t.NATIVE_TYPE_NAMES=["Array","Object","Number","Boolean","Date","Array","String"];t.FOR_INIT_KEYS=["left","init"];t.VISITOR_KEYS=require("./visitor-keys");t.ALIAS_KEYS=require("./alias-keys");t.FLIPPED_ALIAS_KEYS={};each(t.VISITOR_KEYS,function(keys,type){registerType(type,true)});each(t.ALIAS_KEYS,function(aliases,type){each(aliases,function(alias){var types=t.FLIPPED_ALIAS_KEYS[alias]=t.FLIPPED_ALIAS_KEYS[alias]||[];types.push(type)})});each(t.FLIPPED_ALIAS_KEYS,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;registerType(type,false)});t.is=function(type,node,opts,skipAliasCheck){if(!node)return false;var typeMatches=type===node.type;if(!typeMatches&&!skipAliasCheck){var aliases=t.FLIPPED_ALIAS_KEYS[type];if(typeof aliases!=="undefined"){typeMatches=aliases.indexOf(node.type)>-1}}if(!typeMatches){return false}if(typeof opts!=="undefined"){return t.shallowEqual(node,opts)}return true};t.BUILDER_KEYS=require("./builder-keys");each(t.VISITOR_KEYS,function(keys,type){if(t.BUILDER_KEYS[type])return;var defs={};each(keys,function(key){defs[key]=null});t.BUILDER_KEYS[type]=defs});each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var node={};node.start=null;node.type=type;var i=0;for(var key in keys){var arg=arguments[i++];if(arg===undefined)arg=keys[key];node[key]=arg}return node}});t.toComputedKey=function(node,key){if(!node.computed){if(t.isIdentifier(key))key=t.literal(key.name)}return key};t.isFalsyExpression=function(node){if(t.isLiteral(node)){return!node.value}else if(t.isIdentifier(node)){return node.name==="undefined"}return false};t.toSequenceExpression=function(nodes,scope){var exprs=[];each(nodes,function(node){if(t.isExpression(node)){exprs.push(node)}if(t.isExpressionStatement(node)){exprs.push(node.expression)}else if(t.isVariableDeclaration(node)){each(node.declarations,function(declar){scope.push({kind:node.kind,key:declar.id.name,id:declar.id});
exprs.push(t.assignmentExpression("=",declar.id,declar.init))})}});if(exprs.length===1){return exprs[0]}else{return t.sequenceExpression(exprs)}};t.shallowEqual=function(actual,expected){var keys=Object.keys(expected);for(var i=0;i<keys.length;i++){var key=keys[i];if(actual[key]!==expected[key]){return false}}return true};t.appendToMemberExpression=function(member,append,computed){member.object=t.memberExpression(member.object,member.property,member.computed);member.property=append;member.computed=!!computed;return member};t.prependToMemberExpression=function(member,append){member.object=t.memberExpression(append,member.object);return member};t.isReferenced=function(node,parent){if(t.isMemberExpression(parent)){if(parent.property===node&&parent.computed){return true}else if(parent.object===node){return true}else{return false}}if(t.isProperty(parent)&&parent.key===node){return parent.computed}if(t.isVariableDeclarator(parent)){return parent.id!==node}if(t.isFunction(parent)){for(var i=0;i<parent.params.length;i++){var param=parent.params[i];if(param===node)return false}return parent.id!==node}if(t.isClass(parent)){return parent.id!==node}if(t.isMethodDefinition(parent)){return parent.key===node&&parent.computed}if(t.isLabeledStatement(parent)){return false}if(t.isCatchClause(parent)){return parent.param!==node}if(t.isRestElement(parent)){return false}if(t.isAssignmentPattern(parent)){return parent.right===node}if(t.isPattern(parent)){return false}if(t.isImportSpecifier(parent)){return false}if(t.isImportBatchSpecifier(parent)){return false}if(t.isPrivateDeclaration(parent)){return false}return true};t.isReferencedIdentifier=function(node,parent,opts){return t.isIdentifier(node,opts)&&t.isReferenced(node,parent)};t.isValidIdentifier=function(name){return isString(name)&&esutils.keyword.isIdentifierName(name)&&!esutils.keyword.isReservedWordES6(name,true)};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name+"";name=name.replace(/[^a-zA-Z0-9$_]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});if(!t.isValidIdentifier(name)){name="_"+name}return name||"_"};t.ensureBlock=function(node,key){key=key||"body";return node[key]=t.toBlock(node[key],node)};t.buildMatchMemberExpression=function(match,allowPartial){var parts=match.split(".");return function(member){if(!t.isMemberExpression(member))return false;var search=[member];var i=0;while(search.length){var node=search.shift();if(allowPartial&&i===parts.length){return true}if(t.isIdentifier(node)){if(parts[i]!==node.name)return false}else if(t.isLiteral(node)){if(parts[i]!==node.value)return false}else if(t.isMemberExpression(node)){if(node.computed&&!t.isLiteral(node.property)){return false}else{search.push(node.object);search.push(node.property);continue}}else{return false}if(++i>parts.length){return false}}return true}};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}else if(t.isAssignmentExpression(node)){return t.expressionStatement(node)}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};exports.toExpression=function(node){if(t.isExpressionStatement(node)){node=node.expression}if(t.isClass(node)){node.type="ClassExpression"}else if(t.isFunction(node)){node.type="FunctionExpression"}if(t.isExpression(node)){return node}else{throw new Error("cannot turn "+node.type+" to an expression")}};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(t.isEmptyStatement(node)){node=[]}if(!Array.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getBindingIdentifiers=function(node){var search=[].concat(node);var ids=object();while(search.length){var id=search.shift();if(!id)continue;var keys=t.getBindingIdentifiers.keys[id.type];if(t.isIdentifier(id)){ids[id.name]=id}else if(t.isImportSpecifier(id)){search.push(id.name||id.id)}else if(t.isExportDeclaration(id)){if(t.isDeclaration(node.declaration)){search.push(node.declaration)}}else if(keys){for(var i=0;i<keys.length;i++){var key=keys[i];search=search.concat(id[key]||[])}}}return ids};t.getBindingIdentifiers.keys={UnaryExpression:["argument"],AssignmentExpression:["left"],ImportBatchSpecifier:["name"],VariableDeclarator:["id"],FunctionDeclaration:["id"],ClassDeclaration:["id"],SpreadElement:["argument"],RestElement:["argument"],UpdateExpression:["argument"],SpreadProperty:["argument"],Property:["value"],ComprehensionBlock:["left"],AssignmentPattern:["left"],PrivateDeclaration:["declarations"],ComprehensionExpression:["blocks"],ImportDeclaration:["specifiers"],VariableDeclaration:["declarations"],ArrayPattern:["elements"],ObjectPattern:["properties"]};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isBlockScoped=function(node){return t.isFunctionDeclaration(node)||t.isClassDeclaration(node)||t.isLet(node)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.COMMENT_KEYS=["leadingComments","trailingComments"];t.removeComments=function(child){each(t.COMMENT_KEYS,function(key){delete child[key]});return child};t.inheritsComments=function(child,parent){each(t.COMMENT_KEYS,function(key){child[key]=uniq(compact([].concat(child[key],parent[key])))});return child};t.inherits=function(child,parent){child._declarations=parent._declarations;child._scopeInfo=parent._scopeInfo;child.range=parent.range;child.start=parent.start;child.loc=parent.loc;child.end=parent.end;t.inheritsComments(child,parent);return child};t.getLastStatements=function(node){var nodes=[];var add=function(node){nodes=nodes.concat(t.getLastStatements(node))};if(t.isIfStatement(node)){add(node.consequent);add(node.alternate)}else if(t.isFor(node)||t.isWhile(node)){add(node.body)}else if(t.isProgram(node)||t.isBlockStatement(node)){add(node.body[node.body.length-1])}else if(node){nodes.push(node)}return nodes};t.getSpecifierName=function(specifier){return specifier.name||specifier.id};t.getSpecifierId=function(specifier){if(specifier.default){return t.identifier("default")}else{return specifier.id}};t.isSpecifierDefault=function(specifier){return specifier.default||t.isIdentifier(specifier.id)&&specifier.id.name==="default"};t.isScope=function(node,parent){if(t.isBlockStatement(node)){if(t.isLoop(parent.block,{body:node})){return false}if(t.isFunction(parent.block,{body:node})){return false}}return t.isScopable(node)};toFastProperties(t);toFastProperties(t.VISITOR_KEYS)},{"../helpers/object":27,"../helpers/to-fast-properties":29,"./alias-keys":119,"./builder-keys":120,"./visitor-keys":122,esutils:184,"lodash/array/compact":188,"lodash/array/uniq":192,"lodash/collection/each":194,"lodash/lang/isString":276}],122:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindFunctionExpression:["callee","arguments"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateDeclaration:["declarations"],Program:["body"],Property:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],AnyTypeAnnotation:[],ArrayTypeAnnotation:[],BooleanTypeAnnotation:[],ClassProperty:["key","value"],DeclareClass:[],DeclareFunction:[],DeclareModule:[],DeclareVariable:[],FunctionTypeAnnotation:[],FunctionTypeParam:[],GenericTypeAnnotation:[],InterfaceExtends:[],InterfaceDeclaration:[],IntersectionTypeAnnotation:[],NullableTypeAnnotation:[],NumberTypeAnnotation:[],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],TupleTypeAnnotation:[],TypeofTypeAnnotation:[],TypeAlias:[],TypeAnnotation:[],TypeCastExpression:["expression"],TypeParameterDeclaration:[],TypeParameterInstantiation:[],ObjectTypeAnnotation:[],ObjectTypeCallProperty:[],ObjectTypeIndexer:[],ObjectTypeProperty:[],QualifiedTypeIdentifier:[],UnionTypeAnnotation:[],VoidTypeAnnotation:[],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXElement:["openingElement","closingElement","children"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes"],JSXSpreadAttribute:["argument"]}},{}],123:[function(require,module,exports){(function(Buffer,__dirname){"use strict";require("./patch");var cloneDeep=require("lodash/lang/cloneDeep");var contains=require("lodash/collection/contains");var traverse=require("./traversal");var isNumber=require("lodash/lang/isNumber");var isString=require("lodash/lang/isString");var isRegExp=require("lodash/lang/isRegExp");var isEmpty=require("lodash/lang/isEmpty");var parse=require("./helpers/parse");var debug=require("debug/node");var path=require("path");var util=require("util");var each=require("lodash/collection/each");var has=require("lodash/object/has");var fs=require("fs");var t=require("./types");exports.inherits=util.inherits;exports.debug=debug("6to5");exports.canCompile=function(filename,altExts){var exts=altExts||exports.canCompile.EXTENSIONS;var ext=path.extname(filename);return contains(exts,ext)};exports.canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"];exports.normalisePathSeparator=function(filename){return filename.replace(/\\/g,"/")};exports.isInteger=function(i){return isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.regexify=function(val){if(!val)return new RegExp(/.^/);if(Array.isArray(val))val=val.join("|");if(isString(val))return new RegExp(val);if(isRegExp(val))return val;throw new TypeError("illegal type for regexify")};exports.arrayify=function(val){if(!val)return[];if(isString(val))return exports.list(val);if(Array.isArray(val))return val;throw new TypeError("illegal type for arrayify")};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};var templateVisitor={enter:function(node,parent,scope,nodes){if(t.isExpressionStatement(node)){node=node.expression}if(t.isIdentifier(node)&&has(nodes,node.name)){this.skip();return nodes[node.name]}}};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=cloneDeep(template);if(!isEmpty(nodes)){traverse(template,templateVisitor,null,nodes)}if(template.body.length>1)return template.body;var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){return node.expression}else{return node}};exports.repeat=function(width,cha){cha=cha||" ";var result="";for(var i=0;i<width;i++){result+=cha}return result};exports.parseTemplate=function(loc,code){var ast=parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/transformation/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://github.com/6to5/6to5/issues")}each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":320,"./helpers/parse":28,"./patch":31,"./traversal":116,"./types":121,buffer:140,"debug/node":175,fs:138,"lodash/collection/contains":193,"lodash/collection/each":194,"lodash/lang/cloneDeep":265,"lodash/lang/isEmpty":269,"lodash/lang/isNumber":272,"lodash/lang/isRegExp":275,"lodash/lang/isString":276,"lodash/object/has":282,path:147,util:164}],124:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Printable").field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("Node").bases("Printable").field("type",isString);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]).field("comments",or([or(def("Block"),def("Line"))],null),defaults["null"],true);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp));def("Block").bases("Printable").build("loc","value").field("value",isString);def("Line").bases("Printable").build("loc","value").field("value",isString)},{"../lib/shared":135,"../lib/types":136}],125:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":136,"./core":124}],126:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("PropertyPattern").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("value",def("Function")).field("computed",isBoolean,defaults["false"]);def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("key").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]).field("implements",[def("ClassImplements")],defaults.emptyArray);def("ClassImplements").bases("Node").build("id").field("id",def("Identifier")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":135,"../lib/types":136,"./core":124}],127:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":135,"../lib/types":136,"./core":124}],128:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name
}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]);def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("Type").bases("Node");def("AnyTypeAnnotation").bases("Type");def("VoidTypeAnnotation").bases("Type");def("NumberTypeAnnotation").bases("Type");def("StringTypeAnnotation").bases("Type");def("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",isString).field("raw",isString);def("BooleanTypeAnnotation").bases("Type");def("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",def("Type"));def("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",def("Type"));def("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[def("FunctionTypeParam")]).field("returnType",def("Type")).field("rest",or(def("FunctionTypeParam"),null)).field("typeParameters",or(def("TypeParameterDeclaration"),null));def("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",def("Identifier")).field("typeAnnotation",def("Type")).field("optional",isBoolean);def("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",def("Type"));def("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[def("ObjectTypeProperty")]).field("indexers",[def("ObjectTypeIndexer")],defaults.emptyArray).field("callProperties",[def("ObjectTypeCallProperty")],defaults.emptyArray);def("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",or(def("Literal"),def("Identifier"))).field("value",def("Type")).field("optional",isBoolean);def("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",def("Identifier")).field("key",def("Type")).field("value",def("Type"));def("ObjectTypeCallProperty").bases("Node").build("value").field("value",def("FunctionTypeAnnotation")).field("static",isBoolean,false);def("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("id",def("Identifier"));def("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("MemberTypeAnnotation").bases("Type").build("object","property").field("object",def("Identifier")).field("property",or(def("MemberTypeAnnotation"),def("GenericTypeAnnotation")));def("UnionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",def("Type"));def("Identifier").field("typeAnnotation",or(def("TypeAnnotation"),null),defaults["null"]);def("TypeParameterDeclaration").bases("Node").build("params").field("params",[def("Identifier")]);def("TypeParameterInstantiation").bases("Node").build("params").field("params",[def("Type")]);def("Function").field("returnType",or(def("TypeAnnotation"),null),defaults["null"]).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]);def("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",def("TypeAnnotation")).field("static",isBoolean,false);def("ClassImplements").field("typeParameters",or(def("TypeParameterInstantiation"),null),defaults["null"]);def("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]).field("body",def("ObjectTypeAnnotation")).field("extends",[def("InterfaceExtends")]);def("InterfaceExtends").bases("Node").build("id").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null)).field("right",def("Type"));def("TupleTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("DeclareVariable").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareFunction").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareClass").bases("InterfaceDeclaration").build("id");def("DeclareModule").bases("Statement").build("id","body").field("id",or(def("Identifier"),def("Literal"))).field("body",def("BlockStatement"))},{"../lib/shared":135,"../lib/types":136,"./core":124}],129:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":135,"../lib/types":136,"./core":124}],130:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property}return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":137,assert:139}],131:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()});return this.scope}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();return cleanUpNodesAfterPrune(remainingNodePath)};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){var pp=this.parentPath;if(!pp){return false}var node=this.value;if(!n.Expression.check(node)){return false}if(node.type==="Identifier"){return false}while(!n.Node.check(pp.value)){pp=pp.parentPath;if(!pp){return false}}var parent=pp.value;switch(node.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return parent.type==="MemberExpression"&&this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":switch(parent.type){case"CallExpression":return this.name==="callee"&&parent.callee===node;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}default:return false}case"SequenceExpression":switch(parent.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(parent.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return true;default:return false}case"Literal":return parent.type==="MemberExpression"&&isNumber.check(node.value)&&this.name==="object"&&parent.object===node;case"AssignmentExpression":case"ConditionalExpression":switch(parent.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&parent.callee===node;case"ConditionalExpression":return this.name==="test"&&parent.test===node;case"MemberExpression":return this.name==="object"&&parent.object===node;default:return false}default:if(parent.type==="NewExpression"&&this.name==="callee"&&parent.callee===node){return containsCallExpression(node)}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}function cleanUpNodesAfterPrune(remainingNodePath){if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}else if(n.IfStatement.check(remainingNodePath.node)){cleanUpIfStatementAfterPrune(remainingNodePath)}return remainingNodePath}function cleanUpIfStatementAfterPrune(ifStatement){var testExpression=ifStatement.get("test").value;var alternate=ifStatement.get("alternate").value;var consequent=ifStatement.get("consequent").value;if(!consequent&&!alternate){var testExpressionStatement=b.expressionStatement(testExpression);ifStatement.replace(testExpressionStatement)}else if(!consequent&&alternate){var negatedTestExpression=b.unaryExpression("!",testExpression,true);if(n.UnaryExpression.check(testExpression)&&testExpression.operator==="!"){negatedTestExpression=testExpression.argument}ifStatement.get("test").replace(negatedTestExpression);ifStatement.get("consequent").replace(alternate);ifStatement.get("alternate").replace()}}module.exports=NodePath},{"./path":133,"./scope":134,"./types":136,assert:139,util:164}],132:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this);this._visiting=false;this._changeReported=false}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);var typeNames=Object.keys(supertypeTable);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){return PathVisitor.fromMethodsObject(methods).visit(node)};var PVp=PathVisitor.prototype;var recursiveVisitWarning=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");PVp.visit=function(){assert.ok(!this._visiting,recursiveVisitWarning);this._visiting=true;this._changeReported=false;var argc=arguments.length;var args=new Array(argc);for(var i=0;i<argc;++i){args[i]=arguments[i]}if(!(args[0]instanceof NodePath)){args[0]=new NodePath({root:args[0]}).get("root")}this.reset.apply(this,args);try{return this.visitWithoutReset(args[0])}finally{this._visiting=false}};PVp.reset=function(path){};PVp.visitWithoutReset=function(path){if(this instanceof this.Context){return this.visitor.visitWithoutReset(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{return context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{return visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visitWithoutReset,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visitWithoutReset(childPaths[i])}}return path.value}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};PVp.reportChanged=function(){this._changeReported=true};PVp.wasChangeReported=function(){return this._changeReported};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName);var path=this.currentPath;return path&&path.value};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;return visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};sharedContextProtoMethods.visit=function visit(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;return PathVisitor.fromMethodsObject(newVisitor||this.visitor).visitWithoutReset(path)};sharedContextProtoMethods.reportChanged=function reportChanged(){this.visitor.reportChanged()};module.exports=PathVisitor},{"./node-path":131,"./types":136,assert:139}],133:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":136,assert:139}],134:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var Expression=namedTypes.Expression;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name)};Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)&&!Expression.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node||Expression.check(node)){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(ScopeType.check(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;
return scope};module.exports=Scope},{"./node-path":131,"./types":136,assert:139}],135:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":136}],136:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i]));return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name);type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep)},typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};var typeNames=Object.keys(defCache);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var j=0;j<d.supertypeList.length;++j){var superTypeName=d.supertypeList[j];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName)};Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}if(!type.check(value)){assert.ok(false,shallowStringify(value)+" does not match field "+field+" of type "+self.typeName)}built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}if("type"in object){assert.ok(false,"did not recognize object of type "+JSON.stringify(object.type))}return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name))},context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:139}],137:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":124,"./def/e4x":125,"./def/es6":126,"./def/es7":127,"./def/fb-harmony":128,"./def/mozilla":129,"./lib/equiv":130,"./lib/node-path":131,"./lib/path-visitor":132,"./lib/types":136}],138:[function(require,module,exports){},{}],139:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&!isFinite(value)){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(util.isPrimitive(a)||util.isPrimitive(b)){return a===b}var aIsArgs=isArguments(a),bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return false;if(aIsArgs){a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}var ka=objectKeys(a),kb=objectKeys(b),key,i;if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":164}],140:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;var rootParent={};Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}if(length>0&&length<=Buffer.poolSize)buf.parent=rootParent;return buf}function SlowBuffer(subject,encoding,noZero){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding,noZero);var buf=new Buffer(subject,encoding,noZero);delete buf.parent;return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";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"binary":return binarySlice(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}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){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 "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};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}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length,2);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;if(length<0||offset<0||offset>this.length)throw new RangeError("attempt to write outside buffer bounds");var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){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){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}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]&127)}return ret}function binarySlice(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(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}}if(newBuf.length)newBuf.parent=this.parent||this;return newBuf};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(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*=256))val+=this[offset+i]*mul;return val};Buffer.prototype.readUIntBE=function(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*=256))val+=this[offset+--byteLength]*mul;return val};Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function(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*=256))val+=this[offset+i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function(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*=256))val+=this[offset+--i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range")}Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);
this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range");if(offset<0)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(target_start>=target.length)target_start=target.length;if(!target_start)target_start=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||source.length===0)return 0;if(target_start<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=source.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}return len};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new RangeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new RangeError("start out of bounds");if(end<0||end>this.length)throw new RangeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUIntLE=BP.readUIntLE;arr.readUIntBE=BP.readUIntBE;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readIntLE=BP.readIntLE;arr.readIntBE=BP.readIntBE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUIntLE=BP.writeUIntLE;arr.writeUIntBE=BP.writeUIntBE;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeIntLE=BP.writeIntLE;arr.writeIntBE=BP.writeIntBE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z\-]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){var codePoint,length=string.length;var leadSurrogate=null;units=units||Infinity;var bytes=[];var i=0;for(;i<length;i++){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(leadSurrogate){if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}else{codePoint=leadSurrogate-55296<<10|codePoint-56320|65536;leadSurrogate=null}}else{if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}else{leadSurrogate=codePoint;continue}}}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=null}if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<2097152){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}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,unitSize){if(unitSize)length-=length%unitSize;for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":141,ieee754:142,"is-array":143}],141:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);var PLUS_URL_SAFE="-".charCodeAt(0);var SLASH_URL_SAFE="_".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;if(code===SLASH||code===SLASH_URL_SAFE)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],142:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,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,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,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&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],143:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],144:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;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(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];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={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;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"){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};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;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}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{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.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};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}},{}],145:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],146:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],147:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this,require("_process"))},{_process:148}],148:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;function drainQueue(){if(draining){return}draining=true;var currentQueue;var len=queue.length;while(len){currentQueue=queue;queue=[];var i=-1;while(++i<len){currentQueue[i]()}len=queue.length}draining=false}process.nextTick=function(fun){queue.push(fun);if(!draining){setTimeout(drainQueue,0)}};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],149:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":150}],150:[function(require,module,exports){(function(process){module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);forEach(objectKeys(Writable.prototype),function(method){if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]});function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}}).call(this,require("_process"))},{"./_stream_readable":152,"./_stream_writable":154,_process:148,"core-util-is":155,inherits:145}],151:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":153,"core-util-is":155,inherits:145}],152:[function(require,module,exports){(function(process){module.exports=Readable;var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;if(!EE.listenerCount)EE.listenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("stream");var util=require("core-util-is");util.inherits=require("inherits");var StringDecoder;util.inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc};var MAX_HWM=8388608;function roundUpToNextPowerOf2(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;var ret;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){ret=null;if(state.length>0&&state.decoder){ret=fromList(n,state);state.length-=ret.length}if(state.length===0)endReadable(this);return ret}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)process.nextTick(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;
var endFn=doEnd?onend:cleanup;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){if(readable!==src)return;cleanup()}function onend(){dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);function cleanup(){dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);if(!dest._writableState||dest._writableState.needDrain)ondrain()}function onerror(er){unpipe();dest.removeListener("error",onerror);if(EE.listenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){this.on("readable",pipeOnReadable);state.flowing=true;process.nextTick(function(){flow(src)})}return dest};function pipeOnDrain(src){return function(){var dest=this;var state=src._readableState;state.awaitDrain--;if(state.awaitDrain===0)flow(src)}}function flow(src){var state=src._readableState;var chunk;state.awaitDrain=0;function write(dest,i,list){var written=dest.write(chunk);if(false===written){state.awaitDrain++}}while(state.pipesCount&&null!==(chunk=src.read())){if(state.pipesCount===1)write(state.pipes,0,null);else forEach(state.pipes,write);src.emit("data",chunk);if(state.awaitDrain>0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&!this._readableState.flowing)emitDataEvents(this);if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){this.read(0)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.resume=function(){emitDataEvents(this);this.read(0);this.emit("resume")};Readable.prototype.pause=function(){emitDataEvents(this,true);this.emit("pause")};function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing){throw new Error("Cannot switch to old mode now.")}var paused=startPaused||false;var readable=false;stream.readable=true;stream.pipe=Stream.prototype.pipe;stream.on=stream.addListener=Stream.prototype.on;stream.on("readable",function(){readable=true;var c;while(!paused&&null!==(c=stream.read()))stream.emit("data",c);if(c===null){readable=false;stream._readableState.needReadable=true}});stream.pause=function(){paused=true;this.emit("pause")};stream.resume=function(){paused=false;if(readable)process.nextTick(function(){stream.emit("readable")});else this.read(0);this.emit("resume")};stream.emit("readable")}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(typeof stream[i]==="function"&&typeof this[i]==="undefined"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted&&state.calledRead){state.ended=true;process.nextTick(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{_process:148,buffer:140,"core-util-is":155,events:144,inherits:145,isarray:146,stream:160,"string_decoder/":161}],153:[function(require,module,exports){module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);var ts=this._transformState=new TransformState(options,this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var rs=stream._readableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":150,"core-util-is":155,inherits:145}],154:[function(require,module,exports){(function(process){module.exports=Writable;var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream=require("stream");util.inherits(Writable,Stream);function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb}function WritableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.objectMode=!!options.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function Writable(options){var Duplex=require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,state,cb){var er=new Error("write after end");stream.emit("error",er);process.nextTick(function(){cb(er)})}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);process.nextTick(function(){cb(er)});valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=function(){};if(state.ended)writeAfterEnd(this,state,cb);else if(validChunk(this,state,chunk,cb))ret=writeOrBuffer(this,state,chunk,encoding,cb);return ret};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing)state.buffer.push(new WriteReq(chunk,encoding,cb));else doWrite(stream,state,len,chunk,encoding,cb);return ret}function doWrite(stream,state,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){if(sync)process.nextTick(function(){cb(er)});else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(stream,state);if(!finished&&!state.bufferProcessing&&state.buffer.length)clearBuffer(stream,state);if(sync){process.nextTick(function(){afterWrite(stream,state,finished,cb)})}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);cb();if(finished)finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;for(var c=0;c<state.buffer.length;c++){var entry=state.buffer[c];var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,len,chunk,encoding,cb);if(state.writing){c++;break}}state.bufferProcessing=false;if(c<state.buffer.length)state.buffer=state.buffer.slice(c);else state.buffer.length=0}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(typeof chunk!=="undefined"&&chunk!==null)this.write(chunk,encoding);if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(stream,state){return state.ending&&state.length===0&&!state.finished&&!state.writing}function finishMaybe(stream,state){var need=needFinish(stream,state);if(need){state.finished=true;stream.emit("finish")}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true}}).call(this,require("_process"))},{"./_stream_duplex":150,_process:148,buffer:140,"core-util-is":155,inherits:145,stream:160}],155:[function(require,module,exports){(function(Buffer){function isArray(ar){return Array.isArray(ar)}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 isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(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"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;function isBuffer(arg){return Buffer.isBuffer(arg)}exports.isBuffer=isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,require("buffer").Buffer)},{buffer:140}],156:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":151}],157:[function(require,module,exports){var Stream=require("stream");exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":150,"./lib/_stream_passthrough.js":151,"./lib/_stream_readable.js":152,"./lib/_stream_transform.js":153,"./lib/_stream_writable.js":154,stream:160}],158:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":153}],159:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":154}],160:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:144,inherits:145,"readable-stream/duplex.js":149,"readable-stream/passthrough.js":156,"readable-stream/readable.js":157,"readable-stream/transform.js":158,"readable-stream/writable.js":159}],161:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:140}],162:[function(require,module,exports){exports.isatty=function(){return false};function ReadStream(){throw new Error("tty.ReadStream is not implemented")}exports.ReadStream=ReadStream;function WriteStream(){throw new Error("tty.ReadStream is not implemented")}exports.WriteStream=WriteStream},{}],163:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],164:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}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 isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(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"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":163,_process:148,inherits:145}],165:[function(require,module,exports){"use strict";var escapeStringRegexp=require("escape-string-regexp");var ansiStyles=require("ansi-styles");var stripAnsi=require("strip-ansi");var hasAnsi=require("has-ansi");var supportsColor=require("supports-color");var defineProps=Object.defineProperties;var chalk=module.exports;function build(_styles){var builder=function builder(){return applyStyle.apply(builder,arguments)};builder._styles=_styles;builder.__proto__=proto;return builder}var styles=function(){var ret={};ansiStyles.grey=ansiStyles.gray;Object.keys(ansiStyles).forEach(function(key){ansiStyles[key].closeRe=new RegExp(escapeStringRegexp(ansiStyles[key].close),"g");ret[key]={get:function(){return build(this._styles.concat(key))
}}});return ret}();var proto=defineProps(function chalk(){},styles);function applyStyle(){var args=arguments;var argsLen=args.length;var str=argsLen!==0&&String(arguments[0]);if(argsLen>1){for(var a=1;a<argsLen;a++){str+=" "+args[a]}}if(!chalk.enabled||!str){return str}var nestedStyles=this._styles;for(var i=0;i<nestedStyles.length;i++){var code=ansiStyles[nestedStyles[i]];str=code.open+str.replace(code.closeRe,code.open)+code.close}return str}function init(){var ret={};Object.keys(styles).forEach(function(name){ret[name]={get:function(){return build([name])}}});return ret}defineProps(chalk,init());chalk.styles=ansiStyles;chalk.hasColor=hasAnsi;chalk.stripColor=stripAnsi;chalk.supportsColor=supportsColor;if(chalk.enabled===undefined){chalk.enabled=chalk.supportsColor}},{"ansi-styles":166,"escape-string-regexp":167,"has-ansi":168,"strip-ansi":170,"supports-color":172}],166:[function(require,module,exports){"use strict";var styles=module.exports;var codes={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]};Object.keys(codes).forEach(function(key){var val=codes[key];var style=styles[key]={};style.open="["+val[0]+"m";style.close="["+val[1]+"m"})},{}],167:[function(require,module,exports){"use strict";var matchOperatorsRe=/[|\\{}()[\]^$+*?.]/g;module.exports=function(str){if(typeof str!=="string"){throw new TypeError("Expected a string")}return str.replace(matchOperatorsRe,"\\$&")}},{}],168:[function(require,module,exports){"use strict";var ansiRegex=require("ansi-regex");var re=new RegExp(ansiRegex().source);module.exports=re.test.bind(re)},{"ansi-regex":169}],169:[function(require,module,exports){"use strict";module.exports=function(){return/\u001b\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]/g}},{}],170:[function(require,module,exports){"use strict";var ansiRegex=require("ansi-regex")();module.exports=function(str){return typeof str==="string"?str.replace(ansiRegex,""):str}},{"ansi-regex":171}],171:[function(require,module,exports){arguments[4][169][0].apply(exports,arguments)},{dup:169}],172:[function(require,module,exports){(function(process){"use strict";module.exports=function(){if(process.argv.indexOf("--no-color")!==-1){return false}if(process.argv.indexOf("--color")!==-1){return true}if(process.stdout&&!process.stdout.isTTY){return false}if(process.platform==="win32"){return true}if("COLORTERM"in process.env){return true}if(process.env.TERM==="dumb"){return false}if(/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)){return true}return false}()}).call(this,require("_process"))},{_process:148}],173:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,RangeError=global.RangeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,parseInt=global.parseInt,isFinite=global.isFinite,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".",CONSOLE_METHODS="assert,clear,count,debug,dir,dirxml,error,exception,"+"group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,"+"markTimeline,profile,profileEnd,table,time,timeEnd,timeline,"+"timelineEnd,timeStamp,trace,warn";function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return toString.call(it).slice(8,-1)}function classof(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[SYMBOL_TAG])=="string"?T:cof(O)}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&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(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){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]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}function construct(target,argumentsList){var proto=assertFunction(arguments.length<3?target:arguments[2])[PROTOTYPE],instance=create(isObject(proto)?proto:ObjectProto),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,isFrozen=Object.isFrozen,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,pow=Math.pow,abs=Math.abs,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function lz(num){return num>9?num:"0"+num}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_SPECIES=getWellKnownSymbol("species");function setSpecies(C){if(framework||!isNative(C))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description),sym=set(create(Symbol[PROTOTYPE]),TAG,tag);AllSymbols[tag]=sym;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return sym};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(AllSymbols[key]);return result}})}(safeSymbol("tag"),{},{},true);!function(tmp){var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"})}setToStringTag(Math,MATH,true);setToStringTag(global.JSON,"JSON",true)}({});!function(){function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames")}();!function(isInteger){$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt})}(Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it});!function(){var E=Math.E,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,sign=Math.sign||function(x){return(x=+x)==0||x!=x?x:x<0?-1:1};function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc})}();!function(fromCharCode){function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fromCharCode(code):fromCharCode(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}})}(String.fromCharCode);!function(){$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),mapfn=arguments[1],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,arguments[2],2):undefined,index=0,length,result,iter,step;if(isIterable(O))for(iter=getIterator(O),result=new(generic(this,Array));!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(result=new(generic(this,Array))(length=toLength(O.length));length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});if(framework){forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}setSpecies(Array)}();!function(at){defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)})}(createPointAt(true));isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(run,0,id)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&¬ify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&DEF in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),O1=safeSymbol("O1"),WEAK=safeSymbol("weak"),LEAK=safeSymbol("leak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0,tmp={};function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];if(framework)proto[key]=function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result}}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,FOR_EACH)&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,O1,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto;if(framework)proto[CONSTRUCTOR]=C}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,UID)){if(!create)return"E";hidden(it,UID,++uid)}return"O"+it[UID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}function def(that,key,value){var entry=getEntry(that,key),prev,index;if(entry)entry.v=value;else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that}var collectionMethods={clear:function(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return!!getEntry(this,key)}};Map=getCollection(Map,MAP,{get:function(key){var entry=getEntry(this,key);
return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function defWeak(that,key,value){if(isFrozen(assertObject(key)))leakStore(that).set(key,value);else{has(key,WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value}return that}function leakStore(that){return that[LEAK]||hidden(that,LEAK,new Map)[LEAK]}var weakMethods={"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return has(key,WEAK)&&has(key[WEAK],this[UID])&&delete key[WEAK][this[UID]]},has:function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return has(key,WEAK)&&has(key[WEAK],this[UID])}};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[UID]]}},set:function(key,value){return defWeak(this,key,value)}},weakMethods,true,true);if(framework&&(new WeakMap).set(Object.freeze(tmp),7).get(tmp)!=7){forEach.call(array("delete,has,get,set"),function(key){var method=WeakMap[PROTOTYPE][key];WeakMap[PROTOTYPE][key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return defWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return has(desc,"value")?desc.value:desc.get===undefined?undefined:desc.get.call(receiver);return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],ownDesc=getOwnDescriptor(assertObject(target),propertyKey),existingDescriptor,proto;if(!ownDesc){if(isObject(proto=getPrototypeOf(target))){return reflectSet(proto,propertyKey,V,receiver)}ownDesc=descriptor(0)}if(has(ownDesc,"value")){if(ownDesc.writable===false||!isObject(receiver))return false;existingDescriptor=getOwnDescriptor(receiver,propertyKey)||descriptor(0);existingDescriptor.value=V;return defineProperty(receiver,propertyKey,existingDescriptor),true}return ownDesc.set===undefined?false:(ownDesc.set.call(receiver,V),true)}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(DICT){Dict=function(iterable){var dict=create(null);if(iterable!=undefined){if(isIterable(iterable)){for(var iter=getIterator(iterable),step,value;!(step=iter.next()).done;){value=step.value;dict[value[0]]=value[1]}}else assign(dict,iterable)}return dict};Dict[PROTOTYPE]=null;function DictIterator(iterated,kind){set(this,ITER,{o:toObject(iterated),a:getKeys(iterated),i:0,k:kind})}createIterator(DictIterator,DICT,function(){var iter=this[ITER],O=iter.o,keys=iter.a,kind=iter.k,key;do{if(iter.i>=keys.length){iter.o=undefined;return iterResult(1)}}while(!has(O,key=keys[iter.i++]));if(kind==KEY)return iterResult(0,key);if(kind==VALUE)return iterResult(0,O[key]);return iterResult(0,[key,O[key]])});function createDictIter(kind){return function(it){return new DictIterator(it,kind)}}function createDictMethod(type){var isMap=type==1,isEvery=type==4;return function(object,callbackfn,that){var f=ctx(callbackfn,that,3),O=toObject(object),result=isMap||type==7||type==2?new(generic(this,Dict)):undefined,key,val,res;for(key in O)if(has(O,key)){val=O[key];res=f(val,key,object);if(type){if(isMap)result[key]=res;else if(res)switch(type){case 2:result[key]=val;break;case 3:return true;case 5:return val;case 6:return key;case 7:result[res[0]]=res[1]}else if(isEvery)return false}}return type==3||isEvery?isEvery:result}}function createDictReduce(isTurn){return function(object,mapfn,init){assertFunction(mapfn);var O=toObject(object),keys=getKeys(O),length=keys.length,i=0,memo,key,result;if(isTurn)memo=init==undefined?new(generic(this,Dict)):Object(init);else if(arguments.length<3){assert(length,REDUCE_ERROR);memo=O[keys[i++]]}else memo=Object(init);while(length>i)if(has(O,key=keys[i++])){result=mapfn(memo,O[key],key,object);if(isTurn){if(result===false)break}else memo=result}return memo}}var findKey=createDictMethod(6);function includes(object,el){return(el==el?keyOf(object,el):findKey(object,sameNaN))!==undefined}var dictMethods={keys:createDictIter(KEY),values:createDictIter(VALUE),entries:createDictIter(KEY+VALUE),forEach:createDictMethod(0),map:createDictMethod(1),filter:createDictMethod(2),some:createDictMethod(3),every:createDictMethod(4),find:createDictMethod(5),findKey:findKey,mapPairs:createDictMethod(7),reduce:createDictReduce(false),turn:createDictReduce(true),keyOf:keyOf,includes:includes,has:has,get:get,set:createDefiner(0),isDict:function(it){return isObject(it)&&getPrototypeOf(it)===Dict[PROTOTYPE]}};if(REFERENCE_GET)for(var key in dictMethods)!function(fn){function method(){for(var args=[this],i=0;i<arguments.length;)args.push(arguments[i++]);return invoke(fn,args)}fn[REFERENCE_GET]=function(){return method}}(dictMethods[key]);$define(GLOBAL+FORCED,{Dict:assignHidden(Dict,dictMethods)})}("Dict");!function(ENTRIES,FN){function $for(iterable,entries){if(!(this instanceof $for))return new $for(iterable,entries);this[ITER]=getIterator(iterable);this[ENTRIES]=!!entries}createIterator($for,"Wrapper",function(){return this[ITER].next()});var $forProto=$for[PROTOTYPE];setIterator($forProto,function(){return this[ITER]});function createChainIterator(next){function Iter(I,fn,that){this[ITER]=getIterator(I);this[ENTRIES]=I[ENTRIES];this[FN]=ctx(fn,that,I[ENTRIES]?2:1)}createIterator(Iter,"Chain",next,$forProto);setIterator(Iter[PROTOTYPE],returnThis);return Iter}var MapIter=createChainIterator(function(){var step=this[ITER].next();return step.done?step:iterResult(0,stepCall(this[FN],step.value,this[ENTRIES]))});var FilterIter=createChainIterator(function(){for(;;){var step=this[ITER].next();if(step.done||stepCall(this[FN],step.value,this[ENTRIES]))return step}});assignHidden($forProto,{of:function(fn,that){forOf(this,this[ENTRIES],fn,that)},array:function(fn,that){var result=[];forOf(fn!=undefined?this.map(fn,that):this,false,push,result);return result},filter:function(fn,that){return new FilterIter(this,fn,that)},map:function(fn,that){return new MapIter(this,fn,that)}});$for.isIterable=isIterable;$for.getIterator=getIterator;$define(GLOBAL+FORCED,{$for:$for})}("entries",safeSymbol("fn"));$define(GLOBAL+FORCED,{delay:function(time){return new Promise(function(resolve){setTimeout(resolve,time,true)})}});!function(_,toLocaleString){core._=path._=path._||{};$define(PROTO+FORCED,FUNCTION,{part:part,only:function(numberArguments,that){var fn=assertFunction(this),n=toLength(numberArguments),isThat=arguments.length>1;return function(){var length=min(n,arguments.length),args=Array(length),i=0;while(length>i)args[i]=arguments[i++];return invoke(fn,args,isThat?that:this)}}});function tie(key){var that=this,bound={};return hidden(that,_,function(key){if(key===undefined||!(key in that))return toLocaleString.call(that);return has(bound,key)?bound[key]:bound[key]=ctx(that[key],that,-1)})[_](key)}hidden(path._,TO_STRING,function(){return _});hidden(ObjectProto,_,tie);DESC||hidden(ArrayProto,_,tie)}(DESC?uid("tie"):TO_LOCALE,ObjectProto[TO_LOCALE]);!function(){function define(target,mixin){var keys=ownKeys(toObject(mixin)),length=keys.length,i=0,key;while(length>i)defineProperty(target,key=keys[i++],getOwnDescriptor(mixin,key));return target}$define(STATIC+FORCED,OBJECT,{isObject:isObject,classof:classof,define:define,make:function(proto,mixin){return define(create(proto),mixin)}})}();$define(PROTO+FORCED,ARRAY,{turn:function(fn,target){assertFunction(fn);var memo=target==undefined?[]:Object(target),O=ES5Object(this),length=toLength(O.length),index=0;while(length>index)if(fn(memo,O[index],index++,this)===false)break;return memo}});if(framework)ArrayUnscopables.turn=true;!function(numberMethods){function NumberIterator(iterated){set(this,ITER,{l:toLength(iterated),i:0})}createIterator(NumberIterator,NUMBER,function(){var iter=this[ITER],i=iter.i++;return i<iter.l?iterResult(0,i):iterResult(1)});defineIterator(Number,NUMBER,function(){return new NumberIterator(this)});numberMethods.random=function(lim){var a=+this,b=lim==undefined?0:+lim,m=min(a,b);return random()*(max(a,b)-m)+m};forEach.call(array("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,"+"acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc"),function(key){var fn=Math[key];if(fn)numberMethods[key]=function(){var args=[+this],i=0;while(arguments.length>i)args.push(arguments[i++]);return invoke(fn,args)}});$define(PROTO+FORCED,NUMBER,numberMethods)}({});!function(){var escapeHTMLDict={"&":"&","<":"<",">":">",'"':""","'":"'"},unescapeHTMLDict={},key;for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]]=key;$define(PROTO+FORCED,STRING,{escapeHTML:createReplacer(/[&<>"']/g,escapeHTMLDict),unescapeHTML:createReplacer(/&(?:amp|lt|gt|quot|apos);/g,unescapeHTMLDict)})}();!function(formatRegExp,flexioRegExp,locales,current,SECONDS,MINUTES,HOURS,MONTH,YEAR){function createFormat(prefix){return function(template,locale){var that=this,dict=locales[has(locales,locale)?locale:current];function get(unit){return that[prefix+unit]()}return String(template).replace(formatRegExp,function(part){switch(part){case"s":return get(SECONDS);case"ss":return lz(get(SECONDS));case"m":return get(MINUTES);case"mm":return lz(get(MINUTES));case"h":return get(HOURS);case"hh":return lz(get(HOURS));case"D":return get(DATE);case"DD":return lz(get(DATE));case"W":return dict[0][get("Day")];case"N":return get(MONTH)+1;case"NN":return lz(get(MONTH)+1);case"M":return dict[2][get(MONTH)];case"MM":return dict[1][get(MONTH)];case"Y":return get(YEAR);case"YY":return lz(get(YEAR)%100)}return part})}}function addLocale(lang,locale){function split(index){var result=[];forEach.call(array(locale.months),function(it){result.push(it.replace(flexioRegExp,"$"+index))});return result}locales[lang]=[array(locale.weekdays),split(1),split(2)];return core}$define(PROTO+FORCED,DATE,{format:createFormat("get"),formatUTC:createFormat("getUTC")});addLocale(current,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"});addLocale("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,"+"Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"});core.locale=function(locale){return has(locales,locale)?current=locale:current};core.addLocale=addLocale}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear");$define(GLOBAL+FORCED,{global:global});!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({});!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList);!function(log,console,enabled){forEach.call(array(CONSOLE_METHODS),function(key){log[key]=function(){if(enabled&&key in console)return apply.call(console[key],console,arguments)}});$define(GLOBAL+FORCED,{log:assign(log.log,log,{enable:function(){enabled=true},disable:function(){enabled=false}})})}({},global.console||{},true)}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),false)},{}],174:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{exports.names.push(new RegExp("^"+namespaces+"$"))}}}function disable(){exports.enable("")}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}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{ms:176}],175:[function(require,module,exports){(function(process){var tty=require("tty");var util=require("util");exports=module.exports=require("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=[6,2,3,4,5,1];var fd=parseInt(process.env.DEBUG_FD,10)||2;var stream=1===fd?process.stdout:2===fd?process.stderr:createWritableStdioStream(fd);function useColors(){var debugColors=(process.env.DEBUG_COLORS||"").trim().toLowerCase();if(0===debugColors.length){return tty.isatty(fd)}else{return"0"!==debugColors&&"no"!==debugColors&&"false"!==debugColors&&"disabled"!==debugColors}}var inspect=4===util.inspect.length?function(v,colors){return util.inspect(v,void 0,void 0,colors)}:function(v,colors){return util.inspect(v,{colors:colors})};exports.formatters.o=function(v){return inspect(v,this.useColors).replace(/\s*\n\s*/g," ")};function formatArgs(){var args=arguments;var useColors=this.useColors;var name=this.namespace;if(useColors){var c=this.color;args[0]=" [9"+c+"m"+name+" "+"[0m"+args[0]+"[3"+c+"m"+" +"+exports.humanize(this.diff)+"[0m"}else{args[0]=(new Date).toUTCString()+" "+name+" "+args[0]}return args}function log(){return stream.write(util.format.apply(this,arguments)+"\n")}function save(namespaces){if(null==namespaces){delete process.env.DEBUG}else{process.env.DEBUG=namespaces}}function load(){return process.env.DEBUG}function createWritableStdioStream(fd){var stream;var tty_wrap=process.binding("tty_wrap");switch(tty_wrap.guessHandleType(fd)){case"TTY":stream=new tty.WriteStream(fd);stream._type="tty";if(stream._handle&&stream._handle.unref){stream._handle.unref()}break;case"FILE":var fs=require("fs");stream=new fs.SyncWriteStream(fd,{autoClose:false});stream._type="fs";break;case"PIPE":case"TCP":var net=require("net");stream=new net.Socket({fd:fd,readable:false,writable:true});stream.readable=false;stream.read=null;stream._type="pipe";if(stream._handle&&stream._handle.unref){stream._handle.unref()}break;default:throw new Error("Implement me. Unknown stream file type!")}stream.fd=fd;stream._isStdio=true;return stream}exports.enable(load())}).call(this,require("_process"))},{"./debug":174,_process:148,fs:138,net:138,tty:162,util:164}],176:[function(require,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){var match=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"h":return n*h;case"minutes":case"minute":case"m":return n*m;case"seconds":case"second":case"s":return n*s;case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+" "+name;return Math.ceil(ms/n)+" "+name+"s"}},{}],177:[function(require,module,exports){"use strict";var repeating=require("repeating");var INDENT_RE=/^(?:( )+|\t+)/;function getMostUsed(indents){var result=0;var maxUsed=0;var maxWeight=0;for(var n in indents){var indent=indents[n];var u=indent[0];var w=indent[1];if(u>maxUsed||u===maxUsed&&w>maxWeight){maxUsed=u;maxWeight=w;result=+n}}return result}module.exports=function(str){if(typeof str!=="string"){throw new TypeError("Expected a string")}var tabs=0;var spaces=0;var prev=0;var indents={};var current;var isIndent;str.split(/\n/g).forEach(function(line){if(!line){return}var indent;var matches=line.match(INDENT_RE);if(!matches){indent=0}else{indent=matches[0].length;if(matches[1]){spaces++}else{tabs++}}var diff=indent-prev;prev=indent;if(diff){isIndent=diff>0;current=indents[isIndent?diff:-diff];if(current){current[0]++}else{current=indents[diff]=[1,0]}}else if(current){current[1]+=+isIndent}});var amount=getMostUsed(indents);var type;var actual;if(!amount){type=null;actual=""}else if(spaces>=tabs){type="space";actual=repeating(" ",amount)}else{type="tab";actual=repeating(" ",amount)}return{amount:amount,type:type,indent:actual}}},{repeating:178}],178:[function(require,module,exports){"use strict";var isFinite=require("is-finite");module.exports=function(str,n){if(typeof str!=="string"){throw new TypeError("Expected a string as the first argument")}if(n<0||!isFinite(n)){throw new TypeError("Expected a finite positive number")}var ret="";do{if(n&1){ret+=str}str+=str}while(n=n>>1);return ret}},{"is-finite":179}],179:[function(require,module,exports){"use strict";module.exports=Number.isFinite||function(val){if(typeof val!=="number"||val!==val||val===Infinity||val===-Infinity){return false}return true}},{}],180:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function clone(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(element){var i,key,nextElem,parent;
if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.8.1-dev";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller;exports.cloneEnvironment=function(){return clone({})};return exports})},{}],181:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],182:[function(require,module,exports){(function(){"use strict";var Regex,NON_ASCII_WHITESPACES;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}NON_ASCII_WHITESPACES=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&NON_ASCII_WHITESPACES.indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch>=48&&ch<=57||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],183:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="yield"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":182}],184:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":181,"./code":182,"./keyword":183}],185:[function(require,module,exports){module.exports={builtin:{Array:false,ArrayBuffer:false,Boolean:false,constructor:false,Date:false,decodeURI:false,decodeURIComponent:false,encodeURI:false,encodeURIComponent:false,Error:false,eval:false,EvalError:false,Float32Array:false,Float64Array:false,Function:false,hasOwnProperty:false,Infinity:false,Int16Array:false,Int32Array:false,Int8Array:false,isFinite:false,isNaN:false,isPrototypeOf:false,JSON:false,Map:false,Math:false,NaN:false,Number:false,Object:false,parseFloat:false,parseInt:false,Promise:false,propertyIsEnumerable:false,Proxy:false,RangeError:false,ReferenceError:false,Reflect:false,RegExp:false,Set:false,String:false,Symbol:false,SyntaxError:false,System:false,toLocaleString:false,toString:false,TypeError:false,Uint16Array:false,Uint32Array:false,Uint8Array:false,Uint8ClampedArray:false,undefined:false,URIError:false,valueOf:false,WeakMap:false,WeakSet:false},nonstandard:{escape:false,unescape:false},browser:{addEventListener:false,alert:false,applicationCache:false,atob:false,Audio:false,Blob:false,blur:false,btoa:false,cancelAnimationFrame:false,CanvasGradient:false,CanvasPattern:false,CanvasRenderingContext2D:false,clearInterval:false,clearTimeout:false,close:false,closed:false,confirm:false,console:false,crypto:false,CSS:false,CustomEvent:false,DataView:false,Debug:false,defaultStatus:false,devicePixelRatio:false,dispatchEvent:false,document:false,DOMParser:false,Element:false,ElementTimeControl:false,Event:false,event:false,FileReader:false,find:false,focus:false,FormData:false,frameElement:false,frames:false,getComputedStyle:false,getSelection:false,history:false,HTMLAnchorElement:false,HTMLBaseElement:false,HTMLBlockquoteElement:false,HTMLBodyElement:false,HTMLBRElement:false,HTMLButtonElement:false,HTMLCanvasElement:false,HTMLDirectoryElement:false,HTMLDivElement:false,HTMLDListElement:false,HTMLElement:false,HTMLFieldSetElement:false,HTMLFontElement:false,HTMLFormElement:false,HTMLFrameElement:false,HTMLFrameSetElement:false,HTMLHeadElement:false,HTMLHeadingElement:false,HTMLHRElement:false,HTMLHtmlElement:false,HTMLIFrameElement:false,HTMLImageElement:false,HTMLInputElement:false,HTMLIsIndexElement:false,HTMLLabelElement:false,HTMLLayerElement:false,HTMLLegendElement:false,HTMLLIElement:false,HTMLLinkElement:false,HTMLMapElement:false,HTMLMenuElement:false,HTMLMetaElement:false,HTMLModElement:false,HTMLObjectElement:false,HTMLOListElement:false,HTMLOptGroupElement:false,HTMLOptionElement:false,HTMLParagraphElement:false,HTMLParamElement:false,HTMLPreElement:false,HTMLQuoteElement:false,HTMLScriptElement:false,HTMLSelectElement:false,HTMLStyleElement:false,HTMLTableCaptionElement:false,HTMLTableCellElement:false,HTMLTableColElement:false,HTMLTableElement:false,HTMLTableRowElement:false,HTMLTableSectionElement:false,HTMLTextAreaElement:false,HTMLTitleElement:false,HTMLUListElement:false,HTMLVideoElement:false,IDBCursor:false,IDBCursorWithValue:false,IDBDatabase:false,IDBEnvironment:false,IDBFactory:false,IDBIndex:false,IDBKeyRange:false,IDBObjectStore:false,IDBOpenDBRequest:false,IDBRequest:false,IDBTransaction:false,Image:false,indexedDB:false,innerHeight:false,innerWidth:false,Intl:false,length:false,localStorage:false,location:false,matchMedia:false,MessageChannel:false,MessageEvent:false,MessagePort:false,MouseEvent:false,moveBy:false,moveTo:false,MutationObserver:false,name:false,navigator:false,Node:false,NodeFilter:false,NodeList:false,onbeforeunload:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:false,openDatabase:false,opener:false,opera:false,Option:false,outerHeight:false,outerWidth:false,pageXOffset:false,pageYOffset:false,parent:false,postMessage:false,print:false,prompt:false,removeEventListener:false,requestAnimationFrame:false,resizeBy:false,resizeTo:false,screen:false,screenX:false,screenY:false,scroll:false,scrollbars:false,scrollBy:false,scrollTo:false,scrollX:false,scrollY:false,self:false,sessionStorage:false,setInterval:false,setTimeout:false,SharedWorker:false,showModalDialog:false,status:false,stop:false,SVGAElement:false,SVGAltGlyphDefElement:false,SVGAltGlyphElement:false,SVGAltGlyphItemElement:false,SVGAngle:false,SVGAnimateColorElement:false,SVGAnimatedAngle:false,SVGAnimatedBoolean:false,SVGAnimatedEnumeration:false,SVGAnimatedInteger:false,SVGAnimatedLength:false,SVGAnimatedLengthList:false,SVGAnimatedNumber:false,SVGAnimatedNumberList:false,SVGAnimatedPathData:false,SVGAnimatedPoints:false,SVGAnimatedPreserveAspectRatio:false,SVGAnimatedRect:false,SVGAnimatedString:false,SVGAnimatedTransformList:false,SVGAnimateElement:false,SVGAnimateMotionElement:false,SVGAnimateTransformElement:false,SVGAnimationElement:false,SVGCircleElement:false,SVGClipPathElement:false,SVGColor:false,SVGColorProfileElement:false,SVGColorProfileRule:false,SVGComponentTransferFunctionElement:false,SVGCSSRule:false,SVGCursorElement:false,SVGDefsElement:false,SVGDescElement:false,SVGDocument:false,SVGElement:false,SVGElementInstance:false,SVGElementInstanceList:false,SVGEllipseElement:false,SVGExternalResourcesRequired:false,SVGFEBlendElement:false,SVGFEColorMatrixElement:false,SVGFEComponentTransferElement:false,SVGFECompositeElement:false,SVGFEConvolveMatrixElement:false,SVGFEDiffuseLightingElement:false,SVGFEDisplacementMapElement:false,SVGFEDistantLightElement:false,SVGFEFloodElement:false,SVGFEFuncAElement:false,SVGFEFuncBElement:false,SVGFEFuncGElement:false,SVGFEFuncRElement:false,SVGFEGaussianBlurElement:false,SVGFEImageElement:false,SVGFEMergeElement:false,SVGFEMergeNodeElement:false,SVGFEMorphologyElement:false,SVGFEOffsetElement:false,SVGFEPointLightElement:false,SVGFESpecularLightingElement:false,SVGFESpotLightElement:false,SVGFETileElement:false,SVGFETurbulenceElement:false,SVGFilterElement:false,SVGFilterPrimitiveStandardAttributes:false,SVGFitToViewBox:false,SVGFontElement:false,SVGFontFaceElement:false,SVGFontFaceFormatElement:false,SVGFontFaceNameElement:false,SVGFontFaceSrcElement:false,SVGFontFaceUriElement:false,SVGForeignObjectElement:false,SVGGElement:false,SVGGlyphElement:false,SVGGlyphRefElement:false,SVGGradientElement:false,SVGHKernElement:false,SVGICCColor:false,SVGImageElement:false,SVGLangSpace:false,SVGLength:false,SVGLengthList:false,SVGLinearGradientElement:false,SVGLineElement:false,SVGLocatable:false,SVGMarkerElement:false,SVGMaskElement:false,SVGMatrix:false,SVGMetadataElement:false,SVGMissingGlyphElement:false,SVGMPathElement:false,SVGNumber:false,SVGNumberList:false,SVGPaint:false,SVGPathElement:false,SVGPathSeg:false,SVGPathSegArcAbs:false,SVGPathSegArcRel:false,SVGPathSegClosePath:false,SVGPathSegCurvetoCubicAbs:false,SVGPathSegCurvetoCubicRel:false,SVGPathSegCurvetoCubicSmoothAbs:false,SVGPathSegCurvetoCubicSmoothRel:false,SVGPathSegCurvetoQuadraticAbs:false,SVGPathSegCurvetoQuadraticRel:false,SVGPathSegCurvetoQuadraticSmoothAbs:false,SVGPathSegCurvetoQuadraticSmoothRel:false,SVGPathSegLinetoAbs:false,SVGPathSegLinetoHorizontalAbs:false,SVGPathSegLinetoHorizontalRel:false,SVGPathSegLinetoRel:false,SVGPathSegLinetoVerticalAbs:false,SVGPathSegLinetoVerticalRel:false,SVGPathSegList:false,SVGPathSegMovetoAbs:false,SVGPathSegMovetoRel:false,SVGPatternElement:false,SVGPoint:false,SVGPointList:false,SVGPolygonElement:false,SVGPolylineElement:false,SVGPreserveAspectRatio:false,SVGRadialGradientElement:false,SVGRect:false,SVGRectElement:false,SVGRenderingIntent:false,SVGScriptElement:false,SVGSetElement:false,SVGStopElement:false,SVGStringList:false,SVGStylable:false,SVGStyleElement:false,SVGSVGElement:false,SVGSwitchElement:false,SVGSymbolElement:false,SVGTests:false,SVGTextContentElement:false,SVGTextElement:false,SVGTextPathElement:false,SVGTextPositioningElement:false,SVGTitleElement:false,SVGTransform:false,SVGTransformable:false,SVGTransformList:false,SVGTRefElement:false,SVGTSpanElement:false,SVGUnitTypes:false,SVGURIReference:false,SVGUseElement:false,SVGViewElement:false,SVGViewSpec:false,SVGVKernElement:false,SVGZoomAndPan:false,TextDecoder:false,TextEncoder:false,TimeEvent:false,top:false,URL:false,WebGLActiveInfo:false,WebGLBuffer:false,WebGLContextEvent:false,WebGLFramebuffer:false,WebGLProgram:false,WebGLRenderbuffer:false,WebGLRenderingContext:false,WebGLShader:false,WebGLShaderPrecisionFormat:false,WebGLTexture:false,WebGLUniformLocation:false,WebSocket:false,window:false,Worker:false,XDomainRequest:false,XMLHttpRequest:false,XMLSerializer:false,XPathEvaluator:false,XPathException:false,XPathExpression:false,XPathNamespace:false,XPathNSResolver:false,XPathResult:false},worker:{importScripts:true,postMessage:true,self:true},node:{__filename:false,__dirname:false,arguments:false,Buffer:false,DataView:false,console:false,exports:true,GLOBAL:false,global:false,module:false,process:false,require:false,setTimeout:false,clearTimeout:false,setInterval:false,clearInterval:false,setImmediate:false,clearImmediate:false},amd:{require:false,define:false},mocha:{describe:false,it:false,before:false,after:false,beforeEach:false,afterEach:false,suite:false,test:false,setup:false,teardown:false,suiteSetup:false,suiteTeardown:false},jasmine:{afterAll:false,afterEach:false,beforeAll:false,beforeEach:false,describe:false,expect:false,fail:false,fdescribe:false,fit:false,it:false,jasmine:false,pending:false,spyOn:false,waits:false,waitsFor:false,xdescribe:false,xit:false},qunit:{asyncTest:false,deepEqual:false,equal:false,expect:false,module:false,notDeepEqual:false,notEqual:false,notPropEqual:false,notStrictEqual:false,ok:false,propEqual:false,QUnit:false,raises:false,start:false,stop:false,strictEqual:false,test:false,"throws":false},phantom:{phantom:true,require:true,WebPage:true,console:true,exports:true},couch:{require:false,respond:false,getRow:false,emit:false,send:false,start:false,sum:false,log:false,exports:false,module:false,provides:false},rhino:{defineClass:false,deserialize:false,gc:false,help:false,importPackage:false,java:false,load:false,loadClass:false,print:false,quit:false,readFile:false,readUrl:false,runCommand:false,seal:false,serialize:false,spawn:false,sync:false,toint32:false,version:false},wsh:{ActiveXObject:true,Enumerator:true,GetObject:true,ScriptEngine:true,ScriptEngineBuildVersion:true,ScriptEngineMajorVersion:true,ScriptEngineMinorVersion:true,VBArray:true,WSH:true,WScript:true,XDomainRequest:true},jquery:{$:false,jQuery:false},yui:{YUI:false,Y:false,YUI_config:false},shelljs:{target:false,echo:false,exit:false,cd:false,pwd:false,ls:false,find:false,cp:false,rm:false,mv:false,mkdir:false,test:false,cat:false,sed:false,grep:false,which:false,dirs:false,pushd:false,popd:false,env:false,exec:false,chmod:false,config:false,error:false,tempdir:false},prototypejs:{$:false,$$:false,$A:false,$F:false,$H:false,$R:false,$break:false,$continue:false,$w:false,Abstract:false,Ajax:false,Class:false,Enumerable:false,Element:false,Event:false,Field:false,Form:false,Hash:false,Insertion:false,ObjectRange:false,PeriodicalExecuter:false,Position:false,Prototype:false,Selector:false,Template:false,Toggle:false,Try:false,Autocompleter:false,Builder:false,Control:false,Draggable:false,Draggables:false,Droppables:false,Effect:false,Sortable:false,SortableObserver:false,Sound:false,Scriptaculous:false}}},{}],186:[function(require,module,exports){module.exports=require("./globals.json")},{"./globals.json":185}],187:[function(require,module,exports){function combine(){return new RegExp("("+[].slice.call(arguments).map(function(e){var e=e.toString();return"(?:"+e.substring(1,e.length-1)+")"}).join("|")+")")}function makeTester(rx){var s=rx.toString();return new RegExp("^"+s.substring(1,s.length-1)+"$")}var pattern={string1:/"(?:(?:\\\n|\\"|[^"\n]))*?"/,string2:/'(?:(?:\\\n|\\'|[^'\n]))*?'/,comment1:/\/\*[\s\S]*?\*\//,comment2:/\/\/.*?\n/,whitespace:/\s+/,keyword:/\b(?:var|let|for|if|else|in|class|function|return|with|case|break|switch|export|new|while|do|throw|catch)\b/,regexp:/\/(?:(?:\\\/|[^\n\/]))*?\//,name:/[a-zA-Z_\$][a-zA-Z_\$0-9]*/,number:/\d+(?:\.\d+)?(?:e[+-]?\d+)?/,parens:/[\(\)]/,curly:/[{}]/,square:/[\[\]]/,punct:/[;.:\?\^%<>=!&|+\-,~]/};var match=combine(pattern.string1,pattern.string2,pattern.comment1,pattern.comment2,pattern.regexp,pattern.whitespace,pattern.name,pattern.number,pattern.parens,pattern.curly,pattern.square,pattern.punct);var tester={};for(var k in pattern){tester[k]=makeTester(pattern[k])}module.exports=function(str,doNotThrow){return str.split(match).filter(function(e,i){if(i%2)return true;if(e!==""){if(!doNotThrow)throw new Error("invalid token:"+JSON.stringify(e));return true}})};module.exports.type=function(e){for(var type in pattern)if(tester[type].test(e))return type;return"invalid"}},{}],188:[function(require,module,exports){function compact(array){var index=-1,length=array?array.length:0,resIndex=-1,result=[];while(++index<length){var value=array[index];if(value){result[++resIndex]=value}}return result}module.exports=compact},{}],189:[function(require,module,exports){var baseFlatten=require("../internal/baseFlatten"),isIterateeCall=require("../internal/isIterateeCall");function flatten(array,isDeep,guard){var length=array?array.length:0;if(guard&&isIterateeCall(array,isDeep,guard)){isDeep=false}return length?baseFlatten(array,isDeep):[]}module.exports=flatten},{"../internal/baseFlatten":216,"../internal/isIterateeCall":255}],190:[function(require,module,exports){function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}module.exports=last},{}],191:[function(require,module,exports){var baseIndexOf=require("../internal/baseIndexOf");var arrayProto=Array.prototype;var splice=arrayProto.splice;function pull(){var array=arguments[0];if(!(array&&array.length)){return array}var index=0,indexOf=baseIndexOf,length=arguments.length;while(++index<length){var fromIndex=0,value=arguments[index];while((fromIndex=indexOf(array,value,fromIndex))>-1){splice.call(array,fromIndex,1)}}return array}module.exports=pull},{"../internal/baseIndexOf":222}],192:[function(require,module,exports){var baseCallback=require("../internal/baseCallback"),baseUniq=require("../internal/baseUniq"),isIterateeCall=require("../internal/isIterateeCall"),sortedUniq=require("../internal/sortedUniq");function uniq(array,isSorted,iteratee,thisArg){var length=array?array.length:0;if(!length){return[]}if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=iteratee;iteratee=isIterateeCall(array,isSorted,thisArg)?null:isSorted;isSorted=false}iteratee=iteratee==null?iteratee:baseCallback(iteratee,thisArg,3);return isSorted?sortedUniq(array,iteratee):baseUniq(array,iteratee)}module.exports=uniq},{"../internal/baseCallback":210,"../internal/baseUniq":236,"../internal/isIterateeCall":255,"../internal/sortedUniq":262}],193:[function(require,module,exports){module.exports=require("./includes")},{"./includes":197}],194:[function(require,module,exports){module.exports=require("./forEach")},{"./forEach":195}],195:[function(require,module,exports){var arrayEach=require("../internal/arrayEach"),baseEach=require("../internal/baseEach"),bindCallback=require("../internal/bindCallback"),isArray=require("../lang/isArray");function forEach(collection,iteratee,thisArg){return typeof iteratee=="function"&&typeof thisArg=="undefined"&&isArray(collection)?arrayEach(collection,iteratee):baseEach(collection,bindCallback(iteratee,thisArg,3))}module.exports=forEach},{"../internal/arrayEach":204,"../internal/baseEach":214,"../internal/bindCallback":238,"../lang/isArray":267}],196:[function(require,module,exports){var createAggregator=require("../internal/createAggregator");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value)}else{result[key]=[value]}});module.exports=groupBy},{"../internal/createAggregator":243}],197:[function(require,module,exports){var baseIndexOf=require("../internal/baseIndexOf"),isArray=require("../lang/isArray"),isLength=require("../internal/isLength"),isString=require("../lang/isString"),values=require("../object/values");var nativeMax=Math.max;function includes(collection,target,fromIndex){var length=collection?collection.length:0;if(!isLength(length)){collection=values(collection);length=collection.length}if(!length){return false}if(typeof fromIndex=="number"){fromIndex=fromIndex<0?nativeMax(length+fromIndex,0):fromIndex||0}else{fromIndex=0}return typeof collection=="string"||!isArray(collection)&&isString(collection)?fromIndex<length&&collection.indexOf(target,fromIndex)>-1:baseIndexOf(collection,target,fromIndex)>-1}module.exports=includes},{"../internal/baseIndexOf":222,"../internal/isLength":256,"../lang/isArray":267,"../lang/isString":276,"../object/values":286}],198:[function(require,module,exports){var arrayMap=require("../internal/arrayMap"),baseCallback=require("../internal/baseCallback"),baseMap=require("../internal/baseMap"),isArray=require("../lang/isArray");function map(collection,iteratee,thisArg){var func=isArray(collection)?arrayMap:baseMap;iteratee=baseCallback(iteratee,thisArg,3);return func(collection,iteratee)}module.exports=map},{"../internal/arrayMap":205,"../internal/baseCallback":210,"../internal/baseMap":226,"../lang/isArray":267}],199:[function(require,module,exports){var arrayReduceRight=require("../internal/arrayReduceRight"),baseCallback=require("../internal/baseCallback"),baseEachRight=require("../internal/baseEachRight"),baseReduce=require("../internal/baseReduce"),isArray=require("../lang/isArray");function reduceRight(collection,iteratee,accumulator,thisArg){var func=isArray(collection)?arrayReduceRight:baseReduce;return func(collection,baseCallback(iteratee,thisArg,4),accumulator,arguments.length<3,baseEachRight)}module.exports=reduceRight},{"../internal/arrayReduceRight":206,"../internal/baseCallback":210,"../internal/baseEachRight":215,"../internal/baseReduce":231,"../lang/isArray":267}],200:[function(require,module,exports){var arraySome=require("../internal/arraySome"),baseCallback=require("../internal/baseCallback"),baseSome=require("../internal/baseSome"),isArray=require("../lang/isArray");function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;if(typeof predicate!="function"||typeof thisArg!="undefined"){predicate=baseCallback(predicate,thisArg,3)}return func(collection,predicate)}module.exports=some},{"../internal/arraySome":207,"../internal/baseCallback":210,"../internal/baseSome":233,"../lang/isArray":267}],201:[function(require,module,exports){var baseCallback=require("../internal/baseCallback"),baseEach=require("../internal/baseEach"),baseSortBy=require("../internal/baseSortBy"),compareAscending=require("../internal/compareAscending"),isIterateeCall=require("../internal/isIterateeCall"),isLength=require("../internal/isLength");function sortBy(collection,iteratee,thisArg){var index=-1,length=collection?collection.length:0,result=isLength(length)?Array(length):[];if(thisArg&&isIterateeCall(collection,iteratee,thisArg)){iteratee=null}iteratee=baseCallback(iteratee,thisArg,3);baseEach(collection,function(value,key,collection){result[++index]={criteria:iteratee(value,key,collection),index:index,value:value}});return baseSortBy(result,compareAscending)}module.exports=sortBy},{"../internal/baseCallback":210,"../internal/baseEach":214,"../internal/baseSortBy":234,"../internal/compareAscending":242,"../internal/isIterateeCall":255,"../internal/isLength":256}],202:[function(require,module,exports){(function(global){var cachePush=require("./cachePush"),isNative=require("../lang/isNative");var Set=isNative(Set=global.Set)&&Set;var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate;
function SetCache(values){var length=values?values.length:0;this.data={hash:nativeCreate(null),set:new Set};while(length--){this.push(values[length])}}SetCache.prototype.push=cachePush;module.exports=SetCache}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../lang/isNative":271,"./cachePush":241}],203:[function(require,module,exports){function arrayCopy(source,array){var index=-1,length=source.length;array||(array=Array(length));while(++index<length){array[index]=source[index]}return array}module.exports=arrayCopy},{}],204:[function(require,module,exports){function arrayEach(array,iteratee){var index=-1,length=array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break}}return array}module.exports=arrayEach},{}],205:[function(require,module,exports){function arrayMap(array,iteratee){var index=-1,length=array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array)}return result}module.exports=arrayMap},{}],206:[function(require,module,exports){function arrayReduceRight(array,iteratee,accumulator,initFromArray){var length=array.length;if(initFromArray&&length){accumulator=array[--length]}while(length--){accumulator=iteratee(accumulator,array[length],length,array)}return accumulator}module.exports=arrayReduceRight},{}],207:[function(require,module,exports){function arraySome(array,predicate){var index=-1,length=array.length;while(++index<length){if(predicate(array[index],index,array)){return true}}return false}module.exports=arraySome},{}],208:[function(require,module,exports){function assignDefaults(objectValue,sourceValue){return typeof objectValue=="undefined"?sourceValue:objectValue}module.exports=assignDefaults},{}],209:[function(require,module,exports){var baseCopy=require("./baseCopy"),keys=require("../object/keys");function baseAssign(object,source,customizer){var props=keys(source);if(!customizer){return baseCopy(source,object,props)}var index=-1,length=props.length;while(++index<length){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);if((result===result?result!==value:value===value)||typeof value=="undefined"&&!(key in object)){object[key]=result}}return object}module.exports=baseAssign},{"../object/keys":283,"./baseCopy":213}],210:[function(require,module,exports){var baseMatches=require("./baseMatches"),baseProperty=require("./baseProperty"),baseToString=require("./baseToString"),bindCallback=require("./bindCallback"),identity=require("../utility/identity"),isBindable=require("./isBindable");function baseCallback(func,thisArg,argCount){var type=typeof func;if(type=="function"){return typeof thisArg!="undefined"&&isBindable(func)?bindCallback(func,thisArg,argCount):func}if(func==null){return identity}return type=="object"?baseMatches(func,!argCount):baseProperty(argCount?baseToString(func):func)}module.exports=baseCallback},{"../utility/identity":290,"./baseMatches":227,"./baseProperty":230,"./baseToString":235,"./bindCallback":238,"./isBindable":253}],211:[function(require,module,exports){var arrayCopy=require("./arrayCopy"),arrayEach=require("./arrayEach"),baseCopy=require("./baseCopy"),baseForOwn=require("./baseForOwn"),initCloneArray=require("./initCloneArray"),initCloneByTag=require("./initCloneByTag"),initCloneObject=require("./initCloneObject"),isArray=require("../lang/isArray"),isObject=require("../lang/isObject"),keys=require("../object/keys");var argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]";var arrayBufferTag="[object ArrayBuffer]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]";var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=false;var objectProto=Object.prototype;var objToString=objectProto.toString;function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer){result=object?customizer(value,key,object):customizer(value)}if(typeof result!="undefined"){return result}if(!isObject(value)){return value}var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return arrayCopy(value,result)}}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag==objectTag||tag==argsTag||isFunc&&!object){result=initCloneObject(isFunc?{}:value);if(!isDeep){return baseCopy(value,result,keys(value))}}else{return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{}}}stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}stackA.push(value);stackB.push(result);(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)});return result}module.exports=baseClone},{"../lang/isArray":267,"../lang/isObject":273,"../object/keys":283,"./arrayCopy":203,"./arrayEach":204,"./baseCopy":213,"./baseForOwn":219,"./initCloneArray":250,"./initCloneByTag":251,"./initCloneObject":252}],212:[function(require,module,exports){function baseCompareAscending(value,other){if(value!==other){var valIsReflexive=value===value,othIsReflexive=other===other;if(value>other||!valIsReflexive||typeof value=="undefined"&&othIsReflexive){return 1}if(value<other||!othIsReflexive||typeof other=="undefined"&&valIsReflexive){return-1}}return 0}module.exports=baseCompareAscending},{}],213:[function(require,module,exports){function baseCopy(source,object,props){if(!props){props=object;object={}}var index=-1,length=props.length;while(++index<length){var key=props[index];object[key]=source[key]}return object}module.exports=baseCopy},{}],214:[function(require,module,exports){var baseForOwn=require("./baseForOwn"),isLength=require("./isLength"),toObject=require("./toObject");function baseEach(collection,iteratee){var length=collection?collection.length:0;if(!isLength(length)){return baseForOwn(collection,iteratee)}var index=-1,iterable=toObject(collection);while(++index<length){if(iteratee(iterable[index],index,iterable)===false){break}}return collection}module.exports=baseEach},{"./baseForOwn":219,"./isLength":256,"./toObject":263}],215:[function(require,module,exports){var baseForOwnRight=require("./baseForOwnRight"),isLength=require("./isLength"),toObject=require("./toObject");function baseEachRight(collection,iteratee){var length=collection?collection.length:0;if(!isLength(length)){return baseForOwnRight(collection,iteratee)}var iterable=toObject(collection);while(length--){if(iteratee(iterable[length],length,iterable)===false){break}}return collection}module.exports=baseEachRight},{"./baseForOwnRight":220,"./isLength":256,"./toObject":263}],216:[function(require,module,exports){var isArguments=require("../lang/isArguments"),isArray=require("../lang/isArray"),isLength=require("./isLength"),isObjectLike=require("./isObjectLike");function baseFlatten(array,isDeep,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index];if(isObjectLike(value)&&isLength(value.length)&&(isArray(value)||isArguments(value))){if(isDeep){value=baseFlatten(value,isDeep,isStrict)}var valIndex=-1,valLength=value.length;result.length+=valLength;while(++valIndex<valLength){result[++resIndex]=value[valIndex]}}else if(!isStrict){result[++resIndex]=value}}return result}module.exports=baseFlatten},{"../lang/isArguments":266,"../lang/isArray":267,"./isLength":256,"./isObjectLike":257}],217:[function(require,module,exports){var toObject=require("./toObject");function baseFor(object,iteratee,keysFunc){var index=-1,iterable=toObject(object),props=keysFunc(object),length=props.length;while(++index<length){var key=props[index];if(iteratee(iterable[key],key,iterable)===false){break}}return object}module.exports=baseFor},{"./toObject":263}],218:[function(require,module,exports){var baseFor=require("./baseFor"),keysIn=require("../object/keysIn");function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}module.exports=baseForIn},{"../object/keysIn":284,"./baseFor":217}],219:[function(require,module,exports){var baseFor=require("./baseFor"),keys=require("../object/keys");function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}module.exports=baseForOwn},{"../object/keys":283,"./baseFor":217}],220:[function(require,module,exports){var baseForRight=require("./baseForRight"),keys=require("../object/keys");function baseForOwnRight(object,iteratee){return baseForRight(object,iteratee,keys)}module.exports=baseForOwnRight},{"../object/keys":283,"./baseForRight":221}],221:[function(require,module,exports){var toObject=require("./toObject");function baseForRight(object,iteratee,keysFunc){var iterable=toObject(object),props=keysFunc(object),length=props.length;while(length--){var key=props[length];if(iteratee(iterable[key],key,iterable)===false){break}}return object}module.exports=baseForRight},{"./toObject":263}],222:[function(require,module,exports){var indexOfNaN=require("./indexOfNaN");function baseIndexOf(array,value,fromIndex){if(value!==value){return indexOfNaN(array,fromIndex)}var index=(fromIndex||0)-1,length=array.length;while(++index<length){if(array[index]===value){return index}}return-1}module.exports=baseIndexOf},{"./indexOfNaN":249}],223:[function(require,module,exports){var baseIsEqualDeep=require("./baseIsEqualDeep");function baseIsEqual(value,other,customizer,isWhere,stackA,stackB){if(value===other){return value!==0||1/value==1/other}var valType=typeof value,othType=typeof other;if(valType!="function"&&valType!="object"&&othType!="function"&&othType!="object"||value==null||other==null){return value!==value&&other!==other}return baseIsEqualDeep(value,other,baseIsEqual,customizer,isWhere,stackA,stackB)}module.exports=baseIsEqual},{"./baseIsEqualDeep":224}],224:[function(require,module,exports){var equalArrays=require("./equalArrays"),equalByTag=require("./equalByTag"),equalObjects=require("./equalObjects"),isArray=require("../lang/isArray"),isTypedArray=require("../lang/isTypedArray");var argsTag="[object Arguments]",arrayTag="[object Array]",objectTag="[object Object]";var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var objToString=objectProto.toString;function baseIsEqualDeep(object,other,equalFunc,customizer,isWhere,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;if(!objIsArr){objTag=objToString.call(object);if(objTag==argsTag){objTag=objectTag}else if(objTag!=objectTag){objIsArr=isTypedArray(object)}}if(!othIsArr){othTag=objToString.call(other);if(othTag==argsTag){othTag=objectTag}else if(othTag!=objectTag){othIsArr=isTypedArray(other)}}var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!(objIsArr||objIsObj)){return equalByTag(object,other,objTag)}var valWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(valWrapped||othWrapped){return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isWhere,stackA,stackB)}if(!isSameTag){return false}stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==object){return stackB[length]==other}}stackA.push(object);stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isWhere,stackA,stackB);stackA.pop();stackB.pop();return result}module.exports=baseIsEqualDeep},{"../lang/isArray":267,"../lang/isTypedArray":277,"./equalArrays":246,"./equalByTag":247,"./equalObjects":248}],225:[function(require,module,exports){var baseIsEqual=require("./baseIsEqual");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function baseIsMatch(object,props,values,strictCompareFlags,customizer){var length=props.length;if(object==null){return!length}var index=-1,noCustomizer=!customizer;while(++index<length){if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!hasOwnProperty.call(object,props[index])){return false}}index=-1;while(++index<length){var key=props[index];if(noCustomizer&&strictCompareFlags[index]){var result=hasOwnProperty.call(object,key)}else{var objValue=object[key],srcValue=values[index];result=customizer?customizer(objValue,srcValue,key):undefined;if(typeof result=="undefined"){result=baseIsEqual(srcValue,objValue,customizer,true)}}if(!result){return false}}return true}module.exports=baseIsMatch},{"./baseIsEqual":223}],226:[function(require,module,exports){var baseEach=require("./baseEach");function baseMap(collection,iteratee){var result=[];baseEach(collection,function(value,key,collection){result.push(iteratee(value,key,collection))});return result}module.exports=baseMap},{"./baseEach":214}],227:[function(require,module,exports){var baseClone=require("./baseClone"),baseIsMatch=require("./baseIsMatch"),isStrictComparable=require("./isStrictComparable"),keys=require("../object/keys");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function baseMatches(source,isCloned){var props=keys(source),length=props.length;if(length==1){var key=props[0],value=source[key];if(isStrictComparable(value)){return function(object){return object!=null&&value===object[key]&&hasOwnProperty.call(object,key)}}}if(isCloned){source=baseClone(source,true)}var values=Array(length),strictCompareFlags=Array(length);while(length--){value=source[props[length]];values[length]=value;strictCompareFlags[length]=isStrictComparable(value)}return function(object){return baseIsMatch(object,props,values,strictCompareFlags)}}module.exports=baseMatches},{"../object/keys":283,"./baseClone":211,"./baseIsMatch":225,"./isStrictComparable":258}],228:[function(require,module,exports){var arrayEach=require("./arrayEach"),baseForOwn=require("./baseForOwn"),baseMergeDeep=require("./baseMergeDeep"),isArray=require("../lang/isArray"),isLength=require("./isLength"),isObjectLike=require("./isObjectLike"),isTypedArray=require("../lang/isTypedArray");function baseMerge(object,source,customizer,stackA,stackB){var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));(isSrcArr?arrayEach:baseForOwn)(source,function(srcValue,key,source){if(isObjectLike(srcValue)){stackA||(stackA=[]);stackB||(stackB=[]);return baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB)}var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=typeof result=="undefined";if(isCommon){result=srcValue}if((isSrcArr||typeof result!="undefined")&&(isCommon||(result===result?result!==value:value===value))){object[key]=result}});return object}module.exports=baseMerge},{"../lang/isArray":267,"../lang/isTypedArray":277,"./arrayEach":204,"./baseForOwn":219,"./baseMergeDeep":229,"./isLength":256,"./isObjectLike":257}],229:[function(require,module,exports){var arrayCopy=require("./arrayCopy"),isArguments=require("../lang/isArguments"),isArray=require("../lang/isArray"),isLength=require("./isLength"),isPlainObject=require("../lang/isPlainObject"),isTypedArray=require("../lang/isTypedArray"),toPlainObject=require("../lang/toPlainObject");function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){var length=stackA.length,srcValue=source[key];while(length--){if(stackA[length]==srcValue){object[key]=stackB[length];return}}var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=typeof result=="undefined";if(isCommon){result=srcValue;if(isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))){result=isArray(value)?value:value?arrayCopy(value):[]}else if(isPlainObject(srcValue)||isArguments(srcValue)){result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}}}stackA.push(srcValue);stackB.push(result);if(isCommon){object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB)}else if(result===result?result!==value:value===value){object[key]=result}}module.exports=baseMergeDeep},{"../lang/isArguments":266,"../lang/isArray":267,"../lang/isPlainObject":274,"../lang/isTypedArray":277,"../lang/toPlainObject":278,"./arrayCopy":203,"./isLength":256}],230:[function(require,module,exports){function baseProperty(key){return function(object){return object==null?undefined:object[key]}}module.exports=baseProperty},{}],231:[function(require,module,exports){function baseReduce(collection,iteratee,accumulator,initFromCollection,eachFunc){eachFunc(collection,function(value,index,collection){accumulator=initFromCollection?(initFromCollection=false,value):iteratee(accumulator,value,index,collection)});return accumulator}module.exports=baseReduce},{}],232:[function(require,module,exports){var identity=require("../utility/identity"),metaMap=require("./metaMap");var baseSetData=!metaMap?identity:function(func,data){metaMap.set(func,data);return func};module.exports=baseSetData},{"../utility/identity":290,"./metaMap":259}],233:[function(require,module,exports){var baseEach=require("./baseEach");function baseSome(collection,predicate){var result;baseEach(collection,function(value,index,collection){result=predicate(value,index,collection);return!result});return!!result}module.exports=baseSome},{"./baseEach":214}],234:[function(require,module,exports){function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value}return array}module.exports=baseSortBy},{}],235:[function(require,module,exports){function baseToString(value){if(typeof value=="string"){return value}return value==null?"":value+""}module.exports=baseToString},{}],236:[function(require,module,exports){var baseIndexOf=require("./baseIndexOf"),cacheIndexOf=require("./cacheIndexOf"),createCache=require("./createCache");function baseUniq(array,iteratee){var index=-1,indexOf=baseIndexOf,length=array.length,isCommon=true,isLarge=isCommon&&length>=200,seen=isLarge&&createCache(),result=[];if(seen){indexOf=cacheIndexOf;isCommon=false}else{isLarge=false;seen=iteratee?[]:result}outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value,index,array):value;if(isCommon&&value===value){var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===computed){continue outer}}if(iteratee){seen.push(computed)}result.push(value)}else if(indexOf(seen,computed)<0){if(iteratee||isLarge){seen.push(computed)}result.push(value)}}return result}module.exports=baseUniq},{"./baseIndexOf":222,"./cacheIndexOf":240,"./createCache":245}],237:[function(require,module,exports){function baseValues(object,props){var index=-1,length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}module.exports=baseValues},{}],238:[function(require,module,exports){var identity=require("../utility/identity");function bindCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof thisArg=="undefined"){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}module.exports=bindCallback},{"../utility/identity":290}],239:[function(require,module,exports){(function(global){var constant=require("../utility/constant"),isNative=require("../lang/isNative");var ArrayBuffer=isNative(ArrayBuffer=global.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,Uint8Array=isNative(Uint8Array=global.Uint8Array)&&Uint8Array;var Float64Array=function(){try{var func=isNative(func=global.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}();var FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0;function bufferClone(buffer){return bufferSlice.call(buffer,0)}if(!bufferSlice){bufferClone=!(ArrayBuffer&&Uint8Array)?constant(null):function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}if(byteLength!=offset){view=new Uint8Array(result,offset);view.set(new Uint8Array(buffer,offset))}return result}}module.exports=bufferClone}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../lang/isNative":271,"../utility/constant":289}],240:[function(require,module,exports){var isObject=require("../lang/isObject");function cacheIndexOf(cache,value){var data=cache.data,result=typeof value=="string"||isObject(value)?data.set.has(value):data.hash[value];return result?0:-1}module.exports=cacheIndexOf},{"../lang/isObject":273}],241:[function(require,module,exports){var isObject=require("../lang/isObject");function cachePush(value){var data=this.data;if(typeof value=="string"||isObject(value)){data.set.add(value)}else{data.hash[value]=true}}module.exports=cachePush},{"../lang/isObject":273}],242:[function(require,module,exports){var baseCompareAscending=require("./baseCompareAscending");function compareAscending(object,other){return baseCompareAscending(object.criteria,other.criteria)||object.index-other.index}module.exports=compareAscending},{"./baseCompareAscending":212}],243:[function(require,module,exports){var baseCallback=require("./baseCallback"),baseEach=require("./baseEach"),isArray=require("../lang/isArray");function createAggregator(setter,initializer){return function(collection,iteratee,thisArg){var result=initializer?initializer():{};iteratee=baseCallback(iteratee,thisArg,3);if(isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];setter(result,value,iteratee(value,index,collection),collection)}}else{baseEach(collection,function(value,key,collection){setter(result,value,iteratee(value,key,collection),collection)})}return result}}module.exports=createAggregator},{"../lang/isArray":267,"./baseCallback":210,"./baseEach":214}],244:[function(require,module,exports){var bindCallback=require("./bindCallback"),isIterateeCall=require("./isIterateeCall");function createAssigner(assigner){return function(){var length=arguments.length,object=arguments[0];if(length<2||object==null){return object}if(length>3&&isIterateeCall(arguments[1],arguments[2],arguments[3])){length=2}if(length>3&&typeof arguments[length-2]=="function"){var customizer=bindCallback(arguments[--length-1],arguments[length--],5)}else if(length>2&&typeof arguments[length-1]=="function"){customizer=arguments[--length]}var index=0;while(++index<length){var source=arguments[index];if(source){assigner(object,source,customizer)}}return object}}module.exports=createAssigner},{"./bindCallback":238,"./isIterateeCall":255}],245:[function(require,module,exports){(function(global){var SetCache=require("./SetCache"),constant=require("../utility/constant"),isNative=require("../lang/isNative");var Set=isNative(Set=global.Set)&&Set;var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate;var createCache=!(nativeCreate&&Set)?constant(null):function(values){return new SetCache(values)};module.exports=createCache}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../lang/isNative":271,"../utility/constant":289,"./SetCache":202}],246:[function(require,module,exports){function equalArrays(array,other,equalFunc,customizer,isWhere,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=true;if(arrLength!=othLength&&!(isWhere&&othLength>arrLength)){return false}while(result&&++index<arrLength){var arrValue=array[index],othValue=other[index];result=undefined;if(customizer){result=isWhere?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)}if(typeof result=="undefined"){if(isWhere){var othIndex=othLength;while(othIndex--){othValue=other[othIndex];result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isWhere,stackA,stackB);if(result){break}}}else{result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isWhere,stackA,stackB)}}}return!!result}module.exports=equalArrays},{}],247:[function(require,module,exports){var baseToString=require("./baseToString");var boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",numberTag="[object Number]",regexpTag="[object RegExp]",stringTag="[object String]";function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:object==0?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==baseToString(other)}return false}module.exports=equalByTag},{"./baseToString":235}],248:[function(require,module,exports){var keys=require("../object/keys");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function equalObjects(object,other,equalFunc,customizer,isWhere,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isWhere){return false}var hasCtor,index=-1;while(++index<objLength){var key=objProps[index],result=hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined;if(customizer){result=isWhere?customizer(othValue,objValue,key):customizer(objValue,othValue,key)}if(typeof result=="undefined"){result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isWhere,stackA,stackB)}}if(!result){return false}hasCtor||(hasCtor=key=="constructor")}if(!hasCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&("constructor"in object&&"constructor"in other)&&!(typeof objCtor=="function"&&objCtor instanceof objCtor&&typeof othCtor=="function"&&othCtor instanceof othCtor)){return false}}return true}module.exports=equalObjects},{"../object/keys":283}],249:[function(require,module,exports){function indexOfNaN(array,fromIndex,fromRight){var length=array.length,index=fromRight?fromIndex||length:(fromIndex||0)-1;while(fromRight?index--:++index<length){var other=array[index];if(other!==other){return index}}return-1}module.exports=indexOfNaN},{}],250:[function(require,module,exports){var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function initCloneArray(array){var length=array.length,result=new array.constructor(length);if(length&&typeof array[0]=="string"&&hasOwnProperty.call(array,"index")){result.index=array.index;result.input=array.input}return result}module.exports=initCloneArray},{}],251:[function(require,module,exports){var bufferClone=require("./bufferClone");var boolTag="[object Boolean]",dateTag="[object Date]",numberTag="[object Number]",regexpTag="[object RegExp]",stringTag="[object String]";var arrayBufferTag="[object ArrayBuffer]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]";var reFlags=/\w*$/;function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}module.exports=initCloneByTag},{"./bufferClone":239}],252:[function(require,module,exports){function initCloneObject(object){var Ctor=object.constructor;if(!(typeof Ctor=="function"&&Ctor instanceof Ctor)){Ctor=Object}return new Ctor}module.exports=initCloneObject},{}],253:[function(require,module,exports){var baseSetData=require("./baseSetData"),isNative=require("../lang/isNative"),support=require("../support");var reFuncName=/^\s*function[ \n\r\t]+\w/;var reThis=/\bthis\b/;var fnToString=Function.prototype.toString;function isBindable(func){var result=!(support.funcNames?func.name:support.funcDecomp);if(!result){var source=fnToString.call(func);if(!support.funcNames){result=!reFuncName.test(source)}if(!result){result=reThis.test(source)||isNative(func);baseSetData(func,result)}}return result}module.exports=isBindable},{"../lang/isNative":271,"../support":288,"./baseSetData":232}],254:[function(require,module,exports){var MAX_SAFE_INTEGER=Math.pow(2,53)-1;function isIndex(value,length){value=+value;length=length==null?MAX_SAFE_INTEGER:length;return value>-1&&value%1==0&&value<length}module.exports=isIndex},{}],255:[function(require,module,exports){var isIndex=require("./isIndex"),isLength=require("./isLength"),isObject=require("../lang/isObject");function isIterateeCall(value,index,object){if(!isObject(object)){return false}var type=typeof index;if(type=="number"){var length=object.length,prereq=isLength(length)&&isIndex(index,length)}else{prereq=type=="string"&&index in value}return prereq&&object[index]===value}module.exports=isIterateeCall},{"../lang/isObject":273,"./isIndex":254,"./isLength":256}],256:[function(require,module,exports){var MAX_SAFE_INTEGER=Math.pow(2,53)-1;function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}module.exports=isLength},{}],257:[function(require,module,exports){function isObjectLike(value){return value&&typeof value=="object"||false}module.exports=isObjectLike},{}],258:[function(require,module,exports){var isObject=require("../lang/isObject");function isStrictComparable(value){return value===value&&(value===0?1/value>0:!isObject(value))}module.exports=isStrictComparable},{"../lang/isObject":273}],259:[function(require,module,exports){(function(global){var isNative=require("../lang/isNative");var WeakMap=isNative(WeakMap=global.WeakMap)&&WeakMap;var metaMap=WeakMap&&new WeakMap;module.exports=metaMap}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../lang/isNative":271}],260:[function(require,module,exports){var baseForIn=require("./baseForIn"),isObjectLike=require("./isObjectLike");
var objectTag="[object Object]";var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var objToString=objectProto.toString;function shimIsPlainObject(value){var Ctor;if(!(isObjectLike(value)&&objToString.call(value)==objectTag)||!hasOwnProperty.call(value,"constructor")&&(Ctor=value.constructor,typeof Ctor=="function"&&!(Ctor instanceof Ctor))){return false}var result;baseForIn(value,function(subValue,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}module.exports=shimIsPlainObject},{"./baseForIn":218,"./isObjectLike":257}],261:[function(require,module,exports){var isArguments=require("../lang/isArguments"),isArray=require("../lang/isArray"),isIndex=require("./isIndex"),isLength=require("./isLength"),keysIn=require("../object/keysIn"),support=require("../support");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function shimKeys(object){var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length;var allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object));var index=-1,result=[];while(++index<propsLength){var key=props[index];if(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key)){result.push(key)}}return result}module.exports=shimKeys},{"../lang/isArguments":266,"../lang/isArray":267,"../object/keysIn":284,"../support":288,"./isIndex":254,"./isLength":256}],262:[function(require,module,exports){function sortedUniq(array,iteratee){var seen,index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index],computed=iteratee?iteratee(value,index,array):value;if(!index||seen!==computed){seen=computed;result[++resIndex]=value}}return result}module.exports=sortedUniq},{}],263:[function(require,module,exports){var isObject=require("../lang/isObject");function toObject(value){return isObject(value)?value:Object(value)}module.exports=toObject},{"../lang/isObject":273}],264:[function(require,module,exports){var baseClone=require("../internal/baseClone"),bindCallback=require("../internal/bindCallback"),isIterateeCall=require("../internal/isIterateeCall");function clone(value,isDeep,customizer,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=customizer;customizer=isIterateeCall(value,isDeep,thisArg)?null:isDeep;isDeep=false}customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,1);return baseClone(value,isDeep,customizer)}module.exports=clone},{"../internal/baseClone":211,"../internal/bindCallback":238,"../internal/isIterateeCall":255}],265:[function(require,module,exports){var baseClone=require("../internal/baseClone"),bindCallback=require("../internal/bindCallback");function cloneDeep(value,customizer,thisArg){customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,1);return baseClone(value,true,customizer)}module.exports=cloneDeep},{"../internal/baseClone":211,"../internal/bindCallback":238}],266:[function(require,module,exports){var isLength=require("../internal/isLength"),isObjectLike=require("../internal/isObjectLike");var argsTag="[object Arguments]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag||false}module.exports=isArguments},{"../internal/isLength":256,"../internal/isObjectLike":257}],267:[function(require,module,exports){var isLength=require("../internal/isLength"),isNative=require("./isNative"),isObjectLike=require("../internal/isObjectLike");var arrayTag="[object Array]";var objectProto=Object.prototype;var objToString=objectProto.toString;var nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray;var isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag||false};module.exports=isArray},{"../internal/isLength":256,"../internal/isObjectLike":257,"./isNative":271}],268:[function(require,module,exports){var isObjectLike=require("../internal/isObjectLike");var boolTag="[object Boolean]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isBoolean(value){return value===true||value===false||isObjectLike(value)&&objToString.call(value)==boolTag||false}module.exports=isBoolean},{"../internal/isObjectLike":257}],269:[function(require,module,exports){var isArguments=require("./isArguments"),isArray=require("./isArray"),isFunction=require("./isFunction"),isLength=require("../internal/isLength"),isObjectLike=require("../internal/isObjectLike"),isString=require("./isString"),keys=require("../object/keys");function isEmpty(value){if(value==null){return true}var length=value.length;if(isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))){return!length}return!keys(value).length}module.exports=isEmpty},{"../internal/isLength":256,"../internal/isObjectLike":257,"../object/keys":283,"./isArguments":266,"./isArray":267,"./isFunction":270,"./isString":276}],270:[function(require,module,exports){(function(global){var isNative=require("./isNative");var funcTag="[object Function]";var objectProto=Object.prototype;var objToString=objectProto.toString;var Uint8Array=isNative(Uint8Array=global.Uint8Array)&&Uint8Array;function isFunction(value){return typeof value=="function"||false}if(isFunction(/x/)||Uint8Array&&!isFunction(Uint8Array)){isFunction=function(value){return objToString.call(value)==funcTag}}module.exports=isFunction}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./isNative":271}],271:[function(require,module,exports){var escapeRegExp=require("../string/escapeRegExp"),isObjectLike=require("../internal/isObjectLike");var funcTag="[object Function]";var reHostCtor=/^\[object .+?Constructor\]$/;var objectProto=Object.prototype;var fnToString=Function.prototype.toString;var objToString=objectProto.toString;var reNative=RegExp("^"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function isNative(value){if(value==null){return false}if(objToString.call(value)==funcTag){return reNative.test(fnToString.call(value))}return isObjectLike(value)&&reHostCtor.test(value)||false}module.exports=isNative},{"../internal/isObjectLike":257,"../string/escapeRegExp":287}],272:[function(require,module,exports){var isObjectLike=require("../internal/isObjectLike");var numberTag="[object Number]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isNumber(value){return typeof value=="number"||isObjectLike(value)&&objToString.call(value)==numberTag||false}module.exports=isNumber},{"../internal/isObjectLike":257}],273:[function(require,module,exports){function isObject(value){var type=typeof value;return type=="function"||value&&type=="object"||false}module.exports=isObject},{}],274:[function(require,module,exports){var isNative=require("./isNative"),shimIsPlainObject=require("../internal/shimIsPlainObject");var objectTag="[object Object]";var objectProto=Object.prototype;var objToString=objectProto.toString;var getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf;var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&objToString.call(value)==objectTag)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};module.exports=isPlainObject},{"../internal/shimIsPlainObject":260,"./isNative":271}],275:[function(require,module,exports){var isObjectLike=require("../internal/isObjectLike");var regexpTag="[object RegExp]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isRegExp(value){return isObjectLike(value)&&objToString.call(value)==regexpTag||false}module.exports=isRegExp},{"../internal/isObjectLike":257}],276:[function(require,module,exports){var isObjectLike=require("../internal/isObjectLike");var stringTag="[object String]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isString(value){return typeof value=="string"||isObjectLike(value)&&objToString.call(value)==stringTag||false}module.exports=isString},{"../internal/isObjectLike":257}],277:[function(require,module,exports){var isLength=require("../internal/isLength"),isObjectLike=require("../internal/isObjectLike");var argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]";var arrayBufferTag="[object ArrayBuffer]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]";var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;var objectProto=Object.prototype;var objToString=objectProto.toString;function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&typedArrayTags[objToString.call(value)]||false}module.exports=isTypedArray},{"../internal/isLength":256,"../internal/isObjectLike":257}],278:[function(require,module,exports){var baseCopy=require("../internal/baseCopy"),keysIn=require("../object/keysIn");function toPlainObject(value){return baseCopy(value,keysIn(value))}module.exports=toPlainObject},{"../internal/baseCopy":213,"../object/keysIn":284}],279:[function(require,module,exports){var baseAssign=require("../internal/baseAssign"),createAssigner=require("../internal/createAssigner");var assign=createAssigner(baseAssign);module.exports=assign},{"../internal/baseAssign":209,"../internal/createAssigner":244}],280:[function(require,module,exports){var arrayCopy=require("../internal/arrayCopy"),assign=require("./assign"),assignDefaults=require("../internal/assignDefaults");function defaults(object){if(object==null){return object}var args=arrayCopy(arguments);args.push(assignDefaults);return assign.apply(undefined,args)}module.exports=defaults},{"../internal/arrayCopy":203,"../internal/assignDefaults":208,"./assign":279}],281:[function(require,module,exports){module.exports=require("./assign")},{"./assign":279}],282:[function(require,module,exports){var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function has(object,key){return object?hasOwnProperty.call(object,key):false}module.exports=has},{}],283:[function(require,module,exports){var isLength=require("../internal/isLength"),isNative=require("../lang/isNative"),isObject=require("../lang/isObject"),shimKeys=require("../internal/shimKeys");var nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys;var keys=!nativeKeys?shimKeys:function(object){if(object){var Ctor=object.constructor,length=object.length}if(typeof Ctor=="function"&&Ctor.prototype===object||typeof object!="function"&&(length&&isLength(length))){return shimKeys(object)}return isObject(object)?nativeKeys(object):[]};module.exports=keys},{"../internal/isLength":256,"../internal/shimKeys":261,"../lang/isNative":271,"../lang/isObject":273}],284:[function(require,module,exports){var isArguments=require("../lang/isArguments"),isArray=require("../lang/isArray"),isIndex=require("../internal/isIndex"),isLength=require("../internal/isLength"),isObject=require("../lang/isObject"),support=require("../support");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function keysIn(object){if(object==null){return[]}if(!isObject(object)){object=Object(object)}var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;var Ctor=object.constructor,index=-1,isProto=typeof Ctor=="function"&&Ctor.prototype==object,result=Array(length),skipIndexes=length>0;while(++index<length){result[index]=index+""}for(var key in object){if(!(skipIndexes&&isIndex(key,length))&&!(key=="constructor"&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key)}}return result}module.exports=keysIn},{"../internal/isIndex":254,"../internal/isLength":256,"../lang/isArguments":266,"../lang/isArray":267,"../lang/isObject":273,"../support":288}],285:[function(require,module,exports){var baseMerge=require("../internal/baseMerge"),createAssigner=require("../internal/createAssigner");var merge=createAssigner(baseMerge);module.exports=merge},{"../internal/baseMerge":228,"../internal/createAssigner":244}],286:[function(require,module,exports){var baseValues=require("../internal/baseValues"),keys=require("./keys");function values(object){return baseValues(object,keys(object))}module.exports=values},{"../internal/baseValues":237,"./keys":283}],287:[function(require,module,exports){var baseToString=require("../internal/baseToString");var reRegExpChars=/[.*+?^${}()|[\]\/\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source);function escapeRegExp(string){string=baseToString(string);return string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,"\\$&"):string}module.exports=escapeRegExp},{"../internal/baseToString":235}],288:[function(require,module,exports){(function(global){var isNative=require("./lang/isNative");var reThis=/\bthis\b/;var objectProto=Object.prototype;var document=(document=global.window)&&document.document;var propertyIsEnumerable=objectProto.propertyIsEnumerable;var support={};(function(x){support.funcDecomp=!isNative(global.WinRTError)&&reThis.test(function(){return this});support.funcNames=typeof Function.name=="string";try{support.dom=document.createDocumentFragment().nodeType===11}catch(e){support.dom=false}try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=true}})(0,0);module.exports=support}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./lang/isNative":271}],289:[function(require,module,exports){function constant(value){return function(){return value}}module.exports=constant},{}],290:[function(require,module,exports){function identity(value){return value}module.exports=identity},{}],291:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],292:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var isArray=types.builtInTypes.array;var b=types.builders;var n=types.namedTypes;var leap=require("./leap");var meta=require("./meta");var util=require("./util");var hasOwn=Object.prototype.hasOwnProperty;function Emitter(contextId){assert.ok(this instanceof Emitter);n.Identifier.assert(contextId);Object.defineProperties(this,{contextId:{value:contextId},listing:{value:[]},marked:{value:[true]},finalLoc:{value:loc()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new leap.LeapManager(this)}})}var Ep=Emitter.prototype;exports.Emitter=Emitter;function loc(){return b.literal(-1)}Ep.mark=function(loc){n.Literal.assert(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Ep.emit=function(node){if(n.Expression.check(node))node=b.expressionStatement(node);n.Statement.assert(node);this.listing.push(node)};Ep.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Ep.assign=function(lhs,rhs){return b.expressionStatement(b.assignmentExpression("=",lhs,rhs))};Ep.contextProperty=function(name,computed){return b.memberExpression(this.contextId,computed?b.literal(name):b.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Ep.isVolatileContextProperty=function(expr){if(n.MemberExpression.check(expr)){if(expr.computed){return true}if(n.Identifier.check(expr.object)&&n.Identifier.check(expr.property)&&expr.object.name===this.contextId.name&&hasOwn.call(volatileContextPropertyNames,expr.property.name)){return true}}return false};Ep.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Ep.setReturnValue=function(valuePath){n.Expression.assert(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Ep.clearPendingException=function(tryLoc,assignee){n.Literal.assert(tryLoc);var catchCall=b.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Ep.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(b.breakStatement())};Ep.jumpIf=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);this.emit(b.ifStatement(test,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};Ep.jumpIfNot=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);var negatedTest;if(n.UnaryExpression.check(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=b.unaryExpression("!",test)}this.emit(b.ifStatement(negatedTest,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};var nextTempId=0;Ep.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Ep.getContextFunction=function(id){var func=b.functionExpression(id||null,[this.contextId],b.blockStatement([this.getDispatchLoop()]),false,false);func._aliasFunction=true;return func};Ep.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(b.switchCase(b.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(b.switchCase(this.finalLoc,[]),b.switchCase(b.literal("end"),[b.returnStatement(b.callExpression(this.contextProperty("stop"),[]))]));return b.whileStatement(b.literal(1),b.switchStatement(b.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return n.BreakStatement.check(stmt)||n.ContinueStatement.check(stmt)||n.ReturnStatement.check(stmt)||n.ThrowStatement.check(stmt)}Ep.getTryLocsList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return b.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var locs=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){locs[2]=fe.firstLoc;locs[3]=fe.afterLoc}return b.arrayExpression(locs)}))};Ep.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.assert(node);if(n.Statement.check(node))return self.explodeStatement(path);if(n.Expression.check(node))return self.explodeExpression(path,ignoreResult);if(n.Declaration.check(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Ep.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;n.Statement.assert(stmt);if(labelId){n.Identifier.assert(labelId)}else{labelId=null}if(n.BlockStatement.check(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}switch(stmt.type){case"ExpressionStatement":self.explodeExpression(path.get("expression"),true);break;case"LabeledStatement":var after=loc();self.leapManager.withEntry(new leap.LabeledEntry(after,stmt.label),function(){self.explodeStatement(path.get("body"),stmt.label)});self.mark(after);break;case"WhileStatement":var before=loc();var after=loc();self.mark(before);self.jumpIfNot(self.explodeExpression(path.get("test")),after);self.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(before);self.mark(after);break;case"DoWhileStatement":var first=loc();var test=loc();var after=loc();self.mark(first);self.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){self.explode(path.get("body"))});self.mark(test);self.jumpIf(self.explodeExpression(path.get("test")),first);self.mark(after);break;case"ForStatement":var head=loc();var update=loc();var after=loc();if(stmt.init){self.explode(path.get("init"),true)}self.mark(head);if(stmt.test){self.jumpIfNot(self.explodeExpression(path.get("test")),after)}else{}self.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){self.explodeStatement(path.get("body"))});self.mark(update);if(stmt.update){self.explode(path.get("update"),true)}self.jump(head);self.mark(after);break;case"ForInStatement":n.Identifier.assert(stmt.left);var head=loc();var after=loc();var keyIterNextFn=self.makeTempVar();self.emitAssign(keyIterNextFn,b.callExpression(util.runtimeProperty("keys"),[self.explodeExpression(path.get("right"))]));self.mark(head);var keyInfoTmpVar=self.makeTempVar();self.jumpIf(b.memberExpression(b.assignmentExpression("=",keyInfoTmpVar,b.callExpression(keyIterNextFn,[])),b.identifier("done"),false),after);self.emitAssign(stmt.left,b.memberExpression(keyInfoTmpVar,b.identifier("value"),false));self.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(head);self.mark(after);break;case"BreakStatement":self.emitAbruptCompletion({type:"break",target:self.leapManager.getBreakLoc(stmt.label)});break;case"ContinueStatement":self.emitAbruptCompletion({type:"continue",target:self.leapManager.getContinueLoc(stmt.label)});break;case"SwitchStatement":var disc=self.emitAssign(self.makeTempVar(),self.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];n.SwitchCase.assert(c);if(c.test){condition=b.conditionalExpression(b.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}self.jump(self.explodeExpression(new types.NodePath(condition,path,"discriminant")));self.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var c=casePath.value;var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});self.mark(after);if(defaultLoc.value===-1){self.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}break;case"IfStatement":var elseLoc=stmt.alternate&&loc();var after=loc();self.jumpIfNot(self.explodeExpression(path.get("test")),elseLoc||after);self.explodeStatement(path.get("consequent"));if(elseLoc){self.jump(after);self.mark(elseLoc);self.explodeStatement(path.get("alternate"))}self.mark(after);break;case"ReturnStatement":self.emitAbruptCompletion({type:"return",value:self.explodeExpression(path.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var after=loc();var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc,after);var tryEntry=new leap.TryEntry(self.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);self.tryEntries.push(tryEntry);self.updateContextPrevLoc(tryEntry.firstLoc);self.leapManager.withEntry(tryEntry,function(){self.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){self.jump(finallyLoc)}else{self.jump(after)}self.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=self.makeTempVar();self.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;n.CatchClause.assert(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(util.isReference(path,catchParamName)&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)},visitFunction:function(path){if(path.scope.declares(catchParamName)){return false}this.traverse(path)}});self.leapManager.withEntry(catchEntry,function(){self.explodeStatement(bodyPath)})}if(finallyLoc){self.updateContextPrevLoc(self.mark(finallyLoc));self.leapManager.withEntry(finallyEntry,function(){self.explodeStatement(path.get("finalizer"))});self.emit(b.returnStatement(b.callExpression(self.contextProperty("finish"),[finallyEntry.firstLoc])))}});self.mark(after);break;case"ThrowStatement":self.emit(b.throwStatement(self.explodeExpression(path.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Ep.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[b.literal(record.type)];if(record.type==="break"||record.type==="continue"){n.Literal.assert(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){n.Expression.assert(record.value);abruptArgs[1]=record.value}}this.emit(b.returnStatement(b.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!hasOwn.call(record,"target")}if(type==="break"||type==="continue"){return!hasOwn.call(record,"value")&&n.Literal.check(record.target)}if(type==="return"||type==="throw"){return hasOwn.call(record,"value")&&!hasOwn.call(record,"target")}return false}Ep.getUnmarkedCurrentLoc=function(){return b.literal(this.listing.length)};Ep.updateContextPrevLoc=function(loc){if(loc){n.Literal.assert(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Ep.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){n.Expression.assert(expr)}else{return expr}var self=this;var result;function finish(expr){n.Expression.assert(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}switch(expr.type){case"MemberExpression":return finish(b.memberExpression(self.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed));case"CallExpression":var oldCalleePath=path.get("callee");var newCallee=self.explodeExpression(oldCalleePath);if(!n.MemberExpression.check(oldCalleePath.node)&&n.MemberExpression.check(newCallee)){newCallee=b.sequenceExpression([b.literal(0),newCallee])}return finish(b.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"NewExpression":return finish(b.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"ObjectExpression":return finish(b.objectExpression(path.get("properties").map(function(propPath){return b.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})));case"ArrayExpression":return finish(b.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})));case"SequenceExpression":var lastIndex=expr.expressions.length-1;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result;case"LogicalExpression":var after=loc();if(!ignoreResult){result=self.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));
if(expr.operator==="&&"){self.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");self.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);self.mark(after);return result;case"ConditionalExpression":var elseLoc=loc();var after=loc();var test=self.explodeExpression(path.get("test"));self.jumpIfNot(test,elseLoc);if(!ignoreResult){result=self.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);self.jump(after);self.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);self.mark(after);return result;case"UnaryExpression":return finish(b.unaryExpression(expr.operator,self.explodeExpression(path.get("argument")),!!expr.prefix));case"BinaryExpression":return finish(b.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))));case"AssignmentExpression":return finish(b.assignmentExpression(expr.operator,self.explodeExpression(path.get("left")),self.explodeExpression(path.get("right"))));case"UpdateExpression":return finish(b.updateExpression(expr.operator,self.explodeExpression(path.get("argument")),expr.prefix));case"YieldExpression":var after=loc();var arg=expr.argument&&self.explodeExpression(path.get("argument"));if(arg&&expr.delegate){var result=self.makeTempVar();self.emit(b.returnStatement(b.callExpression(self.contextProperty("delegateYield"),[arg,b.literal(result.property.name),after])));self.mark(after);return result}self.emitAssign(self.contextProperty("next"),after);self.emit(b.returnStatement(arg||null));self.mark(after);return self.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"./leap":294,"./meta":295,"./util":296,assert:139,"ast-types":137}],293:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);n.Function.assert(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){n.VariableDeclaration.assert(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(b.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return b.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return b.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(n.VariableDeclaration.check(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(n.VariableDeclaration.check(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var parentNode=path.parent.node;var assignment=b.expressionStatement(b.assignmentExpression("=",node.id,b.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(n.BlockStatement.check(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(path){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(n.Identifier.check(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!hasOwn.call(paramNames,name)){declarations.push(b.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return b.variableDeclaration("var",declarations)}},{assert:139,"ast-types":137}],294:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var inherits=require("util").inherits;var hasOwn=Object.prototype.hasOwnProperty;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);n.Literal.assert(returnLoc);this.returnLoc=returnLoc}inherits(FunctionEntry,Entry);exports.FunctionEntry=FunctionEntry;function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Literal.assert(continueLoc);if(label){n.Identifier.assert(label)}else{label=null}this.breakLoc=breakLoc;this.continueLoc=continueLoc;this.label=label}inherits(LoopEntry,Entry);exports.LoopEntry=LoopEntry;function SwitchEntry(breakLoc){Entry.call(this);n.Literal.assert(breakLoc);this.breakLoc=breakLoc}inherits(SwitchEntry,Entry);exports.SwitchEntry=SwitchEntry;function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);n.Literal.assert(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);this.firstLoc=firstLoc;this.catchEntry=catchEntry;this.finallyEntry=finallyEntry}inherits(TryEntry,Entry);exports.TryEntry=TryEntry;function CatchEntry(firstLoc,paramId){Entry.call(this);n.Literal.assert(firstLoc);n.Identifier.assert(paramId);this.firstLoc=firstLoc;this.paramId=paramId}inherits(CatchEntry,Entry);exports.CatchEntry=CatchEntry;function FinallyEntry(firstLoc,afterLoc){Entry.call(this);n.Literal.assert(firstLoc);n.Literal.assert(afterLoc);this.firstLoc=firstLoc;this.afterLoc=afterLoc}inherits(FinallyEntry,Entry);exports.FinallyEntry=FinallyEntry;function LabeledEntry(breakLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Identifier.assert(label);this.breakLoc=breakLoc;this.label=label}inherits(LabeledEntry,Entry);exports.LabeledEntry=LabeledEntry;function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);this.emitter=emitter;this.entryStack=[new FunctionEntry(emitter.finalLoc)]}var LMp=LeapManager.prototype;exports.LeapManager=LeapManager;LMp.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LMp._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else if(entry instanceof LabeledEntry){}else{return loc}}}return null};LMp.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LMp.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"./emit":292,assert:139,"ast-types":137,util:164}],295:[function(require,module,exports){var assert=require("assert");var m=require("private").makeAccessor();var types=require("ast-types");var isArray=types.builtInTypes.array;var n=types.namedTypes;var hasOwn=Object.prototype.hasOwnProperty;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.assert(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.assert(node);var meta=m(node);if(hasOwn.call(meta,propertyName))return meta[propertyName];if(hasOwn.call(opaqueTypes,node.type))return meta[propertyName]=false;if(hasOwn.call(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(hasOwn.call(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:139,"ast-types":137,"private":291}],296:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.defaults=function(obj){var len=arguments.length;var extension;for(var i=1;i<len;++i){if(extension=arguments[i]){for(var key in extension){if(hasOwn.call(extension,key)&&!hasOwn.call(obj,key)){obj[key]=extension[key]}}}}return obj};exports.runtimeProperty=function(name){return b.memberExpression(b.identifier("regeneratorRuntime"),b.identifier(name),false)};exports.isReference=function(path,name){var node=path.value;if(!n.Identifier.check(node)){return false}if(name&&node.name!==name){return false}var parent=path.parent.value;switch(parent.type){case"VariableDeclarator":return path.name==="init";case"MemberExpression":return path.name==="object"||parent.computed&&path.name==="property";case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":if(path.name==="id"){return false}if(parent.params===path.parentPath&&parent.params[path.name]===node){return false}return true;case"ClassDeclaration":case"ClassExpression":return path.name!=="id";case"CatchClause":return path.name!=="param";case"Property":case"MethodDefinition":return path.name!=="key";case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return false;default:return true}}},{assert:139,"ast-types":137}],297:[function(require,module,exports){var assert=require("assert");var fs=require("fs");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var NodePath=types.NodePath;var hoist=require("./hoist").hoist;var Emitter=require("./emit").Emitter;var runtimeProperty=require("./util").runtimeProperty;exports.transform=function transform(node,options){options=options||{};var path=node instanceof NodePath?node:new NodePath(node);visitor.visit(path,options);node=path.value;options.madeChanges=visitor.wasChangeReported();return node};var visitor=types.PathVisitor.fromMethodsObject({reset:function(node,options){this.options=options},visitFunction:function(path){this.traverse(path);var node=path.value;var shouldTransformAsync=node.async&&!this.options.disableAsync;if(!node.generator&&!shouldTransformAsync){return}this.reportChanged();node.generator=false;if(node.expression){node.expression=false;node.body=b.blockStatement([b.returnStatement(node.body)])}if(shouldTransformAsync){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=path.scope.parent.declareTemporary("callee$"));var outerBody=[];var bodyBlock=path.value.body;bodyBlock.body=bodyBlock.body.filter(function(node){if(node&&node._blockHoist!=null){outerBody.push(node);return false}else{return true}});var innerFnId=b.identifier(node.id.name+"$");var contextId=path.scope.declareTemporary("context$");var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),shouldTransformAsync?b.literal(null):outerFnId,b.thisExpression()];var tryLocsList=emitter.getTryLocsList();if(tryLocsList){wrapArgs.push(tryLocsList)}var wrapCall=b.callExpression(shouldTransformAsync?runtimeProperty("async"):runtimeProperty("wrap"),wrapArgs);outerBody.push(b.returnStatement(wrapCall));node.body=b.blockStatement(outerBody);if(shouldTransformAsync){node.async=false;return}if(n.FunctionDeclaration.check(node)){var pp=path.parent;while(pp&&!(n.BlockStatement.check(pp.value)||n.Program.check(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=b.variableDeclaration("var",[b.variableDeclarator(node.id,b.callExpression(runtimeProperty("mark"),[node]))]);if(node.comments){varDecl.leadingComments=node.leadingComments;varDecl.trailingComments=node.trailingComments;node.leadingComments=null;node.trailingComments=null}varDecl._blockHoist=3;var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;bodyPath.push(varDecl)}else{n.FunctionExpression.assert(node);return b.callExpression(runtimeProperty("mark"),[node])}}});function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;n.Statement.assert(value);if(n.ExpressionStatement.check(value)&&n.Literal.check(value.expression)&&value.expression.value==="use strict"){return true}if(n.VariableDeclaration.check(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(n.CallExpression.check(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeProperty("mark"))){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){return false},visitAwaitExpression:function(path){var argument=path.value.argument;if(path.value.all){argument=b.callExpression(b.memberExpression(b.identifier("Promise"),b.identifier("all"),false),[argument])}return b.yieldExpression(argument,false)}})},{"./emit":292,"./hoist":293,"./util":296,assert:139,"ast-types":137,fs:138}],298:[function(require,module,exports){(function(__dirname){var assert=require("assert");var path=require("path");var fs=require("fs");var through=require("through");var transform=require("./lib/visit").transform;var utils=require("./lib/util");var types=require("ast-types");var genOrAsyncFunExp=/\bfunction\s*\*|\basync\b/;var blockBindingExp=/\b(let|const)\s+/;function exports(file,options){var data=[];return through(write,end);function write(buf){data.push(buf)}function end(){this.queue(compile(data.join(""),options).code);this.queue(null)}}module.exports=exports;function runtime(){require("./runtime")}exports.runtime=runtime;runtime.path=path.join(__dirname,"runtime.js");exports.transform=transform}).call(this,"/node_modules/regenerator-6to5")},{"./lib/util":296,"./lib/visit":297,"./runtime":300,assert:139,"ast-types":137,fs:138,path:147,through:299}],299:[function(require,module,exports){(function(process){var Stream=require("stream");exports=module.exports=through;through.through=through;function through(write,end,opts){write=write||function(data){this.queue(data)};end=end||function(){this.queue(null)};var ended=false,destroyed=false,buffer=[],_ended=false;var stream=new Stream;stream.readable=stream.writable=true;stream.paused=false;stream.autoDestroy=!(opts&&opts.autoDestroy===false);stream.write=function(data){write.call(this,data);return!stream.paused};function drain(){while(buffer.length&&!stream.paused){var data=buffer.shift();if(null===data)return stream.emit("end");else stream.emit("data",data)}}stream.queue=stream.push=function(data){if(_ended)return stream;if(data==null)_ended=true;buffer.push(data);drain();return stream};stream.on("end",function(){stream.readable=false;if(!stream.writable&&stream.autoDestroy)process.nextTick(function(){stream.destroy()})});function _end(){stream.writable=false;end.call(stream);if(!stream.readable&&stream.autoDestroy)stream.destroy()}stream.end=function(data){if(ended)return;ended=true;if(arguments.length)stream.write(data);_end();return stream};stream.destroy=function(){if(destroyed)return;destroyed=true;ended=true;buffer.length=0;stream.writable=stream.readable=false;stream.emit("close");return stream};stream.pause=function(){if(stream.paused)return;stream.paused=true;return stream};stream.resume=function(){if(stream.paused){stream.paused=false;stream.emit("resume")}drain();if(!stream.paused)stream.emit("drain");return stream};return stream}}).call(this,require("_process"))},{_process:148,stream:160}],300:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryLocsList){return new Generator(innerFn,outerFn,self||null,tryLocsList||[])}runtime.wrap=wrap;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";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryLocsList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryLocsList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryLocsList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryLocsList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}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){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}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{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},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;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"){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")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},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=record.arg;this.next="end"}else if(record.type==="normal"&&afterLoc){this.next=afterLoc}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion,entry.afterLoc)},"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}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],301:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:303}],302:[function(require,module,exports){module.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],303:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2
}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end)}index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var length=data.length;var start=data[index];var end=data[length-1];if(length>=2){if(codePoint<start||codePoint>end){return false}}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var loneLowSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<HIGH_SURROGATE_MIN){if(end<HIGH_SURROGATE_MIN){bmp.push(start,end+1)}if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,end+1)}if(end>LOW_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,end+1)}if(end>LOW_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>=LOW_SURROGATE_MIN&&start<=LOW_SURROGATE_MAX){if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){loneLowSurrogates.push(start,end+1)}if(end>LOW_SURROGATE_MAX){loneLowSurrogates.push(start,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>LOW_SURROGATE_MAX&&start<=65535){if(end<=65535){bmp.push(start,end+1)}else{bmp.push(start,65535+1);astral.push(65535+1,end+1)}}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,loneLowSurrogates:loneLowSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0];lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data,bmpOnly){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var loneLowSurrogates=parts.loneLowSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneHighSurrogates=!dataIsEmpty(loneHighSurrogates);var hasLoneLowSurrogates=!dataIsEmpty(loneLowSurrogates);var surrogateMappings=surrogateSet(astral);if(bmpOnly){bmp=dataAddData(bmp,loneHighSurrogates);hasLoneHighSurrogates=false;bmp=dataAddData(bmp,loneLowSurrogates);hasLoneLowSurrogates=false}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasLoneHighSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates)+"(?![\\uDC00-\\uDFFF])")}if(hasLoneLowSurrogates){result.push("(?:[^\\uD800-\\uDBFF]|^)"+createBMPCharacterClasses(loneLowSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.2.0";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint))},clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(options){var result=createCharacterClassesFromData(this.data,options?options.bmpOnly:false);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],304:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass");var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],305:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]})}function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1;var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&¤t("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="";var ZWNJ="";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges();skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],306:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);
regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":301,"./data/iu-mappings.json":302,regenerate:303,regjsgen:304,regjsparser:305}],307:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":313,"./source-map/source-map-generator":314,"./source-map/source-node":315}],308:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var isDuplicate=this.has(aStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){this._set[util.toSetString(aStr)]=idx}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(aStr))};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(this.has(aStr)){return this._set[util.toSetString(aStr)]}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":316,amdefine:317}],309:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){var i=0;var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(i>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charAt(i++));continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":310,amdefine:317}],310:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:317}],311:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return mid}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return mid}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?-1:aLow}}exports.search=function search(aNeedle,aHaystack,aCompare){if(aHaystack.length===0){return-1}return recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare)}})},{amdefine:317}],312:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function generatedPositionAfter(mappingA,mappingB){var lineA=mappingA.generatedLine;var lineB=mappingB.generatedLine;var columnA=mappingA.generatedColumn;var columnB=mappingB.generatedColumn;return lineB>lineA||lineB==lineA&&columnB>=columnA||util.compareByGeneratedPositions(mappingA,mappingB)<=0}function MappingList(){this._array=[];this._sorted=true;this._last={generatedLine:-1,generatedColumn:0}}MappingList.prototype.unsortedForEach=function MappingList_forEach(aCallback,aThisArg){this._array.forEach(aCallback,aThisArg)};MappingList.prototype.add=function MappingList_add(aMapping){var mapping;if(generatedPositionAfter(this._last,aMapping)){this._last=aMapping;this._array.push(aMapping)}else{this._sorted=false;this._array.push(aMapping)}};MappingList.prototype.toArray=function MappingList_toArray(){if(!this._sorted){this._array.sort(util.compareByGeneratedPositions);this._sorted=true}return this._array};exports.MappingList=MappingList})},{"./util":316,amdefine:317}],313:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}sources=sources.map(util.normalize);this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}SourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(SourceMapConsumer.prototype);smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;smc.__generatedMappings=aSourceMap._mappings.toArray().slice();smc.__originalMappings=aSourceMap._mappings.toArray().slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var str=aStr;var temp={};var mapping;while(str.length>0){if(str.charAt(0)===";"){generatedLine++;str=str.slice(1);previousGeneratedColumn=0}else if(str.charAt(0)===","){str=str.slice(1)}else{mapping={};mapping.generatedLine=generatedLine;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.name=this._names.at(previousName+temp.value);previousName+=temp.value;str=temp.rest}}this.__generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){this.__originalMappings.push(mapping)}}}this.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator)};SourceMapConsumer.prototype.computeColumnSpans=function SourceMapConsumer_computeColumnSpans(){for(var index=0;index<this._generatedMappings.length;++index){var mapping=this._generatedMappings[index];if(index+1<this._generatedMappings.length){var nextMapping=this._generatedMappings[index+1];if(mapping.generatedLine===nextMapping.generatedLine){mapping.lastGeneratedColumn=nextMapping.generatedColumn-1;continue}}mapping.lastGeneratedColumn=Infinity}};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var index=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(index>=0){var mapping=this._generatedMappings[index];if(mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:util.getArg(mapping,"name",null)}}}return{source:null,line:null,column:null,name:null}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}throw new Error('"'+aSource+'" is not in the SourceMap.')};SourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(index>=0){var mapping=this._originalMappings[index];return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};SourceMapConsumer.prototype.allGeneratedPositionsFor=function SourceMapConsumer_allGeneratedPositionsFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:Infinity};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mappings=[];var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(index>=0){var mapping=this._originalMappings[index];while(mapping&&mapping.originalLine===needle.originalLine){mappings.push({line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)});mapping=this._originalMappings[--index]}}return mappings.reverse()};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source;if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name}}).forEach(aCallback,context)};exports.SourceMapConsumer=SourceMapConsumer})},{"./array-set":308,"./base64-vlq":309,"./binary-search":311,"./util":316,amdefine:317}],314:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;var MappingList=require("./mapping-list").MappingList;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._skipValidation=util.getArg(aArgs,"skipValidation",false);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=new MappingList;this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);if(!this._skipValidation){this._validateMapping(generated,original,source,name)}if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.add({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.unsortedForEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var mapping;var mappings=this._mappings.toArray();for(var i=0,len=mappings.length;i<len;i++){mapping=mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){result+=base64VLQ.encode(this._names.indexOf(mapping.name)-previousName);previousName=this._names.indexOf(mapping.name)}}}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":308,"./base64-vlq":309,"./mapping-list":312,"./util":316,amdefine:317}],315:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var NEWLINE_CODE=10;var isSourceNode="$$$isSourceNode$$$";function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;this[isSourceNode]=true;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[0];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[0]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[0];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[0]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk[isSourceNode]||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk[isSourceNode]||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk[isSourceNode]){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild[isSourceNode]){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i][isSourceNode]){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}for(var idx=0,length=chunk.length;idx<length;idx++){if(chunk.charCodeAt(idx)===NEWLINE_CODE){generated.line++;generated.column=0;if(idx+1===length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column++}}});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":314,"./util":316,amdefine:317}],316:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;
function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var url=urlParse(aRoot);if(aPath.charAt(0)=="/"&&url&&url.path=="/"){return aPath.slice(1)}return aPath.indexOf(aRoot+"/")===0?aPath.substr(aRoot.length+1):aPath}exports.relative=relative;function toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp;cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp||onlyCompareOriginal){return cmp}cmp=strcmp(mappingA.name,mappingB.name);if(cmp){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}return mappingA.generatedColumn-mappingB.generatedColumn}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositions(mappingA,mappingB,onlyCompareGenerated){var cmp;cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp||onlyCompareGenerated){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositions=compareByGeneratedPositions})},{amdefine:317}],317:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part===".."){if(i===1&&(ary[2]===".."||ary[0]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){throw new Error("amdefine does not implement load.fromText")};return load}makeRequire=function(systemRequire,exports,module,relId){function amdRequire(deps,callback){if(typeof deps==="string"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});process.nextTick(function(){callback.apply(null,deps)})}}amdRequire.toUrl=function(filePath){if(filePath.indexOf(".")===0){return normalize(filePath,path.dirname(module.filename))}else{return filePath}};return amdRequire};requireFn=requireFn||function req(){return module.require.apply(module,arguments)};function runFactory(id,deps,factory){var r,e,m,result;if(id){e=loaderCache[id]={};m={id:id,uri:__filename,exports:e};r=makeRequire(requireFn,e,m,id)}else{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}if(typeof factory==="function"){result=factory.apply(m.exports,deps)}else{result=factory}if(result!==undefined){m.exports=result;if(id){loaderCache[id]=m.exports}}}stringRequire=function(systemRequire,exports,module,id,relId){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);if(id==="require"){return makeRequire(systemRequire,exports,module,relId)}else if(id==="exports"){return exports}else if(id==="module"){return module}else if(loaderCache.hasOwnProperty(id)){return loaderCache[id]}else if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}else{if(systemRequire){return systemRequire(originalId)}else{throw new Error("No module with ID: "+id)}}}else{prefix=id.substring(0,index);id=id.substring(index+1,id.length);plugin=stringRequire(systemRequire,exports,module,prefix,relId);if(plugin.normalize){id=plugin.normalize(id,makeNormalize(relId))}else{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};function define(id,deps,factory){if(Array.isArray(id)){factory=deps;deps=id;id=undefined}else if(typeof id!=="string"){factory=id;id=deps=undefined}if(deps&&!Array.isArray(deps)){factory=deps;deps=undefined}if(!deps){deps=["require","exports","module"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}define.require=function(id){if(loaderCache[id]){return loaderCache[id]}if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}};define.amd={};return define}module.exports=amdefine}).call(this,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:148,path:147}],318:[function(require,module,exports){(function(process){"use strict";var argv=process.argv;module.exports=function(){if(argv.indexOf("--no-color")!==-1||argv.indexOf("--no-colors")!==-1||argv.indexOf("--color=false")!==-1){return false}if(argv.indexOf("--color")!==-1||argv.indexOf("--colors")!==-1||argv.indexOf("--color=true")!==-1||argv.indexOf("--color=always")!==-1){return true}if(process.stdout&&!process.stdout.isTTY){return false}if(process.platform==="win32"){return true}if("COLORTERM"in process.env){return true}if(process.env.TERM==="dumb"){return false}if(/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)){return true}return false}()}).call(this,require("_process"))},{_process:148}],319:[function(require,module,exports){module.exports={name:"6to5",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"3.6.5",author:"Sebastian McKenzie <[email protected]>",homepage:"https://6to5.org/",repository:"6to5/6to5",preferGlobal:true,main:"lib/6to5/api/node.js",browser:{"./lib/6to5/api/register/node.js":"./lib/6to5/api/register/browser.js"},bin:{"6to5":"./bin/6to5/index.js","6to5-minify":"./bin/6to5-minify","6to5-node":"./bin/6to5-node","6to5-runtime":"./bin/6to5-runtime"},keywords:["harmony","classes","modules","let","const","var","es6","transpile","transpiler","6to5"],scripts:{bench:"make bench",test:"make test"},dependencies:{"acorn-6to5":"0.11.1-31","ast-types":"~0.6.1",chalk:"^0.5.1",chokidar:"0.12.6",commander:"2.6.0","core-js":"^0.5.3",debug:"^2.1.1","detect-indent":"3.0.0",estraverse:"1.9.1",esutils:"1.1.6","fs-readdir-recursive":"0.1.0",globals:"^5.1.0","js-tokenizer":"1.3.3",lodash:"3.0.0","output-file-sync":"1.1.0","private":"0.1.6","regenerator-6to5":"0.8.10-1",regexpu:"1.1.0",roadrunner:"1.0.4","source-map":"0.1.43","source-map-support":"0.2.9","supports-color":"1.2.0",useragent:"^2.1.5"},devDependencies:{"6to5":"3.6.0",browserify:"8.1.1",chai:"1.10.0",esvalid:"1.1.0",istanbul:"0.3.5",jscs:"1.10.0",jshint:"2.6.0","jshint-stylish":"1.0.0",matcha:"0.6.0",mocha:"2.1.0",rimraf:"2.2.8","uglify-js":"2.4.16"}}},{}],320:[function(require,module,exports){module.exports={"abstract-expression-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-delete":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceDelete",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-get":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-set":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceSet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"apply-constructor":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-comprehension-container":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-from":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-push":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STATEMENT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"async-to-generator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"next",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"throw",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionDeclaration",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"TryStatement",start:null,end:null,loc:null,range:null,block:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},handler:{type:"CatchClause",start:null,end:null,loc:null,range:null,param:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},guard:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},guardedHandlers:[],finalizer:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"then",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},bind:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Function",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},call:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CONTEXT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-call-check":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"instanceof",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:"Cannot call a class as a function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"corejs-is-iterator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CORE_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"$for",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isIterable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"corejs-iterator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CORE_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"$for",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getIterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"default-parameter":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"DEFAULT_VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"let",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},defaults:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyNames",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"define-property":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-default-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-module-declaration":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"__esModule",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"extends":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"assign",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:1,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:null,update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},get:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"has-own":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},inherits:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"Super expression must either be null or a function, not ",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"+",right:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:false,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__proto__",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require-wildcard":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"let-scoping-return":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"v",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"object-destructuring-empty":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:"Cannot destructure undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"object-without-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"indexOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"property-method-assignment-wrapper-generator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:true,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"YieldExpression",start:null,end:null,loc:null,range:null,delegate:true,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"property-method-assignment-wrapper":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-identifier":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"require-assign-key":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},require:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},rest:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"START",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"self-contained-helpers-head":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"helpers",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"self-global":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"self",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},set:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},slice:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"slice",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"sliced-to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"in",right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:"Invalid attempt to destructure non-iterable instance",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},system:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"System",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"register",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_DEPENDENCIES",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXPORT_IDENTIFIER",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setters",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SETTERS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"execute",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXECUTE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tail-call-body":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"LabeledStatement",start:null,end:null,loc:null,range:null,body:{type:"WhileStatement",start:null,end:null,loc:null,range:null,test:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},body:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"BLOCK",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},label:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tail-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"FunctionDeclaration",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Tail",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"func",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"context",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"func",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"func",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"context",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"context",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Tail",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_isTailDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isRunning",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:false,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"func",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"context",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Tail",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"func",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"context",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isRunning",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isRunning",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"DoWhileStatement",start:null,end:null,loc:null,range:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"func",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"context",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"instanceof",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Tail",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_isTailDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isRunning",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:false,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"temporal-assert-defined":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"val",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"name",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undef",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"val",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undef",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ReferenceError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"name",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"+",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:" is not defined - temporal dead zone",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"temporal-undefined":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-exports":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-module":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"to-consumable-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr2",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr2",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr2",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"typeof":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Literal",start:null,end:null,loc:null,range:null,value:"symbol",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},alternate:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"umd-runner-body":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"amd",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"AMD_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_TEST",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}}
},{}]},{},[2])(2)}); |
app/javascript/mastodon/features/direct_timeline/components/conversations_list.js | musashino205/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ConversationContainer from '../containers/conversation_container';
import ScrollableList from '../../../components/scrollable_list';
import { debounce } from 'lodash';
export default class ConversationsList extends ImmutablePureComponent {
static propTypes = {
conversations: ImmutablePropTypes.list.isRequired,
scrollKey: PropTypes.string.isRequired,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
onLoadMore: PropTypes.func,
};
getCurrentIndex = id => this.props.conversations.findIndex(x => x.get('id') === id)
handleMoveUp = id => {
const elementIndex = this.getCurrentIndex(id) - 1;
this._selectChild(elementIndex, true);
}
handleMoveDown = id => {
const elementIndex = this.getCurrentIndex(id) + 1;
this._selectChild(elementIndex, false);
}
_selectChild (index, align_top) {
const container = this.node.node;
const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`);
if (element) {
if (align_top && container.scrollTop > element.offsetTop) {
element.scrollIntoView(true);
} else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) {
element.scrollIntoView(false);
}
element.focus();
}
}
setRef = c => {
this.node = c;
}
handleLoadOlder = debounce(() => {
const last = this.props.conversations.last();
if (last && last.get('last_status')) {
this.props.onLoadMore(last.get('last_status'));
}
}, 300, { leading: true })
render () {
const { conversations, onLoadMore, ...other } = this.props;
return (
<ScrollableList {...other} onLoadMore={onLoadMore && this.handleLoadOlder} ref={this.setRef}>
{conversations.map(item => (
<ConversationContainer
key={item.get('id')}
conversationId={item.get('id')}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
scrollKey={this.props.scrollKey}
/>
))}
</ScrollableList>
);
}
}
|
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/Divider/ExampleList.js | pbogdan/react-flux-mui | import React from 'react';
import Divider from 'material-ui/Divider';
import {List, ListItem} from 'material-ui/List';
import MobileTearSheet from '../../../MobileTearSheet';
const DividerExampleList = () => (
<MobileTearSheet height={250}>
<List>
<ListItem insetChildren={true} primaryText="Janet Perkins Bennet" />
<ListItem insetChildren={true} primaryText="Peter Carlsson" />
</List>
<Divider inset={true} />
<List>
<ListItem insetChildren={true} primaryText="Aaron Bennet" />
<ListItem insetChildren={true} primaryText="Abbey Christensen" />
</List>
</MobileTearSheet>
);
export default DividerExampleList;
|
ajax/libs/react-native-web/0.0.0-4fd133e73/exports/Touchable/Position.min.js | cdnjs/cdnjs | import PooledClass from"../../vendor/react-native/PooledClass";var twoArgumentPooler=PooledClass.twoArgumentPooler;function Position(o,t){this.left=o,this.top=t}Position.prototype.destructor=function(){this.left=null,this.top=null},PooledClass.addPoolingTo(Position,twoArgumentPooler);export default Position; |
src/components/MobileNavigation.js | ICalvinG/icalving.github.io | import React from 'react';
import { NavLink } from 'react-router-dom';
const MobileNavigation = () => (
<nav className='mobile-navigation__wrapper'>
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/resume">Resume</NavLink>
<NavLink to="/skills">Skills</NavLink>
<NavLink to="/projects">Projects</NavLink>
</nav>
);
export default MobileNavigation;
|
test/rehearseTemplate-test.js | cashsun/rehearse | import React from 'react';
import _ from 'lodash';
import 'react-addons-test-utils';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import path from 'path';
import fs from 'fs';
const rehearseTemplate = require('../rehearseTemplates');
const componentFinder = require('../componentsFinder');
const testOutput = path.join(__dirname, 'rehearse-viewer.js');
import componentA from './sample/aComponent';
import component2 from './sample/common/component2';
const sampleComponents = componentFinder.find(path.join(__dirname, 'sample'));
const keys = _.reduce(sampleComponents, (memo, compInfo, key)=>{
memo[compInfo.displayName] = key;
return memo;
}, {});
import testProps from './sample/props';
const propsFile = path.join(__dirname, 'sample/props.js');
describe('rehearse viewer', ()=> {
beforeEach(()=> {
rehearseTemplate.buildViewerPage(testOutput, sampleComponents, propsFile)
});
afterEach(()=> {
window.target = '';
window.scenario = '';
window.isFrame = false;
delete require.cache[testOutput];
fs.unlinkSync(testOutput);
});
it('renders list of available components when no target component selected', () => {
const Viewer = require(testOutput).default;
const viewerProps = require(testOutput).viewerProps;
const wrapper = shallow(<Viewer {...viewerProps}/>);
console.log(wrapper.text());
expect(wrapper.find('a')).to.have.lengthOf(4);
expect(wrapper.find('a').at(0).prop('href')).to.equal('/view/'+keys['aComponent']);
expect(wrapper.find('a').at(0).text()).to.equal('aComponent');
expect(wrapper.find('a').at(1).prop('href')).to.equal('/view/'+keys['PureComponent']);
expect(wrapper.find('a').at(1).text()).to.equal('PureComponent');
expect(wrapper.find('a').at(2).prop('href')).to.equal('/view/'+keys['component-3']);
expect(wrapper.find('a').at(2).text()).to.equal('component-3');
expect(wrapper.find('a').at(3).prop('href')).to.equal('/view/'+keys['component2']);
expect(wrapper.find('a').at(3).text()).to.equal('component2');
});
it('renders error and list of available components when no target props found', () => {
window.target = keys['component-3'];
const Viewer = require(testOutput).default;
const viewerProps = require(testOutput).viewerProps;
const wrapper = shallow(<Viewer {...viewerProps}/>);
expect(wrapper.text()).contains('Error: you have not given props ' +
'for the component component-3 in your props file');
expect(wrapper.find('a')).to.have.lengthOf(4);
expect(wrapper.find('a').at(0).prop('href')).matches(/\/view\/.*/);
expect(wrapper.find('a').at(0).text()).to.equal('aComponent');
expect(wrapper.find('a').at(1).prop('href')).matches(/\/view\/.*/);
expect(wrapper.find('a').at(1).text()).to.equal('PureComponent');
expect(wrapper.find('a').at(2).prop('href')).matches(/\/view\/.*/);
expect(wrapper.find('a').at(2).text()).to.equal('component-3');
expect(wrapper.find('a').at(3).prop('href')).matches(/\/view\/.*/);
expect(wrapper.find('a').at(3).text()).to.equal('component2');
});
it('renders error and list of available components when no target scenario found', () => {
window.target = keys['aComponent'];
window.scenario = 'does-not-exist';
const Viewer = require(testOutput).default;
const viewerProps = require(testOutput).viewerProps;
const wrapper = shallow(<Viewer {...viewerProps}/>);
expect(wrapper.text()).contains('Error: you have not given props for the component aComponent' +
' in your props file');
expect(wrapper.find('a').at(0).prop('href')).matches(/\/view\/.*/);
expect(wrapper.find('a').at(0).text()).to.equal('aComponent');
expect(wrapper.find('a').at(1).prop('href')).matches(/\/view\/.*/);
expect(wrapper.find('a').at(1).text()).to.equal('PureComponent');
expect(wrapper.find('a').at(2).prop('href')).matches(/\/view\/.*/);
expect(wrapper.find('a').at(2).text()).to.equal('component-3');
expect(wrapper.find('a').at(3).prop('href')).matches(/\/view\/.*/);
expect(wrapper.find('a').at(3).text()).to.equal('component2');
});
it('renders aComponent when selected and shows scenarios', () => {
window.target = keys['aComponent'];
window.isFrame = true;
const Viewer = require(testOutput).default;
const viewerProps = require(testOutput).viewerProps;
const wrapper = shallow(<Viewer {...viewerProps}/>);
console.log(wrapper.text());
expect(wrapper.find(componentA)).to.have.lengthOf(1);
expect(wrapper.find(componentA).props()).to.deep.equal(testProps.aComponent);
});
it('renders aComponent when selected with scenario and shows scenarios', () => {
window.target = keys['aComponent'];
window.scenario = 's1';
const Viewer = require(testOutput).default;
const viewerProps = require(testOutput).viewerProps;
const wrapper = shallow(<Viewer {...viewerProps}/>);
expect(wrapper.find('a').at(0).text()).to.equal('aComponent (default)');
expect(wrapper.find('a').at(1).text()).to.equal('aComponent (s1)');
});
it('renders component2 when selected', () => {
window.target = keys['component2'];
window.isFrame = true;
const Viewer = require(testOutput).default;
const viewerProps = require(testOutput).viewerProps;
const wrapper = shallow(<Viewer {...viewerProps}/>);
expect(wrapper.find(component2)).to.have.lengthOf(1);
expect(wrapper.find(component2).props()).to.deep.equal(testProps.component2);
});
}); |
ajax/libs/jquery-localScroll/1.2.9/jquery.localScroll.js | calvinf/cdnjs | /*!
* jQuery.LocalScroll
* Copyright (c) 2007-2013 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html
* @author Ariel Flesler
* @version 1.2.9
*/
;(function( $ ){
var URI = location.href.replace(/#.*/,''); // local url without hash
var $localScroll = $.localScroll = function( settings ){
$('body').localScroll( settings );
};
// Many of these defaults, belong to jQuery.ScrollTo, check it's demo for an example of each option.
// @see http://flesler.demos.com/jquery/scrollTo/
// The defaults are public and can be overriden.
$localScroll.defaults = {
duration:1000, // How long to animate.
axis:'y', // Which of top and left should be modified.
event:'click', // On which event to react.
stop:true, // Avoid queuing animations
target: window // What to scroll (selector or element). The whole window by default.
/*
lock:false, // ignore events if already animating
lazy:false, // if true, links can be added later, and will still work.
filter:null, // filter some anchors out of the matched elements.
hash: false // if true, the hash of the selected link, will appear on the address bar.
*/
};
$.fn.localScroll = function( settings ){
settings = $.extend( {}, $localScroll.defaults, settings );
if (settings.hash && location.hash) {
if (settings.target) window.scrollTo(0, 0);
scroll(0, location, settings);
}
return settings.lazy ?
// use event delegation, more links can be added later.
this.bind( settings.event, function( e ){
// Could use closest(), but that would leave out jQuery -1.3.x
var a = $([e.target, e.target.parentNode]).filter(filter)[0];
// if a valid link was clicked
if( a )
scroll( e, a, settings ); // do scroll.
}) :
// bind concretely, to each matching link
this.find('a,area')
.filter( filter ).bind( settings.event, function(e){
scroll( e, this, settings );
}).end()
.end();
function filter(){// is this a link that points to an anchor and passes a possible filter ? href is checked to avoid a bug in FF.
return !!this.href && !!this.hash && this.href.replace(this.hash,'') == URI && (!settings.filter || $(this).is( settings.filter ));
};
};
// Not needed anymore, kept for backwards compatibility
$localScroll.hash = function() {}
function scroll( e, link, settings ){
var id = link.hash.slice(1),
elem = document.getElementById(id) || document.getElementsByName(id)[0];
if ( !elem )
return;
if( e )
e.preventDefault();
var $target = $( settings.target );
if( settings.lock && $target.is(':animated') ||
settings.onBefore && settings.onBefore(e, elem, $target) === false )
return;
if( settings.stop )
$target._scrollable().stop(true); // remove all its animations
if( settings.hash ) {
var offset = settings.offset;
offset = offset && offset.top || offset || 0;
var attr = elem.id == id ? 'id' : 'name',
$a = $('<a> </a>').attr(attr, id).css({
position:'absolute',
top: $(window).scrollTop() + offset,
left: $(window).scrollLeft()
});
elem[attr] = '';
$('body').prepend($a);
location = link.hash;
$a.remove();
elem[attr] = id;
}
$target
.scrollTo( elem, settings ) // do scroll
.trigger('notify.serialScroll',[elem]); // notify serialScroll about this change
};
})( jQuery ); |
integration_tests/babel-plugin-jest-hoist/__tests__/integration-test.js | blainekasten/jest | /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+jsinfra
*/
/* eslint-disable no-useless-concat */
'use strict';
import React from 'react';
import Unmocked from '../__test_modules__/Unmocked';
import Mocked from '../__test_modules__/Mocked';
import a from '../__test_modules__/a';
import b from '../__test_modules__/b';
import c from '../__test_modules__/c';
import d from '../__test_modules__/d';
import e from '../__test_modules__/e';
// These will all be hoisted above imports
jest.unmock('react');
jest.deepUnmock('../__test_modules__/Unmocked');
jest
.unmock('../__test_modules__/c')
.unmock('../__test_modules__/d');
jest.mock('../__test_modules__/e', () => {
if (!global.CALLS) {
global.CALLS = 0;
}
global.CALLS++;
return {
_isMock: true,
fn: () => {
// The `jest.mock` transform will allow require, built-ins and globals.
const path = require('path');
const array = new Array(3);
array[0] = path.sep;
return jest.fn(() => array);
},
};
});
// These will not be hoisted
jest.unmock('../__test_modules__/a').dontMock('../__test_modules__/b');
jest.unmock('../__test_modules__/' + 'c');
jest.dontMock('../__test_modules__/Mocked');
// This must not throw an error
const myObject = {mock: () => {}};
myObject.mock('apple', 27);
describe('babel-plugin-jest-hoist', () => {
it('does not throw during transform', () => {
const object = {};
object.__defineGetter__('foo', () => 'bar');
expect(object.foo).toEqual('bar');
});
it('hoists react unmock call before imports', () => {
expect(typeof React).toEqual('object');
expect(React.isValidElement.mock).toBe(undefined);
});
it('hoists unmocked modules before imports', () => {
expect(Unmocked._isMockFunction).toBe(undefined);
expect((new Unmocked()).isUnmocked).toEqual(true);
expect(c._isMockFunction).toBe(undefined);
expect(c()).toEqual('unmocked');
expect(d._isMockFunction).toBe(undefined);
expect(d()).toEqual('unmocked');
});
it('hoists mock call with 2 arguments', () => {
const path = require('path');
expect(e._isMock).toBe(true);
const mockFn = e.fn();
expect(mockFn()).toEqual([path.sep, undefined, undefined]);
});
it('only executes the module factories once', () => {
jest.resetModules();
global.CALLS = 0;
require('../__test_modules__/e');
expect(global.CALLS).toEqual(1);
require('../__test_modules__/e');
expect(global.CALLS).toEqual(1);
delete global.CALLS;
});
it('does not hoist dontMock calls before imports', () => {
expect(Mocked._isMockFunction).toBe(true);
expect((new Mocked()).isMocked).toEqual(undefined);
expect(a._isMockFunction).toBe(true);
expect(a()).toEqual(undefined);
expect(b._isMockFunction).toBe(true);
expect(b()).toEqual(undefined);
});
it('requires modules that also call jest.mock', () => {
require('../mock-file');
const mock = require('../banana');
expect(mock).toEqual('apple');
});
});
|
client/modules/User/components/Item/Item.js | b3j0f/lechangement | import './Item.css';
import React, { Component } from 'react';
class Item extends Component {
render() {
return (
<div className="user-item">
</div>
);
}
}
Item.propTypes = {
}
export default Item;
|
react/features/calendar-sync/components/CalendarList.web.js | bgrozev/jitsi-meet | // @flow
import Spinner from '@atlaskit/spinner';
import React from 'react';
import { translate } from '../../base/i18n';
import { AbstractPage } from '../../base/react';
import { connect } from '../../base/redux';
import { openSettingsDialog, SETTINGS_TABS } from '../../settings';
import {
createCalendarClickedEvent,
sendAnalytics
} from '../../analytics';
import { refreshCalendar } from '../actions';
import { ERRORS } from '../constants';
import CalendarListContent from './CalendarListContent';
declare var interfaceConfig: Object;
/**
* The type of the React {@code Component} props of {@link CalendarList}.
*/
type Props = {
/**
* The error object containing details about any error that has occurred
* while interacting with calendar integration.
*/
_calendarError: ?Object,
/**
* Whether or not a calendar may be connected for fetching calendar events.
*/
_hasIntegrationSelected: boolean,
/**
* Whether or not events have been fetched from a calendar.
*/
_hasLoadedEvents: boolean,
/**
* Indicates if the list is disabled or not.
*/
disabled: boolean,
/**
* The Redux dispatch function.
*/
dispatch: Function,
/**
* The translate function.
*/
t: Function
};
/**
* Component to display a list of events from the user's calendar.
*/
class CalendarList extends AbstractPage<Props> {
/**
* Initializes a new {@code CalendarList} instance.
*
* @inheritdoc
*/
constructor(props) {
super(props);
// Bind event handlers so they are only bound once per instance.
this._getRenderListEmptyComponent
= this._getRenderListEmptyComponent.bind(this);
this._onOpenSettings = this._onOpenSettings.bind(this);
this._onRefreshEvents = this._onRefreshEvents.bind(this);
}
/**
* Implements React's {@link Component#render}.
*
* @inheritdoc
*/
render() {
const { disabled } = this.props;
return (
CalendarListContent
? <CalendarListContent
disabled = { disabled }
listEmptyComponent
= { this._getRenderListEmptyComponent() } />
: null
);
}
/**
* Returns a component for showing the error message related to calendar
* sync.
*
* @private
* @returns {React$Component}
*/
_getErrorMessage() {
const { _calendarError = {}, t } = this.props;
let errorMessageKey = 'calendarSync.error.generic';
let showRefreshButton = true;
let showSettingsButton = true;
if (_calendarError.error === ERRORS.GOOGLE_APP_MISCONFIGURED) {
errorMessageKey = 'calendarSync.error.appConfiguration';
showRefreshButton = false;
showSettingsButton = false;
} else if (_calendarError.error === ERRORS.AUTH_FAILED) {
errorMessageKey = 'calendarSync.error.notSignedIn';
showRefreshButton = false;
}
return (
<div className = 'meetings-list-empty'>
<p className = 'description'>
{ t(errorMessageKey) }
</p>
<div className = 'calendar-action-buttons'>
{ showSettingsButton
&& <div
className = 'button'
onClick = { this._onOpenSettings }>
{ t('calendarSync.permissionButton') }
</div>
}
{ showRefreshButton
&& <div
className = 'button'
onClick = { this._onRefreshEvents }>
{ t('calendarSync.refresh') }
</div>
}
</div>
</div>
);
}
_getRenderListEmptyComponent: () => Object;
/**
* Returns a list empty component if a custom one has to be rendered instead
* of the default one in the {@link NavigateSectionList}.
*
* @private
* @returns {React$Component}
*/
_getRenderListEmptyComponent() {
const {
_calendarError,
_hasIntegrationSelected,
_hasLoadedEvents,
t
} = this.props;
if (_calendarError) {
return this._getErrorMessage();
} else if (_hasIntegrationSelected && _hasLoadedEvents) {
return (
<div className = 'meetings-list-empty'>
<p className = 'description'>
{ t('calendarSync.noEvents') }
</p>
<div
className = 'button'
onClick = { this._onRefreshEvents }>
{ t('calendarSync.refresh') }
</div>
</div>
);
} else if (_hasIntegrationSelected && !_hasLoadedEvents) {
return (
<div className = 'meetings-list-empty'>
<Spinner
invertColor = { true }
isCompleting = { false }
size = 'medium' />
</div>
);
}
return (
<div className = 'meetings-list-empty'>
<p className = 'description'>
{ t('welcomepage.connectCalendarText', {
app: interfaceConfig.APP_NAME,
provider: interfaceConfig.PROVIDER_NAME
}) }
</p>
<div
className = 'button'
onClick = { this._onOpenSettings }>
{ t('welcomepage.connectCalendarButton') }
</div>
</div>
);
}
_onOpenSettings: () => void;
/**
* Opens {@code SettingsDialog}.
*
* @private
* @returns {void}
*/
_onOpenSettings() {
sendAnalytics(createCalendarClickedEvent('calendar.connect'));
this.props.dispatch(openSettingsDialog(SETTINGS_TABS.CALENDAR));
}
_onRefreshEvents: () => void;
/**
* Gets an updated list of calendar events.
*
* @private
* @returns {void}
*/
_onRefreshEvents() {
this.props.dispatch(refreshCalendar(true));
}
}
/**
* Maps (parts of) the Redux state to the associated props for the
* {@code CalendarList} component.
*
* @param {Object} state - The Redux state.
* @private
* @returns {{
* _calendarError: Object,
* _hasIntegrationSelected: boolean,
* _hasLoadedEvents: boolean
* }}
*/
function _mapStateToProps(state) {
const {
error,
events,
integrationType,
isLoadingEvents
} = state['features/calendar-sync'];
return {
_calendarError: error,
_hasIntegrationSelected: Boolean(integrationType),
_hasLoadedEvents: Boolean(events) || !isLoadingEvents
};
}
export default translate(connect(_mapStateToProps)(CalendarList));
|
src/js/admin/photos/photo-operation-bar/photo-operation-bar.js | ucev/blog | import React from 'react'
import './photo-operation-bar.style.scss'
export default ({ id, children }) => (
<div className="photo-operation-bar" id={id}>
{children}
</div>
)
|
ui/kirk/src/Finance/index.js | socx/Kirk | import React from 'react'
const Finance = (props) => (
<div>
<h1>Finance</h1>
<p>{console.log(props)}</p>
</div>
)
export default Finance |
test/specs/views/Card/CardDescription-test.js | mohammed88/Semantic-UI-React | import faker from 'faker'
import React from 'react'
import * as common from 'test/specs/commonTests'
import CardDescription from 'src/views/Card/CardDescription'
describe('CardDescription', () => {
common.isConformant(CardDescription)
common.rendersChildren(CardDescription)
describe('description prop', () => {
it('renders child text', () => {
const text = faker.hacker.phrase()
shallow(<CardDescription content={text} />)
.should.contain.text(text)
})
})
})
|
example/App.js | atFriendly/react-native-friendly-chat | import React from 'react';
import {
Platform,
StyleSheet,
Text,
View,
} from 'react-native';
import {GiftedChat, Actions, Bubble, SystemMessage} from 'react-native-gifted-chat';
import CustomActions from './CustomActions';
import CustomView from './CustomView';
export default class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
loadEarlier: true,
typingText: null,
isLoadingEarlier: false,
};
this._isMounted = false;
this.onSend = this.onSend.bind(this);
this.onReceive = this.onReceive.bind(this);
this.renderCustomActions = this.renderCustomActions.bind(this);
this.renderBubble = this.renderBubble.bind(this);
this.renderSystemMessage = this.renderSystemMessage.bind(this);
this.renderFooter = this.renderFooter.bind(this);
this.onLoadEarlier = this.onLoadEarlier.bind(this);
this._isAlright = null;
}
componentWillMount() {
this._isMounted = true;
this.setState(() => {
return {
messages: require('./data/messages.js'),
};
});
}
componentWillUnmount() {
this._isMounted = false;
}
onLoadEarlier() {
this.setState((previousState) => {
return {
isLoadingEarlier: true,
};
});
setTimeout(() => {
if (this._isMounted === true) {
this.setState((previousState) => {
return {
messages: GiftedChat.prepend(previousState.messages, require('./data/old_messages.js')),
loadEarlier: false,
isLoadingEarlier: false,
};
});
}
}, 1000); // simulating network
}
onSend(messages = []) {
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, messages),
};
});
// for demo purpose
this.answerDemo(messages);
}
answerDemo(messages) {
if (messages.length > 0) {
if ((messages[0].image || messages[0].location) || !this._isAlright) {
this.setState((previousState) => {
return {
typingText: 'React Native is typing'
};
});
}
}
setTimeout(() => {
if (this._isMounted === true) {
if (messages.length > 0) {
if (messages[0].image) {
this.onReceive('Nice picture!');
} else if (messages[0].location) {
this.onReceive('My favorite place');
} else {
if (!this._isAlright) {
this._isAlright = true;
this.onReceive('Alright');
}
}
}
}
this.setState((previousState) => {
return {
typingText: null,
};
});
}, 1000);
}
onReceive(text) {
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, {
_id: Math.round(Math.random() * 1000000),
text: text,
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
// avatar: 'https://facebook.github.io/react/img/logo_og.png',
},
}),
};
});
}
renderCustomActions(props) {
if (Platform.OS === 'ios') {
return (
<CustomActions
{...props}
/>
);
}
const options = {
'Action 1': (props) => {
alert('option 1');
},
'Action 2': (props) => {
alert('option 2');
},
'Cancel': () => {},
};
return (
<Actions
{...props}
options={options}
/>
);
}
renderBubble(props) {
return (
<Bubble
{...props}
wrapperStyle={{
left: {
backgroundColor: '#f0f0f0',
}
}}
/>
);
}
renderSystemMessage(props) {
return (
<SystemMessage
{...props}
containerStyle={{
marginBottom: 15,
}}
textStyle={{
fontSize: 14,
}}
/>
);
}
renderCustomView(props) {
return (
<CustomView
{...props}
/>
);
}
renderFooter(props) {
if (this.state.typingText) {
return (
<View style={styles.footerContainer}>
<Text style={styles.footerText}>
{this.state.typingText}
</Text>
</View>
);
}
return null;
}
render() {
return (
<GiftedChat
messages={this.state.messages}
onSend={this.onSend}
loadEarlier={this.state.loadEarlier}
onLoadEarlier={this.onLoadEarlier}
isLoadingEarlier={this.state.isLoadingEarlier}
user={{
_id: 1, // sent messages should have same user._id
}}
renderActions={this.renderCustomActions}
renderBubble={this.renderBubble}
renderSystemMessage={this.renderSystemMessage}
renderCustomView={this.renderCustomView}
renderFooter={this.renderFooter}
/>
);
}
}
const styles = StyleSheet.create({
footerContainer: {
marginTop: 5,
marginLeft: 10,
marginRight: 10,
marginBottom: 10,
},
footerText: {
fontSize: 14,
color: '#aaa',
},
});
|
js/components/listSwipe/index.js | alaxa27/Lukeat | import React, { Component } from 'react';
import { Container, Header, Title, Content, Button, Icon, Text, Left, Right, Body, List, ListItem } from 'native-base';
import styles from './styles';
const datas = [
{
route: 'BasicListSwipe',
text: 'Single SwipeRow',
},
{
route: 'MultiListSwipe',
text: 'Multiple List Swipe',
},
];
class ListSwipe extends Component {
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => this.props.navigation.navigate('DrawerOpen')}>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>List Swipe</Title>
</Body>
<Right />
</Header>
<Content scrollEnabled={false} contentContainerStyle={{ flex: 1 }}>
<List
dataArray={datas}
renderRow={data =>
<ListItem button onPress={() => this.props.navigation.navigate(data.route)}>
<Text>
{data.text}
</Text>
<Right>
<Icon name="arrow-forward" />
</Right>
</ListItem>}
/>
</Content>
</Container>
);
}
}
export default ListSwipe;
|
user_guide/_static/jquery.js | carloDellarossa/Test-carlo | /*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;
if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")
},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
|
examples/with-custom-babel-config/pages/index.js | JeromeFitz/next.js | import { useState, useEffect } from 'react'
const MyLuckNo = () => {
const [randomNumber, setRandomNumber] = useState(null)
const recalculate = () => {
setRandomNumber(Math.ceil(Math.random() * 100))
}
useEffect(() => {
recalculate()
}, [])
const message = do {
if (randomNumber < 30) {
// eslint-disable-next-line no-unused-expressions
;('Do not give up. Try again.')
} else if (randomNumber < 60) {
// eslint-disable-next-line no-unused-expressions
;('You are a lucky guy')
} else {
// eslint-disable-next-line no-unused-expressions
;('You are soooo lucky!')
}
}
if (randomNumber === null) return <p>Please wait..</p>
return (
<div>
<h3>Your Lucky number is: "{randomNumber}"</h3>
<p>{message}</p>
<button onClick={() => recalculate()}>Try Again</button>
</div>
)
}
export default MyLuckNo
|
src/nuggets/node/client/src/views/Home/HomePage.js | civiclee/Hack4Cause2017 | import React from 'react';
import axios from 'axios';
import _ from 'lodash';
import { Grid, Row, Col } from 'react-flexbox-grid';
import CategoryIcon from './Components/CategoryIcon';
import Income from '../../images/profit.png';
import Tie from '../../images/tie.png';
import Tool from '../../images/tool.png';
import Transport from '../../images/transport.png';
import Home from '../../images/home.png';
import Cloud from '../../images/cloud.png';
const iconImageMapping = {
'profit.png': Income,
'tie.png': Tie,
'tool.png': Tool,
'transport.png': Transport,
'home.png': Home,
'cloud.png': Cloud
};
const categoriesEndpoint = 'http://localhost:3001/categories';
export default React.createClass({
getInitialState() {
return {
categories: [],
errors: []
}
},
componentWillMount() {
axios.get(categoriesEndpoint)
.then((res) => {
this.setState({
categories: res.data
});
})
.catch((err) => {
const errors = this.state.errors.concat([err]);
this.setState({errors});
});
},
renderIcons() {
const mappedCategories = [].concat(this.state.categories);
mappedCategories.shift();
const categoryIcons = mappedCategories
.map((category, index) => {
const icon = iconImageMapping[category.icon];
const name = category.name;
return (
<div key={index}>
<Col xs={3} md={3}>
<CategoryIcon icon={icon} name={name} categoryId={category.id} />
</Col>
</div>
)
});
return (
<div className="homepage-container">
<Row start="xs" around="xs">{categoryIcons}</Row>
</div>
);
},
render() {
return (
<Grid fluid>
<Row center="md">
<h1 className="title">Welcome to Eugene</h1>
</Row>
<Row center="md">
<h3 className="subtext">What would you like to learn about?</h3>
</Row>
{this.renderIcons()}
</Grid>
);
}
}); |
test/GridSpec.js | snadn/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Grid from '../src/Grid';
describe('Grid', function () {
it('uses "div" by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Grid />
);
assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
});
it('has "container" class by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Grid />
);
assert.equal(React.findDOMNode(instance).className, 'container');
});
it('turns grid into "full-width" layout via "fluid" property set', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Grid fluid />
);
assert.equal(React.findDOMNode(instance).className, 'container-fluid');
});
it('should merge additional classes passed in', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Grid className="whatever" fluid />
);
assert.ok(React.findDOMNode(instance).className.match(/\bwhatever\b/));
assert.ok(React.findDOMNode(instance).className.match(/\bcontainer-fluid\b/));
});
it('allows custom elements instead of "div"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Grid componentClass='section' />
);
assert.equal(React.findDOMNode(instance).nodeName, 'SECTION');
});
});
|
local-cli/templates/HelloNavigation/components/KeyboardSpacer.js | gilesvangruisen/react-native | 'use strict';
/* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
Platform,
View,
Keyboard,
LayoutAnimation,
UIManager,
} from 'react-native';
type Props = {
offset?: number,
}
type State = {
keyboardHeight: number
}
// Consider contributing this to the popular library:
// https://github.com/Andr3wHur5t/react-native-keyboard-spacer
/**
* On iOS, the software keyboard covers the screen by default.
* This is not desirable if there are TextInputs near the bottom of the screen -
* they would be covered by the keyboard and the user cannot see what they
* are typing.
* To get around this problem, place a `<KeyboardSpacer />` at the bottom
* of the screen, after your TextInputs. The keyboard spacer has size 0 and
* when the keyboard is shown it will grow to the same size as the keyboard,
* shifting all views above it and therefore making them visible.
*
* On Android, this component is not needed because resizing the UI when
* the keyboard is shown is supported by the OS.
* Simply set the `android:windowSoftInputMode="adjustResize"` attribute
* on the <activity> element in your AndroidManifest.xml.
*
* How is this different from KeyboardAvoidingView?
* The KeyboardAvoidingView doesn't work when used together with
* a ScrollView/ListView.
*/
const KeyboardSpacer = () => (
Platform.OS === 'ios' ? <KeyboardSpacerIOS /> : null
);
class KeyboardSpacerIOS extends Component<Props, Props, State> {
static propTypes = {
offset: PropTypes.number,
};
static defaultProps = {
offset: 0,
};
state: State = {
keyboardHeight: 0,
};
componentWillMount() {
this._registerEvents();
}
componentWillUnmount() {
this._unRegisterEvents();
}
_keyboardWillShowSubscription: { remove: Function };
_keyboardWillHideSubscription: { remove: Function };
_registerEvents = () => {
this._keyboardWillShowSubscription = Keyboard.addListener(
'keyboardWillShow',
this._keyboardWillShow
);
this._keyboardWillHideSubscription = Keyboard.addListener(
'keyboardWillHide',
this._keyboardWillHide
);
};
_unRegisterEvents = () => {
this._keyboardWillShowSubscription.remove();
this._keyboardWillHideSubscription.remove();
};
_configureLayoutAnimation = () => {
// Any duration is OK here. The `type: 'keyboard defines the animation.
LayoutAnimation.configureNext({
duration: 100,
update: {
type: 'keyboard',
}
});
}
_keyboardWillShow = (e: any) => {
this._configureLayoutAnimation();
this.setState({
keyboardHeight: e.endCoordinates.height - (this.props.offset || 0),
});
};
_keyboardWillHide = () => {
this._configureLayoutAnimation();
this.setState({
keyboardHeight: 0,
});
};
render() {
return <View style={{ height: this.state.keyboardHeight }} />;
}
}
export default KeyboardSpacer;
|
src/components/AppNav/index.js | matapang/virtualraceph2 | import React from 'react';
import styled from 'styled-components';
import Logo from '../Logo';
import {
Nav,
NavItem,
Navbar
} from 'react-bootstrap';
import {
Link
} from 'react-router-dom';
import RouteNavItem from '../RouteNavItem';
const NavBarWrapper = styled(Navbar) `
background:white;
height:60px;
text-align:center;
padding:0;
box-shadow:0 3px 3px 0 rgba(0,0,0,0.14);
a {
color:#aaa;
&:hover{
color:#0da9ef !important;
border-top:2px solid #0da9ef;
}
}
`
const AppNav = ({ userToken, history, handleLogout }) => {
const handleNavLink = (e) => {
e.preventDefault();
history.push(e.currentTarget.getAttribute('href'));
};
return (
<Navbar fluid collapseOnSelect inverse>
<Navbar.Header>
<Navbar.Brand>
<Link to="/" ><Logo/></Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav pullRight>
{userToken
?
[
<RouteNavItem key={3} onClick={handleNavLink} href="/">Dashboard</RouteNavItem>,
<RouteNavItem key={2} onClick={handleNavLink} href="/feeds">Feeds</RouteNavItem>,
<NavItem key={1} onClick={handleLogout}>Logout</NavItem>
]
: [<RouteNavItem key={1} onClick={handleNavLink} href="/signup">Signup</RouteNavItem>,
<RouteNavItem key={2} onClick={handleNavLink} href="/login">Login</RouteNavItem>]}
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
export default AppNav;
|
spec/components/menu.js | rubenmoya/react-toolbox | import React from 'react';
import { Menu, MenuItem, MenuDivider } from '../../components/menu';
class MenuTest extends React.Component {
state = {
value: undefined,
};
handleSelect = (item) => {
console.log('Menu selection changed!!, now its', item);
this.setState({ value: item });
};
handleItemClick = () => {
console.log('This item is so special that has a special handler');
};
render() {
return (
<section>
<h5>Menus</h5>
<p>This tabs can be disabled or hidden</p>
<Menu onSelect={this.handleSelect} selectable={false} selected={this.state.value}>
<MenuItem value="foo" caption="Caption" />
<MenuItem onClick={this.handleItemClick} value="bar" caption="Caption & Shortcut" shortcut="Ctrl + P" />
<MenuItem caption="Disabled ..." disabled shortcut="Ctrl + P" />
<MenuDivider />
<MenuItem caption="Caption & Icon" icon="phone" />
<MenuItem caption="Caption, Icon & Shortcut" icon="phone" shortcut="Ctrl + P" />
<MenuItem caption="Disabled ..." icon="phone" shortcut="Ctrl + P" disabled />
</Menu>
</section>
);
}
}
export default MenuTest;
|
react-native/NewYorkTimesBestSellers/BookItem.js | tiagofumo/react-sample-projects | 'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
ListView
} from 'react-native';
class BookItem extends Component {
static propTypes = {
coverURL: React.PropTypes.string.isRequired,
author: React.PropTypes.string.isRequired,
title: React.PropTypes.string.isRequired
}
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.bookItem}>
<Image style={styles.cover} source={{uri: this.props.coverURL}}/>
<View style={styles.info}>
<Text style={styles.author}>{this.props.author}</Text>
<Text style={styles.title}>{this.props.title}</Text>
</View>
</View>
);
}
}
var styles = StyleSheet.create({
bookItem: {
flex: 1,
flexDirection: 'row',
backgroundColor: '#FFFFFF',
borderBottomColor: '#AAAAAA',
borderBottomWidth: 2,
padding: 5,
height: 160
},
cover: {
flex: 1,
height: 150,
resizeMode: 'contain'
},
info: {
flex: 3,
alignItems: 'flex-end',
flexDirection: 'column',
alignSelf: 'center',
padding: 20
},
author: {
fontSize: 18
},
title: {
fontSize: 18,
fontWeight: 'bold'
}
});
module.exports = BookItem;
|
src/browser/todos/TodosPage.react.js | syroegkin/mikora.eu | import Buttons from './Buttons.react';
import Component from 'react-pure-render/component';
import Helmet from 'react-helmet';
import NewTodo from './NewTodo.react';
import React from 'react';
import Todos from './Todos.react';
import linksMessages from '../../common/app/linksMessages';
import { injectIntl, intlShape } from 'react-intl';
class TodosPage extends Component {
static propTypes = {
intl: intlShape.isRequired
};
render() {
const { intl } = this.props;
const title = intl.formatMessage(linksMessages.todos);
return (
<div className="todos-page">
<Helmet title={title} />
<NewTodo />
<Todos />
<Buttons />
</div>
);
}
}
export default injectIntl(TodosPage);
|
packages/generator-react-redux-application/template/src/components/App.js | my-dish/dish | // @flow
import React from 'react';
import FilterName from '../containers/FilterName';
import DisplayName from '../containers/DisplayName';
import styles from '../styles/app.css';
const App = () => (
<div className={styles.container}>
<DisplayName />
<FilterName />
</div>
);
export default App;
|
src/collections/Menu/MenuHeader.js | Semantic-Org/Semantic-UI-React | import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import { childrenUtils, customPropTypes, getElementType, getUnhandledProps } from '../../lib'
/**
* A menu item may include a header or may itself be a header.
*/
function MenuHeader(props) {
const { children, className, content } = props
const classes = cx('header', className)
const rest = getUnhandledProps(MenuHeader, props)
const ElementType = getElementType(MenuHeader, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
MenuHeader.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
export default MenuHeader
|
src/components/video_list_item.js | johncpatterson/Learning-React | import React from 'react';
const VideoListItem = (props) => {
const video = props.video;
const onVideoSelect = props.onVideoSelect;
const imageUrl = video.snippet.thumbnails.default.url;
return (
<li onClick={() => onVideoSelect(video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={imageUrl} />
</div>
<div className="media-body">
<div className="media-heading">{video.snippet.title}</div>
</div>
</div>
</li>
);
};
export default VideoListItem; |
src/components/Image/Image.js | ubc-subbots/ubc-subbots.github.io | import React from 'react';
import './styles.scss';
export default function Image(props){
const folder = "/" + (props.folder ? props.folder : "images") + "/";
return(
<div className="ImageContainer">
<img className="Image" src={process.env.PUBLIC_URL + folder + props.src} alt="Error!"/>
</div>
)
} |
ajax/libs/yasgui/1.0.17/yasgui.min.js | JimBobSquarePants/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASGUI=e()}}(function(){var e;return function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=n[s]={exports:{}};e[s][0].call(p.exports,function(t){var n=e[s][1][t];return i(n?n:t)},p,p.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t){t.exports=e("./main.js")},{"./main.js":99}],2:[function(e,t){function n(){this._events=this._events||{};this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function i(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n;n.EventEmitter=n;n.prototype._events=void 0;n.prototype._maxListeners=void 0;n.defaultMaxListeners=10;n.prototype.setMaxListeners=function(e){if(!i(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");this._maxListeners=e;return this};n.prototype.emit=function(e){var t,n,i,a,l,u;this._events||(this._events={});if("error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){t=arguments[1];if(t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}n=this._events[e];if(s(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:i=arguments.length;a=new Array(i-1);for(l=1;i>l;l++)a[l-1]=arguments[l];n.apply(this,a)}else if(o(n)){i=arguments.length;a=new Array(i-1);for(l=1;i>l;l++)a[l-1]=arguments[l];u=n.slice();i=u.length;for(l=0;i>l;l++)u[l].apply(this,a)}return!0};n.prototype.addListener=function(e,t){var i;if(!r(t))throw TypeError("listener must be a function");this._events||(this._events={});this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t);this._events[e]?o(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t;if(o(this._events[e])&&!this._events[e].warned){var i;i=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners;if(i&&i>0&&this._events[e].length>i){this._events[e].warned=!0;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length);"function"==typeof console.trace&&console.trace()}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){function n(){this.removeListener(e,n);if(!i){i=!0;t.apply(this,arguments)}}if(!r(t))throw TypeError("listener must be a function");var i=!1;n.listener=t;this.on(e,n);return this};n.prototype.removeListener=function(e,t){var n,i,s,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;n=this._events[e];s=n.length;i=-1;if(n===t||r(n.listener)&&n.listener===t){delete this._events[e];this._events.removeListener&&this.emit("removeListener",e,t)}else if(o(n)){for(a=s;a-->0;)if(n[a]===t||n[a].listener&&n[a].listener===t){i=a;break}if(0>i)return this;if(1===n.length){n.length=0;delete this._events[e]}else n.splice(i,1);this._events.removeListener&&this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener){0===arguments.length?this._events={}:this._events[e]&&delete this._events[e];return this}if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);this.removeAllListeners("removeListener");this._events={};return this}n=this._events[e];if(r(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);delete this._events[e];return this};n.prototype.listeners=function(e){var t;t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[];return t};n.listenerCount=function(e,t){var n;n=e._events&&e._events[t]?r(e._events[t])?1:e._events[t].length:0;return n}},{}],3:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();(function(e,t){function n(t,n){var i,o,s,a=t.nodeName.toLowerCase();if("area"===a){i=t.parentNode;o=i.name;if(!t.href||!o||"map"!==i.nodeName.toLowerCase())return!1;s=e("img[usemap=#"+o+"]")[0];return!!s&&r(s)}return(/input|select|textarea|button|object/.test(a)?!t.disabled:"a"===a?t.href||n:n)&&r(t)}function r(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var i=0,o=/^ui-id-\d+$/;e.ui=e.ui||{};e.extend(e.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}});e.fn.extend({focus:function(t){return function(n,r){return"number"==typeof n?this.each(function(){var t=this;setTimeout(function(){e(t).focus();r&&r.call(t)},n)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0);return/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length)for(var r,i,o=e(this[0]);o.length&&o[0]!==document;){r=o.css("position");if("absolute"===r||"relative"===r||"fixed"===r){i=parseInt(o.css("zIndex"),10);if(!isNaN(i)&&0!==i)return i}o=o.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++i)})},removeUniqueId:function(){return this.each(function(){o.test(this.id)&&e(this).removeAttr("id")})}});e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return n(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var r=e.attr(t,"tabindex"),i=isNaN(r);return(i||r>=0)&&n(t,!i)}});e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function i(t,n,r,i){e.each(o,function(){n-=parseFloat(e.css(t,"padding"+this))||0;r&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0);i&&(n-=parseFloat(e.css(t,"margin"+this))||0)});return n}var o="Width"===r?["Left","Right"]:["Top","Bottom"],s=r.toLowerCase(),a={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?a["inner"+r].call(this):this.each(function(){e(this).css(s,i(this,n)+"px")})};e.fn["outer"+r]=function(t,n){return"number"!=typeof t?a["outer"+r].call(this,t):this.each(function(){e(this).css(s,i(this,t,!0,n)+"px")})}});e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))});e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData));e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());e.support.selectstart="onselectstart"in document.createElement("div");e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});e.extend(e.ui,{plugin:{add:function(t,n,r){var i,o=e.ui[t].prototype;for(i in r){o.plugins[i]=o.plugins[i]||[];o.plugins[i].push([n,r[i]])}},call:function(e,t,n){var r,i=e.plugins[t];if(i&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(r=0;r<i.length;r++)e.options[i[r][0]]&&i[r][1].apply(e.element,n)}},hasScroll:function(t,n){if("hidden"===e(t).css("overflow"))return!1;var r=n&&"left"===n?"scrollLeft":"scrollTop",i=!1;if(t[r]>0)return!0;t[r]=1;i=t[r]>0;t[r]=0;return i}})})(t)},{jquery:void 0}],4:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("./widget");(function(e){var t=!1;e(document).mouseup(function(){t=!1});e.widget("ui.mouse",{version:"1.10.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent")){e.removeData(n.target,t.widgetName+".preventClickEvent");n.stopImmediatePropagation();return!1}});this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(n){if(!t){this._mouseStarted&&this._mouseUp(n);this._mouseDownEvent=n;var r=this,i=1===n.which,o="string"==typeof this.options.cancel&&n.target.nodeName?e(n.target).closest(this.options.cancel).length:!1;if(!i||o||!this._mouseCapture(n))return!0;this.mouseDelayMet=!this.options.delay;this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(n)&&this._mouseDelayMet(n)){this._mouseStarted=this._mouseStart(n)!==!1;if(!this._mouseStarted){n.preventDefault();return!0}}!0===e.data(n.target,this.widgetName+".preventClickEvent")&&e.removeData(n.target,this.widgetName+".preventClickEvent");this._mouseMoveDelegate=function(e){return r._mouseMove(e)};this._mouseUpDelegate=function(e){return r._mouseUp(e)};e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);n.preventDefault();t=!0;return!0}},_mouseMove:function(t){if(e.ui.ie&&(!document.documentMode||document.documentMode<9)&&!t.button)return this._mouseUp(t);if(this._mouseStarted){this._mouseDrag(t);return t.preventDefault()}if(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)){this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1;this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)}return!this._mouseStarted},_mouseUp:function(t){e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=!1;t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0);this._mouseStop(t)}return!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(t)},{"./widget":7,jquery:void 0}],5:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();(function(e,t){function n(e,t,n){return[parseFloat(e[0])*(h.test(e[0])?t/100:1),parseFloat(e[1])*(h.test(e[1])?n/100:1)]}function r(t,n){return parseInt(e.css(t,n),10)||0}function i(t){var n=t[0];return 9===n.nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var o,s=Math.max,a=Math.abs,l=Math.round,u=/left|center|right/,p=/top|center|bottom/,c=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,h=/%$/,f=e.fn.position;e.position={scrollbarWidth:function(){if(o!==t)return o;var n,r,i=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),s=i.children()[0];e("body").append(i);n=s.offsetWidth;i.css("overflow","scroll");r=s.offsetWidth;n===r&&(r=i[0].clientWidth);i.remove();return o=n-r},getScrollInfo:function(t){var n=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),r=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),i="scroll"===n||"auto"===n&&t.width<t.element[0].scrollWidth,o="scroll"===r||"auto"===r&&t.height<t.element[0].scrollHeight;return{width:o?e.position.scrollbarWidth():0,height:i?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]),i=!!n[0]&&9===n[0].nodeType;return{element:n,isWindow:r,isDocument:i,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}};e.fn.position=function(t){if(!t||!t.of)return f.apply(this,arguments);t=e.extend({},t);var o,h,g,m,E,v,x=e(t.of),y=e.position.getWithinInfo(t.within),N=e.position.getScrollInfo(y),I=(t.collision||"flip").split(" "),A={};v=i(x);x[0].preventDefault&&(t.at="left top");h=v.width;g=v.height;m=v.offset;E=e.extend({},m);e.each(["my","at"],function(){var e,n,r=(t[this]||"").split(" ");1===r.length&&(r=u.test(r[0])?r.concat(["center"]):p.test(r[0])?["center"].concat(r):["center","center"]);r[0]=u.test(r[0])?r[0]:"center";r[1]=p.test(r[1])?r[1]:"center";e=c.exec(r[0]);n=c.exec(r[1]);A[this]=[e?e[0]:0,n?n[0]:0];t[this]=[d.exec(r[0])[0],d.exec(r[1])[0]]});1===I.length&&(I[1]=I[0]);"right"===t.at[0]?E.left+=h:"center"===t.at[0]&&(E.left+=h/2);"bottom"===t.at[1]?E.top+=g:"center"===t.at[1]&&(E.top+=g/2);o=n(A.at,h,g);E.left+=o[0];E.top+=o[1];return this.each(function(){var i,u,p=e(this),c=p.outerWidth(),d=p.outerHeight(),f=r(this,"marginLeft"),v=r(this,"marginTop"),T=c+f+r(this,"marginRight")+N.width,L=d+v+r(this,"marginBottom")+N.height,S=e.extend({},E),b=n(A.my,p.outerWidth(),p.outerHeight());"right"===t.my[0]?S.left-=c:"center"===t.my[0]&&(S.left-=c/2);"bottom"===t.my[1]?S.top-=d:"center"===t.my[1]&&(S.top-=d/2);S.left+=b[0];S.top+=b[1];if(!e.support.offsetFractions){S.left=l(S.left);S.top=l(S.top)}i={marginLeft:f,marginTop:v};e.each(["left","top"],function(n,r){e.ui.position[I[n]]&&e.ui.position[I[n]][r](S,{targetWidth:h,targetHeight:g,elemWidth:c,elemHeight:d,collisionPosition:i,collisionWidth:T,collisionHeight:L,offset:[o[0]+b[0],o[1]+b[1]],my:t.my,at:t.at,within:y,elem:p})});t.using&&(u=function(e){var n=m.left-S.left,r=n+h-c,i=m.top-S.top,o=i+g-d,l={target:{element:x,left:m.left,top:m.top,width:h,height:g},element:{element:p,left:S.left,top:S.top,width:c,height:d},horizontal:0>r?"left":n>0?"right":"center",vertical:0>o?"top":i>0?"bottom":"middle"};c>h&&a(n+r)<h&&(l.horizontal="center");d>g&&a(i+o)<g&&(l.vertical="middle");l.important=s(a(n),a(r))>s(a(i),a(o))?"horizontal":"vertical";t.using.call(this,e,l)});p.offset(e.extend(S,{using:u}))})};e.ui.position={fit:{left:function(e,t){var n,r=t.within,i=r.isWindow?r.scrollLeft:r.offset.left,o=r.width,a=e.left-t.collisionPosition.marginLeft,l=i-a,u=a+t.collisionWidth-o-i;if(t.collisionWidth>o)if(l>0&&0>=u){n=e.left+l+t.collisionWidth-o-i;e.left+=l-n}else e.left=u>0&&0>=l?i:l>u?i+o-t.collisionWidth:i;else l>0?e.left+=l:u>0?e.left-=u:e.left=s(e.left-a,e.left)},top:function(e,t){var n,r=t.within,i=r.isWindow?r.scrollTop:r.offset.top,o=t.within.height,a=e.top-t.collisionPosition.marginTop,l=i-a,u=a+t.collisionHeight-o-i;if(t.collisionHeight>o)if(l>0&&0>=u){n=e.top+l+t.collisionHeight-o-i;e.top+=l-n}else e.top=u>0&&0>=l?i:l>u?i+o-t.collisionHeight:i;else l>0?e.top+=l:u>0?e.top-=u:e.top=s(e.top-a,e.top)}},flip:{left:function(e,t){var n,r,i=t.within,o=i.offset.left+i.scrollLeft,s=i.width,l=i.isWindow?i.scrollLeft:i.offset.left,u=e.left-t.collisionPosition.marginLeft,p=u-l,c=u+t.collisionWidth-s-l,d="left"===t.my[0]?-t.elemWidth:"right"===t.my[0]?t.elemWidth:0,h="left"===t.at[0]?t.targetWidth:"right"===t.at[0]?-t.targetWidth:0,f=-2*t.offset[0];if(0>p){n=e.left+d+h+f+t.collisionWidth-s-o;(0>n||n<a(p))&&(e.left+=d+h+f)}else if(c>0){r=e.left-t.collisionPosition.marginLeft+d+h+f-l;(r>0||a(r)<c)&&(e.left+=d+h+f)}},top:function(e,t){var n,r,i=t.within,o=i.offset.top+i.scrollTop,s=i.height,l=i.isWindow?i.scrollTop:i.offset.top,u=e.top-t.collisionPosition.marginTop,p=u-l,c=u+t.collisionHeight-s-l,d="top"===t.my[1],h=d?-t.elemHeight:"bottom"===t.my[1]?t.elemHeight:0,f="top"===t.at[1]?t.targetHeight:"bottom"===t.at[1]?-t.targetHeight:0,g=-2*t.offset[1];if(0>p){r=e.top+h+f+g+t.collisionHeight-s-o;e.top+h+f+g>p&&(0>r||r<a(p))&&(e.top+=h+f+g)}else if(c>0){n=e.top-t.collisionPosition.marginTop+h+f+g-l;e.top+h+f+g>c&&(n>0||a(n)<c)&&(e.top+=h+f+g)}}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments);e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments);e.ui.position.fit.top.apply(this,arguments)}}};(function(){var t,n,r,i,o,s=document.getElementsByTagName("body")[0],a=document.createElement("div");t=document.createElement(s?"div":"body");r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"};s&&e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in r)t.style[o]=r[o];t.appendChild(a);n=s||document.documentElement;n.insertBefore(t,n.firstChild);a.style.cssText="position: absolute; left: 10.7432222px;";i=e(a).offset().left;e.support.offsetFractions=i>10&&11>i;t.innerHTML="";n.removeChild(t)})()})(t)},{jquery:void 0}],6:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("./core");e("./mouse");e("./widget");(function(e){function t(e){return parseInt(e,10)||0}function n(e){return!isNaN(parseInt(e,10))}e.widget("ui.resizable",e.ui.mouse,{version:"1.10.4",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_create:function(){var t,n,r,i,o,s=this,a=this.options;this.element.addClass("ui-resizable");e.extend(this,{_aspectRatio:!!a.aspectRatio,aspectRatio:a.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:a.helper||a.ghost||a.animate?a.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){this.element.wrap(e("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable"));this.elementIsWrapper=!0;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=a.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor===String){"all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw");t=this.handles.split(",");this.handles={};for(n=0;n<t.length;n++){r=e.trim(t[n]);o="ui-resizable-"+r;i=e("<div class='ui-resizable-handle "+o+"'></div>");i.css({zIndex:a.zIndex});"se"===r&&i.addClass("ui-icon ui-icon-gripsmall-diagonal-se");this.handles[r]=".ui-resizable-"+r;this.element.append(i)}}this._renderAxis=function(t){var n,r,i,o;t=t||this.element;for(n in this.handles){this.handles[n].constructor===String&&(this.handles[n]=e(this.handles[n],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){r=e(this.handles[n],this.element);o=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth();i=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join("");t.css(i,o);this._proportionallyResize()}e(this.handles[n]).length}};this._renderAxis(this.element);this._handles=e(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!s.resizing){this.className&&(i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i));s.axis=i&&i[1]?i[1]:"se"}});if(a.autoHide){this._handles.hide();e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(!a.disabled){e(this).removeClass("ui-resizable-autohide");s._handles.show()}}).mouseleave(function(){if(!a.disabled&&!s.resizing){e(this).addClass("ui-resizable-autohide");s._handles.hide()}})}this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,n=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){n(this.element);t=this.element;this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t);t.remove()}this.originalElement.css("resize",this.originalResizeStyle);n(this.originalElement);return this},_mouseCapture:function(t){var n,r,i=!1;for(n in this.handles){r=e(this.handles[n])[0];(r===t.target||e.contains(r,t.target))&&(i=!0)}return!this.options.disabled&&i},_mouseStart:function(n){var r,i,o,s=this.options,a=this.element.position(),l=this.element;this.resizing=!0;/absolute/.test(l.css("position"))?l.css({position:"absolute",top:l.css("top"),left:l.css("left")}):l.is(".ui-draggable")&&l.css({position:"absolute",top:a.top,left:a.left});this._renderProxy();r=t(this.helper.css("left"));i=t(this.helper.css("top"));if(s.containment){r+=e(s.containment).scrollLeft()||0;i+=e(s.containment).scrollTop()||0}this.offset=this.helper.offset();this.position={left:r,top:i};this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:l.width(),height:l.height()};this.originalSize=this._helper?{width:l.outerWidth(),height:l.outerHeight()}:{width:l.width(),height:l.height()};this.originalPosition={left:r,top:i};this.sizeDiff={width:l.outerWidth()-l.width(),height:l.outerHeight()-l.height()};this.originalMousePosition={left:n.pageX,top:n.pageY};this.aspectRatio="number"==typeof s.aspectRatio?s.aspectRatio:this.originalSize.width/this.originalSize.height||1;o=e(".ui-resizable-"+this.axis).css("cursor");e("body").css("cursor","auto"===o?this.axis+"-resize":o);l.addClass("ui-resizable-resizing");this._propagate("start",n);return!0},_mouseDrag:function(t){var n,r=this.helper,i={},o=this.originalMousePosition,s=this.axis,a=this.position.top,l=this.position.left,u=this.size.width,p=this.size.height,c=t.pageX-o.left||0,d=t.pageY-o.top||0,h=this._change[s];if(!h)return!1;n=h.apply(this,[t,c,d]);this._updateVirtualBoundaries(t.shiftKey);(this._aspectRatio||t.shiftKey)&&(n=this._updateRatio(n,t));n=this._respectSize(n,t);this._updateCache(n);this._propagate("resize",t);this.position.top!==a&&(i.top=this.position.top+"px");this.position.left!==l&&(i.left=this.position.left+"px");this.size.width!==u&&(i.width=this.size.width+"px");this.size.height!==p&&(i.height=this.size.height+"px");r.css(i);!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize();e.isEmptyObject(i)||this._trigger("resize",t,this.ui());return!1},_mouseStop:function(t){this.resizing=!1;var n,r,i,o,s,a,l,u=this.options,p=this;if(this._helper){n=this._proportionallyResizeElements;r=n.length&&/textarea/i.test(n[0].nodeName);i=r&&e.ui.hasScroll(n[0],"left")?0:p.sizeDiff.height;o=r?0:p.sizeDiff.width;s={width:p.helper.width()-o,height:p.helper.height()-i};a=parseInt(p.element.css("left"),10)+(p.position.left-p.originalPosition.left)||null;l=parseInt(p.element.css("top"),10)+(p.position.top-p.originalPosition.top)||null;u.animate||this.element.css(e.extend(s,{top:l,left:a}));p.helper.height(p.size.height);p.helper.width(p.size.width);this._helper&&!u.animate&&this._proportionallyResize()}e("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",t);this._helper&&this.helper.remove();return!1},_updateVirtualBoundaries:function(e){var t,r,i,o,s,a=this.options;s={minWidth:n(a.minWidth)?a.minWidth:0,maxWidth:n(a.maxWidth)?a.maxWidth:1/0,minHeight:n(a.minHeight)?a.minHeight:0,maxHeight:n(a.maxHeight)?a.maxHeight:1/0};if(this._aspectRatio||e){t=s.minHeight*this.aspectRatio;i=s.minWidth/this.aspectRatio;r=s.maxHeight*this.aspectRatio;o=s.maxWidth/this.aspectRatio;t>s.minWidth&&(s.minWidth=t);i>s.minHeight&&(s.minHeight=i);r<s.maxWidth&&(s.maxWidth=r);o<s.maxHeight&&(s.maxHeight=o)}this._vBoundaries=s},_updateCache:function(e){this.offset=this.helper.offset();n(e.left)&&(this.position.left=e.left);n(e.top)&&(this.position.top=e.top);n(e.height)&&(this.size.height=e.height);n(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,r=this.size,i=this.axis;n(e.height)?e.width=e.height*this.aspectRatio:n(e.width)&&(e.height=e.width/this.aspectRatio);if("sw"===i){e.left=t.left+(r.width-e.width);e.top=null}if("nw"===i){e.top=t.top+(r.height-e.height);e.left=t.left+(r.width-e.width)}return e},_respectSize:function(e){var t=this._vBoundaries,r=this.axis,i=n(e.width)&&t.maxWidth&&t.maxWidth<e.width,o=n(e.height)&&t.maxHeight&&t.maxHeight<e.height,s=n(e.width)&&t.minWidth&&t.minWidth>e.width,a=n(e.height)&&t.minHeight&&t.minHeight>e.height,l=this.originalPosition.left+this.originalSize.width,u=this.position.top+this.size.height,p=/sw|nw|w/.test(r),c=/nw|ne|n/.test(r);s&&(e.width=t.minWidth);a&&(e.height=t.minHeight);i&&(e.width=t.maxWidth);o&&(e.height=t.maxHeight);s&&p&&(e.left=l-t.minWidth);i&&p&&(e.left=l-t.maxWidth);a&&c&&(e.top=u-t.minHeight);o&&c&&(e.top=u-t.maxHeight);e.width||e.height||e.left||!e.top?e.width||e.height||e.top||!e.left||(e.left=null):e.top=null;return e},_proportionallyResize:function(){if(this._proportionallyResizeElements.length){var e,t,n,r,i,o=this.helper||this.element;for(e=0;e<this._proportionallyResizeElements.length;e++){i=this._proportionallyResizeElements[e];if(!this.borderDif){this.borderDif=[];n=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")];r=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];for(t=0;t<n.length;t++)this.borderDif[t]=(parseInt(n[t],10)||0)+(parseInt(r[t],10)||0)}i.css({height:o.height()-this.borderDif[0]-this.borderDif[2]||0,width:o.width()-this.borderDif[1]-this.borderDif[3]||0})}}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset();if(this._helper){this.helper=this.helper||e("<div style='overflow:hidden;'></div>");this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++n.zIndex});this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var n=this.originalSize,r=this.originalPosition;return{left:r.left+t,width:n.width-t}},n:function(e,t,n){var r=this.originalSize,i=this.originalPosition;return{top:i.top+n,height:r.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]);"resize"!==t&&this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}});e.ui.plugin.add("resizable","animate",{stop:function(t){var n=e(this).data("ui-resizable"),r=n.options,i=n._proportionallyResizeElements,o=i.length&&/textarea/i.test(i[0].nodeName),s=o&&e.ui.hasScroll(i[0],"left")?0:n.sizeDiff.height,a=o?0:n.sizeDiff.width,l={width:n.size.width-a,height:n.size.height-s},u=parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left)||null,p=parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top)||null;n.element.animate(e.extend(l,p&&u?{top:p,left:u}:{}),{duration:r.animateDuration,easing:r.animateEasing,step:function(){var r={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};i&&i.length&&e(i[0]).css({width:r.width,height:r.height});n._updateCache(r);n._propagate("resize",t)}})}});e.ui.plugin.add("resizable","containment",{start:function(){var n,r,i,o,s,a,l,u=e(this).data("ui-resizable"),p=u.options,c=u.element,d=p.containment,h=d instanceof e?d.get(0):/parent/.test(d)?c.parent().get(0):d;if(h){u.containerElement=e(h);if(/document/.test(d)||d===document){u.containerOffset={left:0,top:0};u.containerPosition={left:0,top:0};u.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}}else{n=e(h);r=[];e(["Top","Right","Left","Bottom"]).each(function(e,i){r[e]=t(n.css("padding"+i))});u.containerOffset=n.offset();u.containerPosition=n.position();u.containerSize={height:n.innerHeight()-r[3],width:n.innerWidth()-r[1]};i=u.containerOffset;o=u.containerSize.height;s=u.containerSize.width;a=e.ui.hasScroll(h,"left")?h.scrollWidth:s;l=e.ui.hasScroll(h)?h.scrollHeight:o;u.parentData={element:h,left:i.left,top:i.top,width:a,height:l}}}},resize:function(t){var n,r,i,o,s=e(this).data("ui-resizable"),a=s.options,l=s.containerOffset,u=s.position,p=s._aspectRatio||t.shiftKey,c={top:0,left:0},d=s.containerElement;d[0]!==document&&/static/.test(d.css("position"))&&(c=l);if(u.left<(s._helper?l.left:0)){s.size.width=s.size.width+(s._helper?s.position.left-l.left:s.position.left-c.left);p&&(s.size.height=s.size.width/s.aspectRatio);s.position.left=a.helper?l.left:0}if(u.top<(s._helper?l.top:0)){s.size.height=s.size.height+(s._helper?s.position.top-l.top:s.position.top);p&&(s.size.width=s.size.height*s.aspectRatio);s.position.top=s._helper?l.top:0}s.offset.left=s.parentData.left+s.position.left;s.offset.top=s.parentData.top+s.position.top;n=Math.abs((s._helper?s.offset.left-c.left:s.offset.left-c.left)+s.sizeDiff.width);r=Math.abs((s._helper?s.offset.top-c.top:s.offset.top-l.top)+s.sizeDiff.height);i=s.containerElement.get(0)===s.element.parent().get(0);o=/relative|absolute/.test(s.containerElement.css("position"));i&&o&&(n-=Math.abs(s.parentData.left));if(n+s.size.width>=s.parentData.width){s.size.width=s.parentData.width-n;p&&(s.size.height=s.size.width/s.aspectRatio)
}if(r+s.size.height>=s.parentData.height){s.size.height=s.parentData.height-r;p&&(s.size.width=s.size.height*s.aspectRatio)}},stop:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.containerOffset,i=t.containerPosition,o=t.containerElement,s=e(t.helper),a=s.offset(),l=s.outerWidth()-t.sizeDiff.width,u=s.outerHeight()-t.sizeDiff.height;t._helper&&!n.animate&&/relative/.test(o.css("position"))&&e(this).css({left:a.left-i.left-r.left,width:l,height:u});t._helper&&!n.animate&&/static/.test(o.css("position"))&&e(this).css({left:a.left-i.left-r.left,width:l,height:u})}});e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=function(t){e(t).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};if("object"!=typeof n.alsoResize||n.alsoResize.parentNode)r(n.alsoResize);else if(n.alsoResize.length){n.alsoResize=n.alsoResize[0];r(n.alsoResize)}else e.each(n.alsoResize,function(e){r(e)})},resize:function(t,n){var r=e(this).data("ui-resizable"),i=r.options,o=r.originalSize,s=r.originalPosition,a={height:r.size.height-o.height||0,width:r.size.width-o.width||0,top:r.position.top-s.top||0,left:r.position.left-s.left||0},l=function(t,r){e(t).each(function(){var t=e(this),i=e(this).data("ui-resizable-alsoresize"),o={},s=r&&r.length?r:t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(s,function(e,t){var n=(i[t]||0)+(a[t]||0);n&&n>=0&&(o[t]=n||null)});t.css(o)})};"object"!=typeof i.alsoResize||i.alsoResize.nodeType?l(i.alsoResize):e.each(i.alsoResize,function(e,t){l(e,t)})},stop:function(){e(this).removeData("resizable-alsoresize")}});e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size;t.ghost=t.originalElement.clone();t.ghost.css({opacity:.25,display:"block",position:"relative",height:r.height,width:r.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof n.ghost?n.ghost:"");t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).data("ui-resizable");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).data("ui-resizable");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}});e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size,i=t.originalSize,o=t.originalPosition,s=t.axis,a="number"==typeof n.grid?[n.grid,n.grid]:n.grid,l=a[0]||1,u=a[1]||1,p=Math.round((r.width-i.width)/l)*l,c=Math.round((r.height-i.height)/u)*u,d=i.width+p,h=i.height+c,f=n.maxWidth&&n.maxWidth<d,g=n.maxHeight&&n.maxHeight<h,m=n.minWidth&&n.minWidth>d,E=n.minHeight&&n.minHeight>h;n.grid=a;m&&(d+=l);E&&(h+=u);f&&(d-=l);g&&(h-=u);if(/^(se|s|e)$/.test(s)){t.size.width=d;t.size.height=h}else if(/^(ne)$/.test(s)){t.size.width=d;t.size.height=h;t.position.top=o.top-c}else if(/^(sw)$/.test(s)){t.size.width=d;t.size.height=h;t.position.left=o.left-p}else{if(h-u>0){t.size.height=h;t.position.top=o.top-c}else{t.size.height=u;t.position.top=o.top+i.height-u}if(d-l>0){t.size.width=d;t.position.left=o.left-p}else{t.size.width=l;t.position.left=o.left+i.width-l}}}})})(t)},{"./core":3,"./mouse":4,"./widget":7,jquery:void 0}],7:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();(function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n,r=0;null!=(n=t[r]);r++)try{e(n).triggerHandler("remove")}catch(o){}i(t)};e.widget=function(t,n,r){var i,o,s,a,l={},u=t.split(".")[0];t=t.split(".")[1];i=u+"-"+t;if(!r){r=n;n=e.Widget}e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)};e[u]=e[u]||{};o=e[u][t];s=e[u][t]=function(e,t){if(!this._createWidget)return new s(e,t);arguments.length&&this._createWidget(e,t);return void 0};e.extend(s,o,{version:r.version,_proto:e.extend({},r),_childConstructors:[]});a=new n;a.options=e.widget.extend({},a.options);e.each(r,function(t,r){l[t]=e.isFunction(r)?function(){var e=function(){return n.prototype[t].apply(this,arguments)},i=function(e){return n.prototype[t].apply(this,e)};return function(){var t,n=this._super,o=this._superApply;this._super=e;this._superApply=i;t=r.apply(this,arguments);this._super=n;this._superApply=o;return t}}():r});s.prototype=e.widget.extend(a,{widgetEventPrefix:o?a.widgetEventPrefix||t:t},l,{constructor:s,namespace:u,widgetName:t,widgetFullName:i});if(o){e.each(o._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,s,n._proto)});delete o._childConstructors}else n._childConstructors.push(s);e.widget.bridge(t,s)};e.widget.extend=function(n){for(var i,o,s=r.call(arguments,1),a=0,l=s.length;l>a;a++)for(i in s[a]){o=s[a][i];s[a].hasOwnProperty(i)&&o!==t&&(n[i]=e.isPlainObject(o)?e.isPlainObject(n[i])?e.widget.extend({},n[i],o):e.widget.extend({},o):o)}return n};e.widget.bridge=function(n,i){var o=i.prototype.widgetFullName||n;e.fn[n]=function(s){var a="string"==typeof s,l=r.call(arguments,1),u=this;s=!a&&l.length?e.widget.extend.apply(null,[s].concat(l)):s;this.each(a?function(){var r,i=e.data(this,o);if(!i)return e.error("cannot call methods on "+n+" prior to initialization; attempted to call method '"+s+"'");if(!e.isFunction(i[s])||"_"===s.charAt(0))return e.error("no such method '"+s+"' for "+n+" widget instance");r=i[s].apply(i,l);if(r!==i&&r!==t){u=r&&r.jquery?u.pushStack(r.get()):r;return!1}}:function(){var t=e.data(this,o);t?t.option(s||{})._init():e.data(this,o,new i(s,this))});return u}};e.Widget=function(){};e.Widget._childConstructors=[];e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0];this.element=e(r);this.uuid=n++;this.eventNamespace="."+this.widgetName+this.uuid;this.options=e.widget.extend({},this.options,this._getCreateOptions(),t);this.bindings=e();this.hoverable=e();this.focusable=e();if(r!==this){e.data(r,this.widgetFullName,this);this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}});this.document=e(r.style?r.ownerDocument:r.document||r);this.window=e(this.document[0].defaultView||this.document[0].parentWindow)}this._create();this._trigger("create",null,this._getCreateEventData());this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy();this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName));this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled");this.bindings.unbind(this.eventNamespace);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i,o,s,a=n;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof n){a={};i=n.split(".");n=i.shift();if(i.length){o=a[n]=e.widget.extend({},this.options[n]);for(s=0;s<i.length-1;s++){o[i[s]]=o[i[s]]||{};o=o[i[s]]}n=i.pop();if(1===arguments.length)return o[n]===t?null:o[n];o[n]=r}else{if(1===arguments.length)return this.options[n]===t?null:this.options[n];a[n]=r}}this._setOptions(a);return this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){this.options[e]=t;if("disabled"===e){this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")}return this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(t,n,r){var i,o=this;if("boolean"!=typeof t){r=n;n=t;t=!1}if(r){n=i=e(n);this.bindings=this.bindings.add(n)}else{r=n;n=this.element;i=this.widget()}e.each(r,function(r,s){function a(){return t||o.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof s?o[s]:s).apply(o,arguments):void 0}"string"!=typeof s&&(a.guid=s.guid=s.guid||a.guid||e.guid++);var l=r.match(/^(\w+)\s*(.*)$/),u=l[1]+o.eventNamespace,p=l[2];p?i.delegate(p,u,a):n.bind(u,a)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace;e.unbind(t).undelegate(t)},_delay:function(e,t){function n(){return("string"==typeof e?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t);this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t);this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,o,s=this.options[t];r=r||{};n=e.Event(n);n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase();n.target=this.element[0];o=n.originalEvent;if(o)for(i in o)i in n||(n[i]=o[i]);this.element.trigger(n,r);return!(e.isFunction(s)&&s.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}};e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,o){"string"==typeof i&&(i={effect:i});var s,a=i?i===!0||"number"==typeof i?n:i.effect||n:t;i=i||{};"number"==typeof i&&(i={duration:i});s=!e.isEmptyObject(i);i.complete=o;i.delay&&r.delay(i.delay);s&&e.effects&&e.effects.effect[a]?r[t](i):a!==t&&r[a]?r[a](i.duration,i.easing,o):r.queue(function(n){e(this)[t]();o&&o.call(r[0]);n()})}})})(t)},{jquery:void 0}],8:[function(t,n,r){(function(i,o){"function"==typeof e&&e.amd?e(["jquery","sifter","microplugin"],o):"object"==typeof r?n.exports=o(function(){try{return t("jquery")}catch(e){return window.jQuery}}(),t("sifter"),t("microplugin")):i.Selectize=o(i.jQuery,i.Sifter,i.MicroPlugin)})(this,function(e,t,n){"use strict";var r=function(e,t){if("string"!=typeof t||t.length){var n="string"==typeof t?new RegExp(t,"i"):t,r=function(e){var t=0;if(3===e.nodeType){var i=e.data.search(n);if(i>=0&&e.data.length>0){var o=e.data.match(n),s=document.createElement("span");s.className="highlight";var a=e.splitText(i),l=(a.splitText(o[0].length),a.cloneNode(!0));s.appendChild(l);a.parentNode.replaceChild(s,a);t=1}}else if(1===e.nodeType&&e.childNodes&&!/(script|style)/i.test(e.tagName))for(var u=0;u<e.childNodes.length;++u)u+=r(e.childNodes[u]);return t};return e.each(function(){r(this)})}},i=function(){};i.prototype={on:function(e,t){this._events=this._events||{};this._events[e]=this._events[e]||[];this._events[e].push(t)},off:function(e,t){var n=arguments.length;if(0===n)return delete this._events;if(1===n)return delete this._events[e];this._events=this._events||{};e in this._events!=!1&&this._events[e].splice(this._events[e].indexOf(t),1)},trigger:function(e){this._events=this._events||{};if(e in this._events!=!1)for(var t=0;t<this._events[e].length;t++)this._events[e][t].apply(this,Array.prototype.slice.call(arguments,1))}};i.mixin=function(e){for(var t=["on","off","trigger"],n=0;n<t.length;n++)e.prototype[t[n]]=i.prototype[t[n]]};var o=/Mac/.test(navigator.userAgent),s=65,a=13,l=27,u=37,p=38,c=80,d=39,h=40,f=78,g=8,m=46,E=16,v=o?91:17,x=o?18:17,y=9,N=1,I=2,A=!/android/i.test(window.navigator.userAgent)&&!!document.createElement("form").validity,T=function(e){return"undefined"!=typeof e},L=function(e){return"undefined"==typeof e||null===e?null:"boolean"==typeof e?e?"1":"0":e+""},S=function(e){return(e+"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")},b=function(e){return(e+"").replace(/\$/g,"$$$$")},C={};C.before=function(e,t,n){var r=e[t];e[t]=function(){n.apply(e,arguments);return r.apply(e,arguments)}};C.after=function(e,t,n){var r=e[t];e[t]=function(){var t=r.apply(e,arguments);n.apply(e,arguments);return t}};var R=function(e){var t=!1;return function(){if(!t){t=!0;e.apply(this,arguments)}}},w=function(e,t){var n;return function(){var r=this,i=arguments;window.clearTimeout(n);n=window.setTimeout(function(){e.apply(r,i)},t)}},O=function(e,t,n){var r,i=e.trigger,o={};e.trigger=function(){var n=arguments[0];if(-1===t.indexOf(n))return i.apply(e,arguments);o[n]=arguments;return void 0};n.apply(e,[]);e.trigger=i;for(r in o)o.hasOwnProperty(r)&&i.apply(e,o[r])},_=function(e,t,n,r){e.on(t,n,function(t){for(var n=t.target;n&&n.parentNode!==e[0];)n=n.parentNode;t.currentTarget=n;return r.apply(this,[t])})},F=function(e){var t={};if("selectionStart"in e){t.start=e.selectionStart;t.length=e.selectionEnd-t.start}else if(document.selection){e.focus();var n=document.selection.createRange(),r=document.selection.createRange().text.length;n.moveStart("character",-e.value.length);t.start=n.text.length-r;t.length=r}return t},P=function(e,t,n){var r,i,o={};if(n)for(r=0,i=n.length;i>r;r++)o[n[r]]=e.css(n[r]);else o=e.css();t.css(o)},k=function(t,n){if(!t)return 0;var r=e("<test>").css({position:"absolute",top:-99999,left:-99999,width:"auto",padding:0,whiteSpace:"pre"}).text(t).appendTo("body");P(n,r,["letterSpacing","fontSize","fontFamily","fontWeight","textTransform"]);var i=r.width();r.remove();return i},M=function(e){var t=null,n=function(n,r){var i,o,s,a,l,u,p,c;n=n||window.event||{};r=r||{};if(!n.metaKey&&!n.altKey&&(r.force||e.data("grow")!==!1)){i=e.val();if(n.type&&"keydown"===n.type.toLowerCase()){o=n.keyCode;s=o>=97&&122>=o||o>=65&&90>=o||o>=48&&57>=o||32===o;if(o===m||o===g){c=F(e[0]);c.length?i=i.substring(0,c.start)+i.substring(c.start+c.length):o===g&&c.start?i=i.substring(0,c.start-1)+i.substring(c.start+1):o===m&&"undefined"!=typeof c.start&&(i=i.substring(0,c.start)+i.substring(c.start+1))}else if(s){u=n.shiftKey;p=String.fromCharCode(n.keyCode);p=u?p.toUpperCase():p.toLowerCase();i+=p}}a=e.attr("placeholder");!i&&a&&(i=a);l=k(i,e)+4;if(l!==t){t=l;e.width(l);e.triggerHandler("resize")}}};e.on("keydown keyup update blur",n);n()},D=function(n,r){var i,o,s,a,l=this;a=n[0];a.selectize=l;var u=window.getComputedStyle&&window.getComputedStyle(a,null);s=u?u.getPropertyValue("direction"):a.currentStyle&&a.currentStyle.direction;s=s||n.parents("[dir]:first").attr("dir")||"";e.extend(l,{order:0,settings:r,$input:n,tabIndex:n.attr("tabindex")||"",tagType:"select"===a.tagName.toLowerCase()?N:I,rtl:/rtl/i.test(s),eventNS:".selectize"+ ++D.count,highlightedValue:null,isOpen:!1,isDisabled:!1,isRequired:n.is("[required]"),isInvalid:!1,isLocked:!1,isFocused:!1,isInputHidden:!1,isSetup:!1,isShiftDown:!1,isCmdDown:!1,isCtrlDown:!1,ignoreFocus:!1,ignoreBlur:!1,ignoreHover:!1,hasOptions:!1,currentResults:null,lastValue:"",caretPos:0,loading:0,loadedSearches:{},$activeOption:null,$activeItems:[],optgroups:{},options:{},userOptions:{},items:[],renderCache:{},onSearchChange:null===r.loadThrottle?l.onSearchChange:w(l.onSearchChange,r.loadThrottle)});l.sifter=new t(this.options,{diacritics:r.diacritics});if(l.settings.options){for(i=0,o=l.settings.options.length;o>i;i++)l.registerOption(l.settings.options[i]);delete l.settings.options}if(l.settings.optgroups){for(i=0,o=l.settings.optgroups.length;o>i;i++)l.registerOptionGroup(l.settings.optgroups[i]);delete l.settings.optgroups}l.settings.mode=l.settings.mode||(1===l.settings.maxItems?"single":"multi");"boolean"!=typeof l.settings.hideSelected&&(l.settings.hideSelected="multi"===l.settings.mode);l.initializePlugins(l.settings.plugins);l.setupCallbacks();l.setupTemplates();l.setup()};i.mixin(D);n.mixin(D);e.extend(D.prototype,{setup:function(){var t,n,r,i,s,a,l,u,p,c=this,d=c.settings,h=c.eventNS,f=e(window),g=e(document),m=c.$input;l=c.settings.mode;u=m.attr("class")||"";t=e("<div>").addClass(d.wrapperClass).addClass(u).addClass(l);n=e("<div>").addClass(d.inputClass).addClass("items").appendTo(t);r=e('<input type="text" autocomplete="off" />').appendTo(n).attr("tabindex",m.is(":disabled")?"-1":c.tabIndex);a=e(d.dropdownParent||t);i=e("<div>").addClass(d.dropdownClass).addClass(l).hide().appendTo(a);s=e("<div>").addClass(d.dropdownContentClass).appendTo(i);c.settings.copyClassesToDropdown&&i.addClass(u);t.css({width:m[0].style.width});if(c.plugins.names.length){p="plugin-"+c.plugins.names.join(" plugin-");t.addClass(p);i.addClass(p)}(null===d.maxItems||d.maxItems>1)&&c.tagType===N&&m.attr("multiple","multiple");c.settings.placeholder&&r.attr("placeholder",d.placeholder);if(!c.settings.splitOn&&c.settings.delimiter){var y=c.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c.settings.splitOn=new RegExp("\\s*"+y+"+\\s*")}m.attr("autocorrect")&&r.attr("autocorrect",m.attr("autocorrect"));m.attr("autocapitalize")&&r.attr("autocapitalize",m.attr("autocapitalize"));c.$wrapper=t;c.$control=n;c.$control_input=r;c.$dropdown=i;c.$dropdown_content=s;i.on("mouseenter","[data-selectable]",function(){return c.onOptionHover.apply(c,arguments)});i.on("mousedown click","[data-selectable]",function(){return c.onOptionSelect.apply(c,arguments)});_(n,"mousedown","*:not(input)",function(){return c.onItemSelect.apply(c,arguments)});M(r);n.on({mousedown:function(){return c.onMouseDown.apply(c,arguments)},click:function(){return c.onClick.apply(c,arguments)}});r.on({mousedown:function(e){e.stopPropagation()},keydown:function(){return c.onKeyDown.apply(c,arguments)},keyup:function(){return c.onKeyUp.apply(c,arguments)},keypress:function(){return c.onKeyPress.apply(c,arguments)},resize:function(){c.positionDropdown.apply(c,[])},blur:function(){return c.onBlur.apply(c,arguments)},focus:function(){c.ignoreBlur=!1;return c.onFocus.apply(c,arguments)},paste:function(){return c.onPaste.apply(c,arguments)}});g.on("keydown"+h,function(e){c.isCmdDown=e[o?"metaKey":"ctrlKey"];c.isCtrlDown=e[o?"altKey":"ctrlKey"];c.isShiftDown=e.shiftKey});g.on("keyup"+h,function(e){e.keyCode===x&&(c.isCtrlDown=!1);e.keyCode===E&&(c.isShiftDown=!1);e.keyCode===v&&(c.isCmdDown=!1)});g.on("mousedown"+h,function(e){if(c.isFocused){if(e.target===c.$dropdown[0]||e.target.parentNode===c.$dropdown[0])return!1;c.$control.has(e.target).length||e.target===c.$control[0]||c.blur(e.target)}});f.on(["scroll"+h,"resize"+h].join(" "),function(){c.isOpen&&c.positionDropdown.apply(c,arguments)});f.on("mousemove"+h,function(){c.ignoreHover=!1});this.revertSettings={$children:m.children().detach(),tabindex:m.attr("tabindex")};m.attr("tabindex",-1).hide().after(c.$wrapper);if(e.isArray(d.items)){c.setValue(d.items);delete d.items}A&&m.on("invalid"+h,function(e){e.preventDefault();c.isInvalid=!0;c.refreshState()});c.updateOriginalInput();c.refreshItems();c.refreshState();c.updatePlaceholder();c.isSetup=!0;m.is(":disabled")&&c.disable();c.on("change",this.onChange);m.data("selectize",c);m.addClass("selectized");c.trigger("initialize");d.preload===!0&&c.onSearchChange("")},setupTemplates:function(){var t=this,n=t.settings.labelField,r=t.settings.optgroupLabelField,i={optgroup:function(e){return'<div class="optgroup">'+e.html+"</div>"},optgroup_header:function(e,t){return'<div class="optgroup-header">'+t(e[r])+"</div>"},option:function(e,t){return'<div class="option">'+t(e[n])+"</div>"},item:function(e,t){return'<div class="item">'+t(e[n])+"</div>"},option_create:function(e,t){return'<div class="create">Add <strong>'+t(e.input)+"</strong>…</div>"}};t.settings.render=e.extend({},i,t.settings.render)},setupCallbacks:function(){var e,t,n={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",optgroup_add:"onOptionGroupAdd",optgroup_remove:"onOptionGroupRemove",optgroup_clear:"onOptionGroupClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad",focus:"onFocus",blur:"onBlur"};for(e in n)if(n.hasOwnProperty(e)){t=this.settings[n[e]];t&&this.on(e,t)}},onClick:function(e){var t=this;if(!t.isFocused){t.focus();e.preventDefault()}},onMouseDown:function(t){{var n=this,r=t.isDefaultPrevented();e(t.target)}if(n.isFocused){if(t.target!==n.$control_input[0]){"single"===n.settings.mode?n.isOpen?n.close():n.open():r||n.setActiveItem(null);return!1}}else r||window.setTimeout(function(){n.focus()},0)},onChange:function(){this.$input.trigger("change")},onPaste:function(t){var n=this;n.isFull()||n.isInputHidden||n.isLocked?t.preventDefault():n.settings.splitOn&&setTimeout(function(){for(var t=e.trim(n.$control_input.val()||"").split(n.settings.splitOn),r=0,i=t.length;i>r;r++)n.createItem(t[r])},0)},onKeyPress:function(e){if(this.isLocked)return e&&e.preventDefault();var t=String.fromCharCode(e.keyCode||e.which);if(this.settings.create&&"multi"===this.settings.mode&&t===this.settings.delimiter){this.createItem();e.preventDefault();return!1}},onKeyDown:function(e){var t=(e.target===this.$control_input[0],this);if(t.isLocked)e.keyCode!==y&&e.preventDefault();else{switch(e.keyCode){case s:if(t.isCmdDown){t.selectAll();return}break;case l:if(t.isOpen){e.preventDefault();e.stopPropagation();t.close()}return;case f:if(!e.ctrlKey||e.altKey)break;case h:if(!t.isOpen&&t.hasOptions)t.open();else if(t.$activeOption){t.ignoreHover=!0;var n=t.getAdjacentOption(t.$activeOption,1);n.length&&t.setActiveOption(n,!0,!0)}e.preventDefault();return;case c:if(!e.ctrlKey||e.altKey)break;case p:if(t.$activeOption){t.ignoreHover=!0;var r=t.getAdjacentOption(t.$activeOption,-1);r.length&&t.setActiveOption(r,!0,!0)}e.preventDefault();return;case a:if(t.isOpen&&t.$activeOption){t.onOptionSelect({currentTarget:t.$activeOption});e.preventDefault()}return;case u:t.advanceSelection(-1,e);return;case d:t.advanceSelection(1,e);return;case y:if(t.settings.selectOnTab&&t.isOpen&&t.$activeOption){t.onOptionSelect({currentTarget:t.$activeOption});t.isFull()||e.preventDefault()}t.settings.create&&t.createItem()&&e.preventDefault();return;case g:case m:t.deleteSelection(e);return}!t.isFull()&&!t.isInputHidden||(o?e.metaKey:e.ctrlKey)||e.preventDefault()}},onKeyUp:function(e){var t=this;if(t.isLocked)return e&&e.preventDefault();var n=t.$control_input.val()||"";if(t.lastValue!==n){t.lastValue=n;t.onSearchChange(n);t.refreshOptions();t.trigger("type",n)}},onSearchChange:function(e){var t=this,n=t.settings.load;if(n&&!t.loadedSearches.hasOwnProperty(e)){t.loadedSearches[e]=!0;t.load(function(r){n.apply(t,[e,r])})}},onFocus:function(e){var t=this,n=t.isFocused;if(t.isDisabled){t.blur();e&&e.preventDefault();return!1}if(!t.ignoreFocus){t.isFocused=!0;"focus"===t.settings.preload&&t.onSearchChange("");n||t.trigger("focus");if(!t.$activeItems.length){t.showInput();t.setActiveItem(null);t.refreshOptions(!!t.settings.openOnFocus)}t.refreshState()}},onBlur:function(e,t){var n=this;if(n.isFocused){n.isFocused=!1;if(!n.ignoreFocus)if(n.ignoreBlur||document.activeElement!==n.$dropdown_content[0]){var r=function(){n.close();n.setTextboxValue("");n.setActiveItem(null);n.setActiveOption(null);n.setCaret(n.items.length);n.refreshState();(t||document.body).focus();n.ignoreFocus=!1;n.trigger("blur")};n.ignoreFocus=!0;n.settings.create&&n.settings.createOnBlur?n.createItem(null,!1,r):r()}else{n.ignoreBlur=!0;n.onFocus(e)}}},onOptionHover:function(e){this.ignoreHover||this.setActiveOption(e.currentTarget,!1)},onOptionSelect:function(t){var n,r,i=this;if(t.preventDefault){t.preventDefault();t.stopPropagation()}r=e(t.currentTarget);if(r.hasClass("create"))i.createItem(null,function(){i.settings.closeAfterSelect&&i.close()});else{n=r.attr("data-value");if("undefined"!=typeof n){i.lastQuery=null;i.setTextboxValue("");i.addItem(n);i.settings.closeAfterSelect?i.close():!i.settings.hideSelected&&t.type&&/mouse/.test(t.type)&&i.setActiveOption(i.getOption(n))}}},onItemSelect:function(e){var t=this;if(!t.isLocked&&"multi"===t.settings.mode){e.preventDefault();t.setActiveItem(e.currentTarget,e)}},load:function(e){var t=this,n=t.$wrapper.addClass(t.settings.loadingClass);t.loading++;e.apply(t,[function(e){t.loading=Math.max(t.loading-1,0);if(e&&e.length){t.addOption(e);t.refreshOptions(t.isFocused&&!t.isInputHidden)}t.loading||n.removeClass(t.settings.loadingClass);t.trigger("load",e)}])},setTextboxValue:function(e){var t=this.$control_input,n=t.val()!==e;if(n){t.val(e).triggerHandler("update");this.lastValue=e}},getValue:function(){return this.tagType===N&&this.$input.attr("multiple")?this.items:this.items.join(this.settings.delimiter)},setValue:function(e,t){var n=t?[]:["change"];O(this,n,function(){this.clear();this.addItems(e,t)})},setActiveItem:function(t,n){var r,i,o,s,a,l,u,p,c=this;if("single"!==c.settings.mode){t=e(t);if(t.length){r=n&&n.type.toLowerCase();if("mousedown"===r&&c.isShiftDown&&c.$activeItems.length){p=c.$control.children(".active:last");s=Array.prototype.indexOf.apply(c.$control[0].childNodes,[p[0]]);a=Array.prototype.indexOf.apply(c.$control[0].childNodes,[t[0]]);if(s>a){u=s;s=a;a=u}for(i=s;a>=i;i++){l=c.$control[0].childNodes[i];if(-1===c.$activeItems.indexOf(l)){e(l).addClass("active");c.$activeItems.push(l)}}n.preventDefault()}else if("mousedown"===r&&c.isCtrlDown||"keydown"===r&&this.isShiftDown)if(t.hasClass("active")){o=c.$activeItems.indexOf(t[0]);c.$activeItems.splice(o,1);t.removeClass("active")}else c.$activeItems.push(t.addClass("active")[0]);else{e(c.$activeItems).removeClass("active");c.$activeItems=[t.addClass("active")[0]]}c.hideInput();this.isFocused||c.focus()}else{e(c.$activeItems).removeClass("active");c.$activeItems=[];c.isFocused&&c.showInput()}}},setActiveOption:function(t,n,r){var i,o,s,a,l,u=this;u.$activeOption&&u.$activeOption.removeClass("active");u.$activeOption=null;t=e(t);if(t.length){u.$activeOption=t.addClass("active");if(n||!T(n)){i=u.$dropdown_content.height();o=u.$activeOption.outerHeight(!0);n=u.$dropdown_content.scrollTop()||0;s=u.$activeOption.offset().top-u.$dropdown_content.offset().top+n;a=s;l=s-i+o;s+o>i+n?u.$dropdown_content.stop().animate({scrollTop:l},r?u.settings.scrollDuration:0):n>s&&u.$dropdown_content.stop().animate({scrollTop:a},r?u.settings.scrollDuration:0)}}},selectAll:function(){var e=this;if("single"!==e.settings.mode){e.$activeItems=Array.prototype.slice.apply(e.$control.children(":not(input)").addClass("active"));if(e.$activeItems.length){e.hideInput();e.close()}e.focus()}},hideInput:function(){var e=this;e.setTextboxValue("");e.$control_input.css({opacity:0,position:"absolute",left:e.rtl?1e4:-1e4});e.isInputHidden=!0},showInput:function(){this.$control_input.css({opacity:1,position:"relative",left:0});this.isInputHidden=!1},focus:function(){var e=this;if(!e.isDisabled){e.ignoreFocus=!0;e.$control_input[0].focus();window.setTimeout(function(){e.ignoreFocus=!1;e.onFocus()},0)}},blur:function(e){this.$control_input[0].blur();this.onBlur(null,e)},getScoreFunction:function(e){return this.sifter.getScoreFunction(e,this.getSearchOptions())},getSearchOptions:function(){var e=this.settings,t=e.sortField;"string"==typeof t&&(t=[{field:t}]);return{fields:e.searchField,conjunction:e.searchConjunction,sort:t}},search:function(t){var n,r,i,o=this,s=o.settings,a=this.getSearchOptions();if(s.score){i=o.settings.score.apply(this,[t]);if("function"!=typeof i)throw new Error('Selectize "score" setting must be a function that returns a function')}if(t!==o.lastQuery){o.lastQuery=t;r=o.sifter.search(t,e.extend(a,{score:i}));o.currentResults=r}else r=e.extend(!0,{},o.currentResults);if(s.hideSelected)for(n=r.items.length-1;n>=0;n--)-1!==o.items.indexOf(L(r.items[n].id))&&r.items.splice(n,1);return r},refreshOptions:function(t){var n,i,o,s,a,l,u,p,c,d,h,f,g,m,E,v;"undefined"==typeof t&&(t=!0);var x=this,y=e.trim(x.$control_input.val()),N=x.search(y),I=x.$dropdown_content,A=x.$activeOption&&L(x.$activeOption.attr("data-value"));s=N.items.length;"number"==typeof x.settings.maxOptions&&(s=Math.min(s,x.settings.maxOptions));a={};l=[];for(n=0;s>n;n++){u=x.options[N.items[n].id];p=x.render("option",u);c=u[x.settings.optgroupField]||"";d=e.isArray(c)?c:[c];for(i=0,o=d&&d.length;o>i;i++){c=d[i];x.optgroups.hasOwnProperty(c)||(c="");if(!a.hasOwnProperty(c)){a[c]=[];l.push(c)}a[c].push(p)}}this.settings.lockOptgroupOrder&&l.sort(function(e,t){var n=x.optgroups[e].$order||0,r=x.optgroups[t].$order||0;return n-r});h=[];for(n=0,s=l.length;s>n;n++){c=l[n];if(x.optgroups.hasOwnProperty(c)&&a[c].length){f=x.render("optgroup_header",x.optgroups[c])||"";f+=a[c].join("");h.push(x.render("optgroup",e.extend({},x.optgroups[c],{html:f})))}else h.push(a[c].join(""))}I.html(h.join(""));if(x.settings.highlight&&N.query.length&&N.tokens.length)for(n=0,s=N.tokens.length;s>n;n++)r(I,N.tokens[n].regex);if(!x.settings.hideSelected)for(n=0,s=x.items.length;s>n;n++)x.getOption(x.items[n]).addClass("selected");g=x.canCreate(y);if(g){I.prepend(x.render("option_create",{input:y}));v=e(I[0].childNodes[0])}x.hasOptions=N.items.length>0||g;if(x.hasOptions){if(N.items.length>0){E=A&&x.getOption(A);E&&E.length?m=E:"single"===x.settings.mode&&x.items.length&&(m=x.getOption(x.items[0]));m&&m.length||(m=v&&!x.settings.addPrecedence?x.getAdjacentOption(v,1):I.find("[data-selectable]:first"))}else m=v;x.setActiveOption(m);t&&!x.isOpen&&x.open()}else{x.setActiveOption(null);t&&x.isOpen&&x.close()}},addOption:function(t){var n,r,i,o=this;if(e.isArray(t))for(n=0,r=t.length;r>n;n++)o.addOption(t[n]);else if(i=o.registerOption(t)){o.userOptions[i]=!0;o.lastQuery=null;o.trigger("option_add",i,t)}},registerOption:function(e){var t=L(e[this.settings.valueField]);if(!t||this.options.hasOwnProperty(t))return!1;e.$order=e.$order||++this.order;this.options[t]=e;return t},registerOptionGroup:function(e){var t=L(e[this.settings.optgroupValueField]);if(!t)return!1;e.$order=e.$order||++this.order;this.optgroups[t]=e;return t},addOptionGroup:function(e,t){t[this.settings.optgroupValueField]=e;(e=this.registerOptionGroup(t))&&this.trigger("optgroup_add",e,t)},removeOptionGroup:function(e){if(this.optgroups.hasOwnProperty(e)){delete this.optgroups[e];this.renderCache={};this.trigger("optgroup_remove",e)}},clearOptionGroups:function(){this.optgroups={};this.renderCache={};this.trigger("optgroup_clear")},updateOption:function(t,n){var r,i,o,s,a,l,u,p=this;t=L(t);o=L(n[p.settings.valueField]);if(null!==t&&p.options.hasOwnProperty(t)){if("string"!=typeof o)throw new Error("Value must be set in option data");u=p.options[t].$order;if(o!==t){delete p.options[t];s=p.items.indexOf(t);-1!==s&&p.items.splice(s,1,o)}n.$order=n.$order||u;p.options[o]=n;a=p.renderCache.item;l=p.renderCache.option;if(a){delete a[t];delete a[o]}if(l){delete l[t];delete l[o]}if(-1!==p.items.indexOf(o)){r=p.getItem(t);i=e(p.render("item",n));r.hasClass("active")&&i.addClass("active");r.replaceWith(i)}p.lastQuery=null;p.isOpen&&p.refreshOptions(!1)}},removeOption:function(e,t){var n=this;e=L(e);var r=n.renderCache.item,i=n.renderCache.option;r&&delete r[e];i&&delete i[e];delete n.userOptions[e];delete n.options[e];n.lastQuery=null;n.trigger("option_remove",e);n.removeItem(e,t)},clearOptions:function(){var e=this;e.loadedSearches={};e.userOptions={};e.renderCache={};e.options=e.sifter.items={};e.lastQuery=null;e.trigger("option_clear");e.clear()},getOption:function(e){return this.getElementWithValue(e,this.$dropdown_content.find("[data-selectable]"))},getAdjacentOption:function(t,n){var r=this.$dropdown.find("[data-selectable]"),i=r.index(t)+n;return i>=0&&i<r.length?r.eq(i):e()},getElementWithValue:function(t,n){t=L(t);if("undefined"!=typeof t&&null!==t)for(var r=0,i=n.length;i>r;r++)if(n[r].getAttribute("data-value")===t)return e(n[r]);return e()},getItem:function(e){return this.getElementWithValue(e,this.$control.children())},addItems:function(t,n){for(var r=e.isArray(t)?t:[t],i=0,o=r.length;o>i;i++){this.isPending=o-1>i;this.addItem(r[i],n)}},addItem:function(t,n){var r=n?[]:["change"];O(this,r,function(){var r,i,o,s,a,l=this,u=l.settings.mode;
t=L(t);if(-1===l.items.indexOf(t)){if(l.options.hasOwnProperty(t)){"single"===u&&l.clear();if("multi"!==u||!l.isFull()){r=e(l.render("item",l.options[t]));a=l.isFull();l.items.splice(l.caretPos,0,t);l.insertAtCaret(r);(!l.isPending||!a&&l.isFull())&&l.refreshState();if(l.isSetup){o=l.$dropdown_content.find("[data-selectable]");if(!l.isPending){i=l.getOption(t);s=l.getAdjacentOption(i,1).attr("data-value");l.refreshOptions(l.isFocused&&"single"!==u);s&&l.setActiveOption(l.getOption(s))}!o.length||l.isFull()?l.close():l.positionDropdown();l.updatePlaceholder();l.trigger("item_add",t,r);l.updateOriginalInput({silent:n})}}}}else"single"===u&&l.close()})},removeItem:function(e,t){var n,r,i,o=this;n="object"==typeof e?e:o.getItem(e);e=L(n.attr("data-value"));r=o.items.indexOf(e);if(-1!==r){n.remove();if(n.hasClass("active")){i=o.$activeItems.indexOf(n[0]);o.$activeItems.splice(i,1)}o.items.splice(r,1);o.lastQuery=null;!o.settings.persist&&o.userOptions.hasOwnProperty(e)&&o.removeOption(e,t);r<o.caretPos&&o.setCaret(o.caretPos-1);o.refreshState();o.updatePlaceholder();o.updateOriginalInput({silent:t});o.positionDropdown();o.trigger("item_remove",e,n)}},createItem:function(t,n){var r=this,i=r.caretPos;t=t||e.trim(r.$control_input.val()||"");var o=arguments[arguments.length-1];"function"!=typeof o&&(o=function(){});"boolean"!=typeof n&&(n=!0);if(!r.canCreate(t)){o();return!1}r.lock();var s="function"==typeof r.settings.create?this.settings.create:function(e){var t={};t[r.settings.labelField]=e;t[r.settings.valueField]=e;return t},a=R(function(e){r.unlock();if(!e||"object"!=typeof e)return o();var t=L(e[r.settings.valueField]);if("string"!=typeof t)return o();r.setTextboxValue("");r.addOption(e);r.setCaret(i);r.addItem(t);r.refreshOptions(n&&"single"!==r.settings.mode);o(e)}),l=s.apply(this,[t,a]);"undefined"!=typeof l&&a(l);return!0},refreshItems:function(){this.lastQuery=null;this.isSetup&&this.addItem(this.items);this.refreshState();this.updateOriginalInput()},refreshState:function(){var e,t=this;if(t.isRequired){t.items.length&&(t.isInvalid=!1);t.$control_input.prop("required",e)}t.refreshClasses()},refreshClasses:function(){var t=this,n=t.isFull(),r=t.isLocked;t.$wrapper.toggleClass("rtl",t.rtl);t.$control.toggleClass("focus",t.isFocused).toggleClass("disabled",t.isDisabled).toggleClass("required",t.isRequired).toggleClass("invalid",t.isInvalid).toggleClass("locked",r).toggleClass("full",n).toggleClass("not-full",!n).toggleClass("input-active",t.isFocused&&!t.isInputHidden).toggleClass("dropdown-active",t.isOpen).toggleClass("has-options",!e.isEmptyObject(t.options)).toggleClass("has-items",t.items.length>0);t.$control_input.data("grow",!n&&!r)},isFull:function(){return null!==this.settings.maxItems&&this.items.length>=this.settings.maxItems},updateOriginalInput:function(e){var t,n,r,i,o=this;e=e||{};if(o.tagType===N){r=[];for(t=0,n=o.items.length;n>t;t++){i=o.options[o.items[t]][o.settings.labelField]||"";r.push('<option value="'+S(o.items[t])+'" selected="selected">'+S(i)+"</option>")}r.length||this.$input.attr("multiple")||r.push('<option value="" selected="selected"></option>');o.$input.html(r.join(""))}else{o.$input.val(o.getValue());o.$input.attr("value",o.$input.val())}o.isSetup&&(e.silent||o.trigger("change",o.$input.val()))},updatePlaceholder:function(){if(this.settings.placeholder){var e=this.$control_input;this.items.length?e.removeAttr("placeholder"):e.attr("placeholder",this.settings.placeholder);e.triggerHandler("update",{force:!0})}},open:function(){var e=this;if(!(e.isLocked||e.isOpen||"multi"===e.settings.mode&&e.isFull())){e.focus();e.isOpen=!0;e.refreshState();e.$dropdown.css({visibility:"hidden",display:"block"});e.positionDropdown();e.$dropdown.css({visibility:"visible"});e.trigger("dropdown_open",e.$dropdown)}},close:function(){var e=this,t=e.isOpen;"single"===e.settings.mode&&e.items.length&&e.hideInput();e.isOpen=!1;e.$dropdown.hide();e.setActiveOption(null);e.refreshState();t&&e.trigger("dropdown_close",e.$dropdown)},positionDropdown:function(){var e=this.$control,t="body"===this.settings.dropdownParent?e.offset():e.position();t.top+=e.outerHeight(!0);this.$dropdown.css({width:e.outerWidth(),top:t.top,left:t.left})},clear:function(e){var t=this;if(t.items.length){t.$control.children(":not(input)").remove();t.items=[];t.lastQuery=null;t.setCaret(0);t.setActiveItem(null);t.updatePlaceholder();t.updateOriginalInput({silent:e});t.refreshState();t.showInput();t.trigger("clear")}},insertAtCaret:function(t){var n=Math.min(this.caretPos,this.items.length);0===n?this.$control.prepend(t):e(this.$control[0].childNodes[n]).before(t);this.setCaret(n+1)},deleteSelection:function(t){var n,r,i,o,s,a,l,u,p,c=this;i=t&&t.keyCode===g?-1:1;o=F(c.$control_input[0]);c.$activeOption&&!c.settings.hideSelected&&(l=c.getAdjacentOption(c.$activeOption,-1).attr("data-value"));s=[];if(c.$activeItems.length){p=c.$control.children(".active:"+(i>0?"last":"first"));a=c.$control.children(":not(input)").index(p);i>0&&a++;for(n=0,r=c.$activeItems.length;r>n;n++)s.push(e(c.$activeItems[n]).attr("data-value"));if(t){t.preventDefault();t.stopPropagation()}}else(c.isFocused||"single"===c.settings.mode)&&c.items.length&&(0>i&&0===o.start&&0===o.length?s.push(c.items[c.caretPos-1]):i>0&&o.start===c.$control_input.val().length&&s.push(c.items[c.caretPos]));if(!s.length||"function"==typeof c.settings.onDelete&&c.settings.onDelete.apply(c,[s])===!1)return!1;"undefined"!=typeof a&&c.setCaret(a);for(;s.length;)c.removeItem(s.pop());c.showInput();c.positionDropdown();c.refreshOptions(!0);if(l){u=c.getOption(l);u.length&&c.setActiveOption(u)}return!0},advanceSelection:function(e,t){var n,r,i,o,s,a,l=this;if(0!==e){l.rtl&&(e*=-1);n=e>0?"last":"first";r=F(l.$control_input[0]);if(l.isFocused&&!l.isInputHidden){o=l.$control_input.val().length;s=0>e?0===r.start&&0===r.length:r.start===o;s&&!o&&l.advanceCaret(e,t)}else{a=l.$control.children(".active:"+n);if(a.length){i=l.$control.children(":not(input)").index(a);l.setActiveItem(null);l.setCaret(e>0?i+1:i)}}}},advanceCaret:function(e,t){var n,r,i=this;if(0!==e){n=e>0?"next":"prev";if(i.isShiftDown){r=i.$control_input[n]();if(r.length){i.hideInput();i.setActiveItem(r);t&&t.preventDefault()}}else i.setCaret(i.caretPos+e)}},setCaret:function(t){var n=this;t="single"===n.settings.mode?n.items.length:Math.max(0,Math.min(n.items.length,t));if(!n.isPending){var r,i,o,s;o=n.$control.children(":not(input)");for(r=0,i=o.length;i>r;r++){s=e(o[r]).detach();t>r?n.$control_input.before(s):n.$control.append(s)}}n.caretPos=t},lock:function(){this.close();this.isLocked=!0;this.refreshState()},unlock:function(){this.isLocked=!1;this.refreshState()},disable:function(){var e=this;e.$input.prop("disabled",!0);e.$control_input.prop("disabled",!0).prop("tabindex",-1);e.isDisabled=!0;e.lock()},enable:function(){var e=this;e.$input.prop("disabled",!1);e.$control_input.prop("disabled",!1).prop("tabindex",e.tabIndex);e.isDisabled=!1;e.unlock()},destroy:function(){var t=this,n=t.eventNS,r=t.revertSettings;t.trigger("destroy");t.off();t.$wrapper.remove();t.$dropdown.remove();t.$input.html("").append(r.$children).removeAttr("tabindex").removeClass("selectized").attr({tabindex:r.tabindex}).show();t.$control_input.removeData("grow");t.$input.removeData("selectize");e(window).off(n);e(document).off(n);e(document.body).off(n);delete t.$input[0].selectize},render:function(e,t){var n,r,i="",o=!1,s=this,a=/^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;if("option"===e||"item"===e){n=L(t[s.settings.valueField]);o=!!n}if(o){T(s.renderCache[e])||(s.renderCache[e]={});if(s.renderCache[e].hasOwnProperty(n))return s.renderCache[e][n]}i=s.settings.render[e].apply(this,[t,S]);("option"===e||"option_create"===e)&&(i=i.replace(a,"<$1 data-selectable"));if("optgroup"===e){r=t[s.settings.optgroupValueField]||"";i=i.replace(a,'<$1 data-group="'+b(S(r))+'"')}("option"===e||"item"===e)&&(i=i.replace(a,'<$1 data-value="'+b(S(n||""))+'"'));o&&(s.renderCache[e][n]=i);return i},clearCache:function(e){var t=this;"undefined"==typeof e?t.renderCache={}:delete t.renderCache[e]},canCreate:function(e){var t=this;if(!t.settings.create)return!1;var n=t.settings.createFilter;return!(!e.length||"function"==typeof n&&!n.apply(t,[e])||"string"==typeof n&&!new RegExp(n).test(e)||n instanceof RegExp&&!n.test(e))}});D.count=0;D.defaults={options:[],optgroups:[],plugins:[],delimiter:",",splitOn:null,persist:!0,diacritics:!0,create:!1,createOnBlur:!1,createFilter:null,highlight:!0,openOnFocus:!0,maxOptions:1e3,maxItems:null,hideSelected:null,addPrecedence:!1,selectOnTab:!1,preload:!1,allowEmptyOption:!1,closeAfterSelect:!1,scrollDuration:60,loadThrottle:300,loadingClass:"loading",dataAttr:"data-data",optgroupField:"optgroup",valueField:"value",labelField:"text",optgroupLabelField:"label",optgroupValueField:"value",lockOptgroupOrder:!1,sortField:"$order",searchField:["text"],searchConjunction:"and",mode:null,wrapperClass:"selectize-control",inputClass:"selectize-input",dropdownClass:"selectize-dropdown",dropdownContentClass:"selectize-dropdown-content",dropdownParent:null,copyClassesToDropdown:!0,render:{}};e.fn.selectize=function(t){var n=e.fn.selectize.defaults,r=e.extend({},n,t),i=r.dataAttr,o=r.labelField,s=r.valueField,a=r.optgroupField,l=r.optgroupLabelField,u=r.optgroupValueField,p={},c=function(t,n){var a,l,u,p,c=t.attr(i);if(c){n.options=JSON.parse(c);for(a=0,l=n.options.length;l>a;a++)n.items.push(n.options[a][s])}else{var d=e.trim(t.val()||"");if(!r.allowEmptyOption&&!d.length)return;u=d.split(r.delimiter);for(a=0,l=u.length;l>a;a++){p={};p[o]=u[a];p[s]=u[a];n.options.push(p)}n.items=u}},d=function(t,n){var c,d,h,f,g=n.options,m=function(e){var t=i&&e.attr(i);return"string"==typeof t&&t.length?JSON.parse(t):null},E=function(t,i){t=e(t);var l=L(t.attr("value"));if(l||r.allowEmptyOption)if(p.hasOwnProperty(l)){if(i){var u=p[l][a];u?e.isArray(u)?u.push(i):p[l][a]=[u,i]:p[l][a]=i}}else{var c=m(t)||{};c[o]=c[o]||t.text();c[s]=c[s]||l;c[a]=c[a]||i;p[l]=c;g.push(c);t.is(":selected")&&n.items.push(l)}},v=function(t){var r,i,o,s,a;t=e(t);o=t.attr("label");if(o){s=m(t)||{};s[l]=o;s[u]=o;n.optgroups.push(s)}a=e("option",t);for(r=0,i=a.length;i>r;r++)E(a[r],o)};n.maxItems=t.attr("multiple")?null:1;f=t.children();for(c=0,d=f.length;d>c;c++){h=f[c].tagName.toLowerCase();"optgroup"===h?v(f[c]):"option"===h&&E(f[c])}};return this.each(function(){if(!this.selectize){var i,o=e(this),s=this.tagName.toLowerCase(),a=o.attr("placeholder")||o.attr("data-placeholder");a||r.allowEmptyOption||(a=o.children('option[value=""]').text());var l={placeholder:a,options:[],optgroups:[],items:[]};"select"===s?d(o,l):c(o,l);i=new D(o,e.extend(!0,{},n,l,t))}})};e.fn.selectize.defaults=D.defaults;e.fn.selectize.support={validity:A};D.define("drag_drop",function(){if(!e.fn.sortable)throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');if("multi"===this.settings.mode){var t=this;t.lock=function(){var e=t.lock;return function(){var n=t.$control.data("sortable");n&&n.disable();return e.apply(t,arguments)}}();t.unlock=function(){var e=t.unlock;return function(){var n=t.$control.data("sortable");n&&n.enable();return e.apply(t,arguments)}}();t.setup=function(){var n=t.setup;return function(){n.apply(this,arguments);var r=t.$control.sortable({items:"[data-value]",forcePlaceholderSize:!0,disabled:t.isLocked,start:function(e,t){t.placeholder.css("width",t.helper.css("width"));r.css({overflow:"visible"})},stop:function(){r.css({overflow:"hidden"});var n=t.$activeItems?t.$activeItems.slice():null,i=[];r.children("[data-value]").each(function(){i.push(e(this).attr("data-value"))});t.setValue(i);t.setActiveItem(n)}})}}()}});D.define("dropdown_header",function(t){var n=this;t=e.extend({title:"Untitled",headerClass:"selectize-dropdown-header",titleRowClass:"selectize-dropdown-header-title",labelClass:"selectize-dropdown-header-label",closeClass:"selectize-dropdown-header-close",html:function(e){return'<div class="'+e.headerClass+'"><div class="'+e.titleRowClass+'"><span class="'+e.labelClass+'">'+e.title+'</span><a href="javascript:void(0)" class="'+e.closeClass+'">×</a></div></div>'}},t);n.setup=function(){var r=n.setup;return function(){r.apply(n,arguments);n.$dropdown_header=e(t.html(t));n.$dropdown.prepend(n.$dropdown_header)}}()});D.define("optgroup_columns",function(t){var n=this;t=e.extend({equalizeWidth:!0,equalizeHeight:!0},t);this.getAdjacentOption=function(t,n){var r=t.closest("[data-group]").find("[data-selectable]"),i=r.index(t)+n;return i>=0&&i<r.length?r.eq(i):e()};this.onKeyDown=function(){var e=n.onKeyDown;return function(t){var r,i,o,s;if(!this.isOpen||t.keyCode!==u&&t.keyCode!==d)return e.apply(this,arguments);n.ignoreHover=!0;s=this.$activeOption.closest("[data-group]");r=s.find("[data-selectable]").index(this.$activeOption);s=t.keyCode===u?s.prev("[data-group]"):s.next("[data-group]");o=s.find("[data-selectable]");i=o.eq(Math.min(o.length-1,r));i.length&&this.setActiveOption(i)}}();var r=function(){var e,t=r.width,n=document;if("undefined"==typeof t){e=n.createElement("div");e.innerHTML='<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';e=e.firstChild;n.body.appendChild(e);t=r.width=e.offsetWidth-e.clientWidth;n.body.removeChild(e)}return t},i=function(){var i,o,s,a,l,u,p;p=e("[data-group]",n.$dropdown_content);o=p.length;if(o&&n.$dropdown_content.width()){if(t.equalizeHeight){s=0;for(i=0;o>i;i++)s=Math.max(s,p.eq(i).height());p.css({height:s})}if(t.equalizeWidth){u=n.$dropdown_content.innerWidth()-r();a=Math.round(u/o);p.css({width:a});if(o>1){l=u-a*(o-1);p.eq(o-1).css({width:l})}}}};if(t.equalizeHeight||t.equalizeWidth){C.after(this,"positionDropdown",i);C.after(this,"refreshOptions",i)}});D.define("remove_button",function(t){if("single"!==this.settings.mode){t=e.extend({label:"×",title:"Remove",className:"remove",append:!0},t);var n=this,r='<a href="javascript:void(0)" class="'+t.className+'" tabindex="-1" title="'+S(t.title)+'">'+t.label+"</a>",i=function(e,t){var n=e.search(/(<\/[^>]+>\s*)$/);return e.substring(0,n)+t+e.substring(n)};this.setup=function(){var o=n.setup;return function(){if(t.append){var s=n.settings.render.item;n.settings.render.item=function(){return i(s.apply(this,arguments),r)}}o.apply(this,arguments);this.$control.on("click","."+t.className,function(t){t.preventDefault();if(!n.isLocked){var r=e(t.currentTarget).parent();n.setActiveItem(r);n.deleteSelection()&&n.setCaret(n.items.length)}})}}()}});D.define("restore_on_backspace",function(e){var t=this;e.text=e.text||function(e){return e[this.settings.labelField]};this.onKeyDown=function(){var n=t.onKeyDown;return function(t){var r,i;if(t.keyCode===g&&""===this.$control_input.val()&&!this.$activeItems.length){r=this.caretPos-1;if(r>=0&&r<this.items.length){i=this.options[this.items[r]];if(this.deleteSelection(t)){this.setTextboxValue(e.text.apply(this,[i]));this.refreshOptions(!0)}t.preventDefault();return}}return n.apply(this,arguments)}}()});return D})},{jquery:void 0,microplugin:9,sifter:10}],9:[function(t,n,r){(function(t,i){"function"==typeof e&&e.amd?e(i):"object"==typeof r?n.exports=i():t.MicroPlugin=i()})(this,function(){var e={};e.mixin=function(e){e.plugins={};e.prototype.initializePlugins=function(e){var n,r,i,o=this,s=[];o.plugins={names:[],settings:{},requested:{},loaded:{}};if(t.isArray(e))for(n=0,r=e.length;r>n;n++)if("string"==typeof e[n])s.push(e[n]);else{o.plugins.settings[e[n].name]=e[n].options;s.push(e[n].name)}else if(e)for(i in e)if(e.hasOwnProperty(i)){o.plugins.settings[i]=e[i];s.push(i)}for(;s.length;)o.require(s.shift())};e.prototype.loadPlugin=function(t){var n=this,r=n.plugins,i=e.plugins[t];if(!e.plugins.hasOwnProperty(t))throw new Error('Unable to find "'+t+'" plugin');r.requested[t]=!0;r.loaded[t]=i.fn.apply(n,[n.plugins.settings[t]||{}]);r.names.push(t)};e.prototype.require=function(e){var t=this,n=t.plugins;if(!t.plugins.loaded.hasOwnProperty(e)){if(n.requested[e])throw new Error('Plugin has circular dependency ("'+e+'")');t.loadPlugin(e)}return n.loaded[e]};e.define=function(t,n){e.plugins[t]={name:t,fn:n}}};var t={isArray:Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}};return e})},{}],10:[function(t,n,r){(function(t,i){"function"==typeof e&&e.amd?e(i):"object"==typeof r?n.exports=i():t.Sifter=i()})(this,function(){var e=function(e,t){this.items=e;this.settings=t||{diacritics:!0}};e.prototype.tokenize=function(e){e=r(String(e||"").toLowerCase());if(!e||!e.length)return[];var t,n,o,a,l=[],u=e.split(/ +/);for(t=0,n=u.length;n>t;t++){o=i(u[t]);if(this.settings.diacritics)for(a in s)s.hasOwnProperty(a)&&(o=o.replace(new RegExp(a,"g"),s[a]));l.push({string:u[t],regex:new RegExp(o,"i")})}return l};e.prototype.iterator=function(e,t){var n;n=o(e)?Array.prototype.forEach||function(e){for(var t=0,n=this.length;n>t;t++)e(this[t],t,this)}:function(e){for(var t in this)this.hasOwnProperty(t)&&e(this[t],t,this)};n.apply(e,[t])};e.prototype.getScoreFunction=function(e,t){var n,r,i,o;n=this;e=n.prepareSearch(e,t);i=e.tokens;r=e.options.fields;o=i.length;var s=function(e,t){var n,r;if(!e)return 0;e=String(e||"");r=e.search(t.regex);if(-1===r)return 0;n=t.string.length/e.length;0===r&&(n+=.5);return n},a=function(){var e=r.length;return e?1===e?function(e,t){return s(t[r[0]],e)}:function(t,n){for(var i=0,o=0;e>i;i++)o+=s(n[r[i]],t);return o/e}:function(){return 0}}();return o?1===o?function(e){return a(i[0],e)}:"and"===e.options.conjunction?function(e){for(var t,n=0,r=0;o>n;n++){t=a(i[n],e);if(0>=t)return 0;r+=t}return r/o}:function(e){for(var t=0,n=0;o>t;t++)n+=a(i[t],e);return n/o}:function(){return 0}};e.prototype.getSortFunction=function(e,n){var r,i,o,s,a,l,u,p,c,d,h;o=this;e=o.prepareSearch(e,n);h=!e.query&&n.sort_empty||n.sort;c=function(e,t){return"$score"===e?t.score:o.items[t.id][e]};a=[];if(h)for(r=0,i=h.length;i>r;r++)(e.query||"$score"!==h[r].field)&&a.push(h[r]);if(e.query){d=!0;for(r=0,i=a.length;i>r;r++)if("$score"===a[r].field){d=!1;break}d&&a.unshift({field:"$score",direction:"desc"})}else for(r=0,i=a.length;i>r;r++)if("$score"===a[r].field){a.splice(r,1);break}p=[];for(r=0,i=a.length;i>r;r++)p.push("desc"===a[r].direction?-1:1);l=a.length;if(l){if(1===l){s=a[0].field;u=p[0];return function(e,n){return u*t(c(s,e),c(s,n))}}return function(e,n){var r,i,o;for(r=0;l>r;r++){o=a[r].field;i=p[r]*t(c(o,e),c(o,n));if(i)return i}return 0}}return null};e.prototype.prepareSearch=function(e,t){if("object"==typeof e)return e;t=n({},t);var r=t.fields,i=t.sort,s=t.sort_empty;r&&!o(r)&&(t.fields=[r]);i&&!o(i)&&(t.sort=[i]);s&&!o(s)&&(t.sort_empty=[s]);return{options:t,query:String(e||"").toLowerCase(),tokens:this.tokenize(e),total:0,items:[]}};e.prototype.search=function(e,t){var n,r,i,o,s=this;r=this.prepareSearch(e,t);t=r.options;e=r.query;o=t.score||s.getScoreFunction(r);e.length?s.iterator(s.items,function(e,i){n=o(e);(t.filter===!1||n>0)&&r.items.push({score:n,id:i})}):s.iterator(s.items,function(e,t){r.items.push({score:1,id:t})});i=s.getSortFunction(r,t);i&&r.items.sort(i);r.total=r.items.length;"number"==typeof t.limit&&(r.items=r.items.slice(0,t.limit));return r};var t=function(e,t){if("number"==typeof e&&"number"==typeof t)return e>t?1:t>e?-1:0;e=a(String(e||""));t=a(String(t||""));return e>t?1:t>e?-1:0},n=function(e){var t,n,r,i;for(t=1,n=arguments.length;n>t;t++){i=arguments[t];if(i)for(r in i)i.hasOwnProperty(r)&&(e[r]=i[r])}return e},r=function(e){return(e+"").replace(/^\s+|\s+$|/g,"")},i=function(e){return(e+"").replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")},o=Array.isArray||$&&$.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},s={a:"[aÀÁÂÃÄÅàáâãäåĀāąĄ]",c:"[cÇçćĆčČ]",d:"[dđĐďĎ]",e:"[eÈÉÊËèéêëěĚĒēęĘ]",i:"[iÌÍÎÏìíîïĪī]",l:"[lłŁ]",n:"[nÑñňŇńŃ]",o:"[oÒÓÔÕÕÖØòóôõöøŌō]",r:"[rřŘ]",s:"[sŠšśŚ]",t:"[tťŤ]",u:"[uÙÚÛÜùúûüůŮŪū]",y:"[yŸÿýÝ]",z:"[zŽžżŻźŹ]"},a=function(){var e,t,n,r,i="",o={};for(n in s)if(s.hasOwnProperty(n)){r=s[n].substring(2,s[n].length-1);i+=r;for(e=0,t=r.length;t>e;e++)o[r.charAt(e)]=n}var a=new RegExp("["+i+"]","g");return function(e){return e.replace(a,function(e){return o[e]}).toLowerCase()}}();return e})},{}],11:[function(t,n,r){(function(){var t=this,i=t._,o=Array.prototype,s=Object.prototype,a=Function.prototype,l=o.push,u=o.slice,p=o.concat,c=s.toString,d=s.hasOwnProperty,h=Array.isArray,f=Object.keys,g=a.bind,m=function(e){if(e instanceof m)return e;if(!(this instanceof m))return new m(e);this._wrapped=e;return void 0};if("undefined"!=typeof r){"undefined"!=typeof n&&n.exports&&(r=n.exports=m);r._=m}else t._=m;m.VERSION="1.7.0";var E=function(e,t,n){if(void 0===t)return e;switch(null==n?3:n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)};case 4:return function(n,r,i,o){return e.call(t,n,r,i,o)}}return function(){return e.apply(t,arguments)}};m.iteratee=function(e,t,n){return null==e?m.identity:m.isFunction(e)?E(e,t,n):m.isObject(e)?m.matches(e):m.property(e)};m.each=m.forEach=function(e,t,n){if(null==e)return e;t=E(t,n);var r,i=e.length;if(i===+i)for(r=0;i>r;r++)t(e[r],r,e);else{var o=m.keys(e);for(r=0,i=o.length;i>r;r++)t(e[o[r]],o[r],e)}return e};m.map=m.collect=function(e,t,n){if(null==e)return[];t=m.iteratee(t,n);for(var r,i=e.length!==+e.length&&m.keys(e),o=(i||e).length,s=Array(o),a=0;o>a;a++){r=i?i[a]:a;s[a]=t(e[r],r,e)}return s};var v="Reduce of empty array with no initial value";m.reduce=m.foldl=m.inject=function(e,t,n,r){null==e&&(e=[]);t=E(t,r,4);var i,o=e.length!==+e.length&&m.keys(e),s=(o||e).length,a=0;if(arguments.length<3){if(!s)throw new TypeError(v);n=e[o?o[a++]:a++]}for(;s>a;a++){i=o?o[a]:a;n=t(n,e[i],i,e)}return n};m.reduceRight=m.foldr=function(e,t,n,r){null==e&&(e=[]);t=E(t,r,4);var i,o=e.length!==+e.length&&m.keys(e),s=(o||e).length;if(arguments.length<3){if(!s)throw new TypeError(v);n=e[o?o[--s]:--s]}for(;s--;){i=o?o[s]:s;n=t(n,e[i],i,e)}return n};m.find=m.detect=function(e,t,n){var r;t=m.iteratee(t,n);m.some(e,function(e,n,i){if(t(e,n,i)){r=e;return!0}});return r};m.filter=m.select=function(e,t,n){var r=[];if(null==e)return r;t=m.iteratee(t,n);m.each(e,function(e,n,i){t(e,n,i)&&r.push(e)});return r};m.reject=function(e,t,n){return m.filter(e,m.negate(m.iteratee(t)),n)};m.every=m.all=function(e,t,n){if(null==e)return!0;t=m.iteratee(t,n);var r,i,o=e.length!==+e.length&&m.keys(e),s=(o||e).length;for(r=0;s>r;r++){i=o?o[r]:r;if(!t(e[i],i,e))return!1}return!0};m.some=m.any=function(e,t,n){if(null==e)return!1;t=m.iteratee(t,n);var r,i,o=e.length!==+e.length&&m.keys(e),s=(o||e).length;for(r=0;s>r;r++){i=o?o[r]:r;if(t(e[i],i,e))return!0}return!1};m.contains=m.include=function(e,t){if(null==e)return!1;e.length!==+e.length&&(e=m.values(e));return m.indexOf(e,t)>=0};m.invoke=function(e,t){var n=u.call(arguments,2),r=m.isFunction(t);return m.map(e,function(e){return(r?t:e[t]).apply(e,n)})};m.pluck=function(e,t){return m.map(e,m.property(t))};m.where=function(e,t){return m.filter(e,m.matches(t))};m.findWhere=function(e,t){return m.find(e,m.matches(t))};m.max=function(e,t,n){var r,i,o=-1/0,s=-1/0;if(null==t&&null!=e){e=e.length===+e.length?e:m.values(e);for(var a=0,l=e.length;l>a;a++){r=e[a];r>o&&(o=r)}}else{t=m.iteratee(t,n);m.each(e,function(e,n,r){i=t(e,n,r);if(i>s||i===-1/0&&o===-1/0){o=e;s=i}})}return o};m.min=function(e,t,n){var r,i,o=1/0,s=1/0;if(null==t&&null!=e){e=e.length===+e.length?e:m.values(e);for(var a=0,l=e.length;l>a;a++){r=e[a];o>r&&(o=r)}}else{t=m.iteratee(t,n);m.each(e,function(e,n,r){i=t(e,n,r);if(s>i||1/0===i&&1/0===o){o=e;s=i}})}return o};m.shuffle=function(e){for(var t,n=e&&e.length===+e.length?e:m.values(e),r=n.length,i=Array(r),o=0;r>o;o++){t=m.random(0,o);t!==o&&(i[o]=i[t]);i[t]=n[o]}return i};m.sample=function(e,t,n){if(null==t||n){e.length!==+e.length&&(e=m.values(e));return e[m.random(e.length-1)]}return m.shuffle(e).slice(0,Math.max(0,t))};m.sortBy=function(e,t,n){t=m.iteratee(t,n);return m.pluck(m.map(e,function(e,n,r){return{value:e,index:n,criteria:t(e,n,r)}}).sort(function(e,t){var n=e.criteria,r=t.criteria;if(n!==r){if(n>r||void 0===n)return 1;if(r>n||void 0===r)return-1}return e.index-t.index}),"value")};var x=function(e){return function(t,n,r){var i={};n=m.iteratee(n,r);m.each(t,function(r,o){var s=n(r,o,t);e(i,r,s)});return i}};m.groupBy=x(function(e,t,n){m.has(e,n)?e[n].push(t):e[n]=[t]});m.indexBy=x(function(e,t,n){e[n]=t});m.countBy=x(function(e,t,n){m.has(e,n)?e[n]++:e[n]=1});m.sortedIndex=function(e,t,n,r){n=m.iteratee(n,r,1);for(var i=n(t),o=0,s=e.length;s>o;){var a=o+s>>>1;n(e[a])<i?o=a+1:s=a}return o};m.toArray=function(e){return e?m.isArray(e)?u.call(e):e.length===+e.length?m.map(e,m.identity):m.values(e):[]};m.size=function(e){return null==e?0:e.length===+e.length?e.length:m.keys(e).length};m.partition=function(e,t,n){t=m.iteratee(t,n);var r=[],i=[];m.each(e,function(e,n,o){(t(e,n,o)?r:i).push(e)});return[r,i]};m.first=m.head=m.take=function(e,t,n){return null==e?void 0:null==t||n?e[0]:0>t?[]:u.call(e,0,t)};m.initial=function(e,t,n){return u.call(e,0,Math.max(0,e.length-(null==t||n?1:t)))};m.last=function(e,t,n){return null==e?void 0:null==t||n?e[e.length-1]:u.call(e,Math.max(e.length-t,0))};m.rest=m.tail=m.drop=function(e,t,n){return u.call(e,null==t||n?1:t)};m.compact=function(e){return m.filter(e,m.identity)};var y=function(e,t,n,r){if(t&&m.every(e,m.isArray))return p.apply(r,e);for(var i=0,o=e.length;o>i;i++){var s=e[i];m.isArray(s)||m.isArguments(s)?t?l.apply(r,s):y(s,t,n,r):n||r.push(s)}return r};m.flatten=function(e,t){return y(e,t,!1,[])};m.without=function(e){return m.difference(e,u.call(arguments,1))};m.uniq=m.unique=function(e,t,n,r){if(null==e)return[];if(!m.isBoolean(t)){r=n;n=t;t=!1}null!=n&&(n=m.iteratee(n,r));for(var i=[],o=[],s=0,a=e.length;a>s;s++){var l=e[s];if(t){s&&o===l||i.push(l);o=l}else if(n){var u=n(l,s,e);if(m.indexOf(o,u)<0){o.push(u);i.push(l)}}else m.indexOf(i,l)<0&&i.push(l)}return i};m.union=function(){return m.uniq(y(arguments,!0,!0,[]))};m.intersection=function(e){if(null==e)return[];for(var t=[],n=arguments.length,r=0,i=e.length;i>r;r++){var o=e[r];if(!m.contains(t,o)){for(var s=1;n>s&&m.contains(arguments[s],o);s++);s===n&&t.push(o)}}return t};m.difference=function(e){var t=y(u.call(arguments,1),!0,!0,[]);return m.filter(e,function(e){return!m.contains(t,e)})};m.zip=function(e){if(null==e)return[];for(var t=m.max(arguments,"length").length,n=Array(t),r=0;t>r;r++)n[r]=m.pluck(arguments,r);return n};m.object=function(e,t){if(null==e)return{};for(var n={},r=0,i=e.length;i>r;r++)t?n[e[r]]=t[r]:n[e[r][0]]=e[r][1];return n};m.indexOf=function(e,t,n){if(null==e)return-1;var r=0,i=e.length;if(n){if("number"!=typeof n){r=m.sortedIndex(e,t);return e[r]===t?r:-1}r=0>n?Math.max(0,i+n):n}for(;i>r;r++)if(e[r]===t)return r;return-1};m.lastIndexOf=function(e,t,n){if(null==e)return-1;var r=e.length;"number"==typeof n&&(r=0>n?r+n+1:Math.min(r,n+1));for(;--r>=0;)if(e[r]===t)return r;return-1};m.range=function(e,t,n){if(arguments.length<=1){t=e||0;e=0}n=n||1;for(var r=Math.max(Math.ceil((t-e)/n),0),i=Array(r),o=0;r>o;o++,e+=n)i[o]=e;return i};var N=function(){};m.bind=function(e,t){var n,r;if(g&&e.bind===g)return g.apply(e,u.call(arguments,1));if(!m.isFunction(e))throw new TypeError("Bind must be called on a function");n=u.call(arguments,2);r=function(){if(!(this instanceof r))return e.apply(t,n.concat(u.call(arguments)));N.prototype=e.prototype;var i=new N;N.prototype=null;var o=e.apply(i,n.concat(u.call(arguments)));return m.isObject(o)?o:i};return r};m.partial=function(e){var t=u.call(arguments,1);return function(){for(var n=0,r=t.slice(),i=0,o=r.length;o>i;i++)r[i]===m&&(r[i]=arguments[n++]);for(;n<arguments.length;)r.push(arguments[n++]);return e.apply(this,r)}};m.bindAll=function(e){var t,n,r=arguments.length;if(1>=r)throw new Error("bindAll must be passed function names");for(t=1;r>t;t++){n=arguments[t];e[n]=m.bind(e[n],e)}return e};m.memoize=function(e,t){var n=function(r){var i=n.cache,o=t?t.apply(this,arguments):r;m.has(i,o)||(i[o]=e.apply(this,arguments));return i[o]};n.cache={};return n};m.delay=function(e,t){var n=u.call(arguments,2);return setTimeout(function(){return e.apply(null,n)},t)};m.defer=function(e){return m.delay.apply(m,[e,1].concat(u.call(arguments,1)))};m.throttle=function(e,t,n){var r,i,o,s=null,a=0;n||(n={});var l=function(){a=n.leading===!1?0:m.now();s=null;o=e.apply(r,i);s||(r=i=null)};return function(){var u=m.now();a||n.leading!==!1||(a=u);var p=t-(u-a);r=this;i=arguments;if(0>=p||p>t){clearTimeout(s);s=null;a=u;o=e.apply(r,i);s||(r=i=null)}else s||n.trailing===!1||(s=setTimeout(l,p));return o}};m.debounce=function(e,t,n){var r,i,o,s,a,l=function(){var u=m.now()-s;if(t>u&&u>0)r=setTimeout(l,t-u);else{r=null;if(!n){a=e.apply(o,i);r||(o=i=null)}}};return function(){o=this;i=arguments;s=m.now();var u=n&&!r;r||(r=setTimeout(l,t));if(u){a=e.apply(o,i);o=i=null}return a}};m.wrap=function(e,t){return m.partial(t,e)};m.negate=function(e){return function(){return!e.apply(this,arguments)}};m.compose=function(){var e=arguments,t=e.length-1;return function(){for(var n=t,r=e[t].apply(this,arguments);n--;)r=e[n].call(this,r);return r}};m.after=function(e,t){return function(){return--e<1?t.apply(this,arguments):void 0}};m.before=function(e,t){var n;return function(){--e>0?n=t.apply(this,arguments):t=null;return n}};m.once=m.partial(m.before,2);m.keys=function(e){if(!m.isObject(e))return[];if(f)return f(e);var t=[];for(var n in e)m.has(e,n)&&t.push(n);return t};m.values=function(e){for(var t=m.keys(e),n=t.length,r=Array(n),i=0;n>i;i++)r[i]=e[t[i]];return r};m.pairs=function(e){for(var t=m.keys(e),n=t.length,r=Array(n),i=0;n>i;i++)r[i]=[t[i],e[t[i]]];return r};m.invert=function(e){for(var t={},n=m.keys(e),r=0,i=n.length;i>r;r++)t[e[n[r]]]=n[r];return t};m.functions=m.methods=function(e){var t=[];for(var n in e)m.isFunction(e[n])&&t.push(n);return t.sort()};m.extend=function(e){if(!m.isObject(e))return e;for(var t,n,r=1,i=arguments.length;i>r;r++){t=arguments[r];for(n in t)d.call(t,n)&&(e[n]=t[n])}return e};m.pick=function(e,t,n){var r,i={};if(null==e)return i;if(m.isFunction(t)){t=E(t,n);for(r in e){var o=e[r];t(o,r,e)&&(i[r]=o)}}else{var s=p.apply([],u.call(arguments,1));e=new Object(e);for(var a=0,l=s.length;l>a;a++){r=s[a];r in e&&(i[r]=e[r])}}return i};m.omit=function(e,t,n){if(m.isFunction(t))t=m.negate(t);else{var r=m.map(p.apply([],u.call(arguments,1)),String);t=function(e,t){return!m.contains(r,t)}}return m.pick(e,t,n)};m.defaults=function(e){if(!m.isObject(e))return e;for(var t=1,n=arguments.length;n>t;t++){var r=arguments[t];for(var i in r)void 0===e[i]&&(e[i]=r[i])}return e};m.clone=function(e){return m.isObject(e)?m.isArray(e)?e.slice():m.extend({},e):e};m.tap=function(e,t){t(e);return e};var I=function(e,t,n,r){if(e===t)return 0!==e||1/e===1/t;if(null==e||null==t)return e===t;e instanceof m&&(e=e._wrapped);t instanceof m&&(t=t._wrapped);var i=c.call(e);if(i!==c.call(t))return!1;switch(i){case"[object RegExp]":case"[object String]":return""+e==""+t;case"[object Number]":return+e!==+e?+t!==+t:0===+e?1/+e===1/t:+e===+t;case"[object Date]":case"[object Boolean]":return+e===+t}if("object"!=typeof e||"object"!=typeof t)return!1;for(var o=n.length;o--;)if(n[o]===e)return r[o]===t;var s=e.constructor,a=t.constructor;if(s!==a&&"constructor"in e&&"constructor"in t&&!(m.isFunction(s)&&s instanceof s&&m.isFunction(a)&&a instanceof a))return!1;n.push(e);r.push(t);var l,u;if("[object Array]"===i){l=e.length;u=l===t.length;if(u)for(;l--&&(u=I(e[l],t[l],n,r)););}else{var p,d=m.keys(e);l=d.length;u=m.keys(t).length===l;if(u)for(;l--;){p=d[l];if(!(u=m.has(t,p)&&I(e[p],t[p],n,r)))break}}n.pop();r.pop();return u};m.isEqual=function(e,t){return I(e,t,[],[])};m.isEmpty=function(e){if(null==e)return!0;if(m.isArray(e)||m.isString(e)||m.isArguments(e))return 0===e.length;for(var t in e)if(m.has(e,t))return!1;return!0};m.isElement=function(e){return!(!e||1!==e.nodeType)
};m.isArray=h||function(e){return"[object Array]"===c.call(e)};m.isObject=function(e){var t=typeof e;return"function"===t||"object"===t&&!!e};m.each(["Arguments","Function","String","Number","Date","RegExp"],function(e){m["is"+e]=function(t){return c.call(t)==="[object "+e+"]"}});m.isArguments(arguments)||(m.isArguments=function(e){return m.has(e,"callee")});"function"!=typeof/./&&(m.isFunction=function(e){return"function"==typeof e||!1});m.isFinite=function(e){return isFinite(e)&&!isNaN(parseFloat(e))};m.isNaN=function(e){return m.isNumber(e)&&e!==+e};m.isBoolean=function(e){return e===!0||e===!1||"[object Boolean]"===c.call(e)};m.isNull=function(e){return null===e};m.isUndefined=function(e){return void 0===e};m.has=function(e,t){return null!=e&&d.call(e,t)};m.noConflict=function(){t._=i;return this};m.identity=function(e){return e};m.constant=function(e){return function(){return e}};m.noop=function(){};m.property=function(e){return function(t){return t[e]}};m.matches=function(e){var t=m.pairs(e),n=t.length;return function(e){if(null==e)return!n;e=new Object(e);for(var r=0;n>r;r++){var i=t[r],o=i[0];if(i[1]!==e[o]||!(o in e))return!1}return!0}};m.times=function(e,t,n){var r=Array(Math.max(0,e));t=E(t,n,1);for(var i=0;e>i;i++)r[i]=t(i);return r};m.random=function(e,t){if(null==t){t=e;e=0}return e+Math.floor(Math.random()*(t-e+1))};m.now=Date.now||function(){return(new Date).getTime()};var A={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},T=m.invert(A),L=function(e){var t=function(t){return e[t]},n="(?:"+m.keys(e).join("|")+")",r=RegExp(n),i=RegExp(n,"g");return function(e){e=null==e?"":""+e;return r.test(e)?e.replace(i,t):e}};m.escape=L(A);m.unescape=L(T);m.result=function(e,t){if(null==e)return void 0;var n=e[t];return m.isFunction(n)?e[t]():n};var S=0;m.uniqueId=function(e){var t=++S+"";return e?e+t:t};m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var b=/(.)^/,C={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},R=/\\|'|\r|\n|\u2028|\u2029/g,w=function(e){return"\\"+C[e]};m.template=function(e,t,n){!t&&n&&(t=n);t=m.defaults({},t,m.templateSettings);var r=RegExp([(t.escape||b).source,(t.interpolate||b).source,(t.evaluate||b).source].join("|")+"|$","g"),i=0,o="__p+='";e.replace(r,function(t,n,r,s,a){o+=e.slice(i,a).replace(R,w);i=a+t.length;n?o+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":r?o+="'+\n((__t=("+r+"))==null?'':__t)+\n'":s&&(o+="';\n"+s+"\n__p+='");return t});o+="';\n";t.variable||(o="with(obj||{}){\n"+o+"}\n");o="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{var s=new Function(t.variable||"obj","_",o)}catch(a){a.source=o;throw a}var l=function(e){return s.call(this,e,m)},u=t.variable||"obj";l.source="function("+u+"){\n"+o+"}";return l};m.chain=function(e){var t=m(e);t._chain=!0;return t};var O=function(e){return this._chain?m(e).chain():e};m.mixin=function(e){m.each(m.functions(e),function(t){var n=m[t]=e[t];m.prototype[t]=function(){var e=[this._wrapped];l.apply(e,arguments);return O.call(this,n.apply(m,e))}})};m.mixin(m);m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=o[e];m.prototype[e]=function(){var n=this._wrapped;t.apply(n,arguments);"shift"!==e&&"splice"!==e||0!==n.length||delete n[0];return O.call(this,n)}});m.each(["concat","join","slice"],function(e){var t=o[e];m.prototype[e]=function(){return O.call(this,t.apply(this._wrapped,arguments))}});m.prototype.value=function(){return this._wrapped};"function"==typeof e&&e.amd&&e("underscore",[],function(){return m})}).call(this)},{}],12:[function(t,n){(function(t){function r(){try{return l in t&&t[l]}catch(e){return!1}}function i(e){return e.replace(/^d/,"___$&").replace(f,"___")}var o,s={},a=t.document,l="localStorage",u="script";s.disabled=!1;s.version="1.3.17";s.set=function(){};s.get=function(){};s.has=function(e){return void 0!==s.get(e)};s.remove=function(){};s.clear=function(){};s.transact=function(e,t,n){if(null==n){n=t;t=null}null==t&&(t={});var r=s.get(e,t);n(r);s.set(e,r)};s.getAll=function(){};s.forEach=function(){};s.serialize=function(e){return JSON.stringify(e)};s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}};if(r()){o=t[l];s.set=function(e,t){if(void 0===t)return s.remove(e);o.setItem(e,s.serialize(t));return t};s.get=function(e,t){var n=s.deserialize(o.getItem(e));return void 0===n?t:n};s.remove=function(e){o.removeItem(e)};s.clear=function(){o.clear()};s.getAll=function(){var e={};s.forEach(function(t,n){e[t]=n});return e};s.forEach=function(e){for(var t=0;t<o.length;t++){var n=o.key(t);e(n,s.get(n))}}}else if(a.documentElement.addBehavior){var p,c;try{c=new ActiveXObject("htmlfile");c.open();c.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');c.close();p=c.w.frames[0].document;o=p.createElement("div")}catch(d){o=a.createElement("div");p=a.body}var h=function(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(o);p.appendChild(o);o.addBehavior("#default#userData");o.load(l);var n=e.apply(s,t);p.removeChild(o);return n}},f=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=h(function(e,t,n){t=i(t);if(void 0===n)return s.remove(t);e.setAttribute(t,s.serialize(n));e.save(l);return n});s.get=h(function(e,t,n){t=i(t);var r=s.deserialize(e.getAttribute(t));return void 0===r?n:r});s.remove=h(function(e,t){t=i(t);e.removeAttribute(t);e.save(l)});s.clear=h(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(l);for(var n,r=0;n=t[r];r++)e.removeAttribute(n.name);e.save(l)});s.getAll=function(){var e={};s.forEach(function(t,n){e[t]=n});return e};s.forEach=h(function(e,t){for(var n,r=e.XMLDocument.documentElement.attributes,i=0;n=r[i];++i)t(n.name,s.deserialize(e.getAttribute(n.name)))})}try{var g="__storejs__";s.set(g,g);s.get(g)!=g&&(s.disabled=!0);s.remove(g)}catch(d){s.disabled=!0}s.enabled=!s.disabled;"undefined"!=typeof n&&n.exports&&this.module!==n?n.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s})(Function("return this")())},{}],13:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.2",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],14:[function(e,t){window.console=window.console||{log:function(){}};t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version},nestedExists:function(e){for(var t=Array.prototype.slice.call(arguments,1),n=0;n<t.length;n++){if(!e||!e.hasOwnProperty(t[n]))return!1;e=e[t[n]]}return!0}}},{"../package.json":13,"./storage.js":15,"./svg.js":16}],15:[function(e,t){{var n=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,i){if(n.enabled&&e&&void 0!==t){"string"==typeof i&&(i=r[i]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));n.set(e,{val:t,exp:i,time:(new Date).getTime()})}},remove:function(e){n.enabled&&e&&n.remove(e)},get:function(e){if(!n.enabled)return null;if(e){var t=n.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}return null}}}},{store:12}],16:[function(e,t){t.exports={draw:function(e,n){if(e){var r=t.exports.getElement(n);r&&(e.append?e.append(r):e.appendChild(r))}},getElement:function(e){if(e&&0==e.indexOf("<svg")){var t=new DOMParser,n=t.parseFromString(e,"text/xml"),r=n.documentElement,i=document.createElement("div");i.className="svgImg";i.appendChild(r);return i}return!1}}},{}],17:[function(e){"use strict";var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.deparam=function(e,n){var r={},i={"true":!0,"false":!1,"null":null};t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=r,p=0,c=l.split("]["),d=c.length-1;if(/\[/.test(c[0])&&/\]$/.test(c[d])){c[d]=c[d].replace(/\]$/,"");c=c.shift().split("[").concat(c);d=c.length-1}else d=0;if(2===a.length){s=decodeURIComponent(a[1]);n&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==i[s]?i[s]:s);if(d)for(;d>=p;p++){l=""===c[p]?u.length:c[p];u=u[l]=d>p?u[l]||(c[p+1]&&isNaN(c[p+1])?{}:[]):s}else t.isArray(r[l])?r[l].push(s):r[l]=void 0!==r[l]?[r[l],s]:s}else l&&(r[l]=n?void 0:"")});return r}},{jquery:void 0}],18:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,n="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",i=r+"|_",o="("+i+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+i+"|[0-9])("+i+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,p="("+r+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",h="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",f="("+d+"|"+h+")";if("sparql11"==u){e="("+i+"|:|[0-9]|"+f+")(("+o+"|\\.|:|"+f+")*("+o+"|:|"+f+"))?";t="_:("+i+"|[0-9])(("+o+"|\\.)*"+o+")?"}else{e="("+i+"|[0-9])((("+o+")|\\.)*("+o+"))?";t="_:"+e}var g="("+p+")?:",m=g+e,E="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",y="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",N="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",I="\\+"+x,A="\\+"+y,T="\\+"+N,L="-"+x,S="-"+y,b="-"+N,C="\\\\[tbnrf\\\\\"']",R=c+"{4}",w="(\\\\u"+R+"|\\\\U00(10|0"+c+")"+R+")",O="'(([^\\x27\\x5C\\x0A\\x0D])|"+C+"|"+w+")*'",_='"(([^\\x22\\x5C\\x0A\\x0D])|'+C+"|"+w+')*"',F="'''(('|'')?([^'\\\\]|"+C+"|"+w+"))*'''",P='"""(("|"")?([^"\\\\]|'+C+"|"+w+'))*"""',k="[\\x20\\x09\\x0D\\x0A]",M="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",D="("+k+"|("+M+"))*",G="\\("+D+"\\)",j="\\["+D+"\\]",U={terminal:[{name:"WS",regex:new RegExp("^"+k+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+M),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+n),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+E),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+N),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+y),style:"number"},{name:"INTEGER",regex:new RegExp("^"+x),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+T),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+A),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+b),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+L),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+F),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+P),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+O),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+_),style:"string"},{name:"NIL",regex:new RegExp("^"+G),style:"punc"},{name:"ANON",regex:new RegExp("^"+j),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+g),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return U}function n(e){var t=[],n=o[e];if(void 0!=n)for(var r in n)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,n=0;n<h.length;++n){t=e.match(h[n].regex,!0,!1);if(t)return{cat:h[n].name,style:h[n].style,text:t[0]}}t=e.match(s,!0,!1);if(t)return{cat:e.current().toUpperCase(),style:"keyword",text:t[0]};t=e.match(a,!0,!1);if(t)return{cat:e.current(),style:"punc",text:t[0]};t=e.match(/^.[A-Za-z0-9]*/,!0,!1);return{cat:"<invalid_token>",style:"error",text:t[0]}}function i(){var n=e.column();t.errorStartPos=n;t.errorEndPos=n+c.text.length}function l(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e||"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e)&&(t.queryType=e)}function u(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=r();if("<invalid_token>"==c.cat){if(1==t.OK){t.OK=!1;i()}t.complete=!1;return c.style}if("WS"==c.cat||"COMMENT"==c.cat){t.possibleCurrent=t.possibleNext;return c.style}for(var d,f=!1,g=c.cat;t.stack.length>0&&g&&t.OK&&!f;){d=t.stack.pop();if(o[d]){var m=o[d][g];if(void 0!=m&&p(d)){for(var E=m.length-1;E>=0;--E)t.stack.push(m[E]);u(d)}else{t.OK=!1;t.complete=!1;i();t.stack.push(d)}}else if(d==g){f=!0;l(d);for(var v=!0,x=t.stack.length;x>0;--x){var y=o[t.stack[x-1]];y&&y.$||(v=!1)}t.complete=v;if(t.storeProperty&&"punc"!=g.cat){t.lastProperty=c.text;t.storeProperty=!1}}else{t.OK=!1;t.complete=!1;i()}}if(!f&&t.OK){t.OK=!1;t.complete=!1;i()}t.possibleCurrent=t.possibleNext;t.possibleNext=n(t.stack[t.stack.length-1]);return c.style}function i(t,n){var r=0,i=t.stack.length-1;if(/^[\}\]\)]/.test(n)){for(var o=n.substr(0,1);i>=0;--i)if(t.stack[i]==o){--i;break}}else{var s=f[t.stack[i]];if(s){r+=s;--i}}for(;i>=0;--i){var s=g[t.stack[i]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",p="sparql11",c=!0,d=t(),h=d.terminal,f={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},g={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1};
return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:n(p),possibleNext:n(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:i,electricChars:"}])"}});e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:void 0}],19:[function(e,t){var n=t.exports=function(){this.words=0;this.prefixes=0;this.children=[]};n.prototype={insert:function(e,t){if(0!=e.length){var r,i,o=this;void 0===t&&(t=0);if(t!==e.length){o.prefixes++;r=e[t];void 0===o.children[r]&&(o.children[r]=new n);i=o.children[r];i.insert(e,t+1)}else o.words++}},remove:function(e,t){if(0!=e.length){var n,r,i=this;void 0===t&&(t=0);if(void 0!==i)if(t!==e.length){i.prefixes--;n=e[t];r=i.children[n];r.remove(e,t+1)}else i.words--}},update:function(e,t){if(0!=e.length&&0!=t.length){this.remove(e);this.insert(t)}},countWord:function(e,t){if(0==e.length)return 0;var n,r,i=this,o=0;void 0===t&&(t=0);if(t===e.length)return i.words;n=e[t];r=i.children[n];void 0!==r&&(o=r.countWord(e,t+1));return o},countPrefix:function(e,t){if(0==e.length)return 0;var n,r,i=this,o=0;void 0===t&&(t=0);if(t===e.length)return i.prefixes;var n=e[t];r=i.children[n];void 0!==r&&(o=r.countPrefix(e,t+1));return o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,n,r=this,i=[];void 0===e&&(e="");if(void 0===r)return[];r.words>0&&i.push(e);for(t in r.children){n=r.children[t];i=i.concat(n.getAllWords(e+t))}return i},autoComplete:function(e,t){var n,r,i=this;if(0==e.length)return void 0===t?i.getAllWords(e):[];void 0===t&&(t=0);n=e[t];r=i.children[n];return void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],20:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e){var t=e.getWrapperElement();e.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:t.style.width,height:t.style.height};t.style.width="";t.style.height="auto";t.className+=" CodeMirror-fullscreen";document.documentElement.style.overflow="hidden";e.refresh()}function n(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var n=e.state.fullScreenRestore;t.style.width=n.width;t.style.height=n.height;window.scrollTo(n.scrollLeft,n.scrollTop);e.refresh()}e.defineOption("fullScreen",!1,function(r,i,o){o==e.Init&&(o=!1);!o!=!i&&(i?t(r):n(r))})})},{codemirror:void 0}],21:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){function t(e,t,r,i){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=n(e,s(t.line,l+(p>0?1:0)),p,c||null,i);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function n(e,t,n,r,i){for(var o=i&&i.maxScanLineLength||1e4,l=i&&i.maxScanLines||1e3,u=[],p=i&&i.bracketRegex?i.bracketRegex:/[(){}[\]]/,c=n>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=n){var h=e.getLine(d);if(h){var f=n>0?0:h.length-1,g=n>0?h.length:-1;if(!(h.length>o)){d==t.line&&(f=t.ch-(0>n?1:0));for(;f!=g;f+=n){var m=h.charAt(f);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,f+1))==r)){var E=a[m];if(">"==E.charAt(1)==n>0)u.push(m);else{if(!u.length)return{pos:s(d,f),ch:m};u.pop()}}}}}}return d-n==(n>0?e.lastLine():e.firstLine())?!1:null}function r(e,n,r){for(var i=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=i){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c}));p.to&&e.getLine(p.to.line).length<=i&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!n)return d;setTimeout(d,800)}}function i(e){e.operation(function(){if(l){l();l=null}l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,n,r){r&&r!=e.Init&&t.off("cursorActivity",i);if(n){t.state.matchBrackets="object"==typeof n?n:{};t.on("cursorActivity",i)}});e.defineExtension("matchBrackets",function(){r(this,!0)});e.defineExtension("findMatchingBracket",function(e,n,r){return t(this,e,n,r)});e.defineExtension("scanForBracket",function(e,t,r,i){return n(this,e,t,r,i)})})},{codemirror:void 0}],22:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.registerHelper("fold","brace",function(t,n){function r(r){for(var i=n.ch,l=0;;){var u=0>=i?-1:a.lastIndexOf(r,i-1);if(-1!=u){if(1==l&&u<n.ch)break;o=t.getTokenTypeAt(e.Pos(s,u+1));if(!/^(comment|string)/.test(o))return u+1;i=u-1}else{if(1==l)break;l=1;i=a.length}}}var i,o,s=n.line,a=t.getLine(s),l="{",u="}",i=r("{");if(null==i){l="[",u="]";i=r("[")}if(null!=i){var p,c,d=1,h=t.lastLine();e:for(var f=s;h>=f;++f)for(var g=t.getLine(f),m=f==s?i:0;;){var E=g.indexOf(l,m),v=g.indexOf(u,m);0>E&&(E=g.length);0>v&&(v=g.length);m=Math.min(E,v);if(m==g.length)break;if(t.getTokenTypeAt(e.Pos(f,m+1))==o)if(m==E)++d;else if(!--d){p=f;c=m;break e}++m}if(null!=p&&(s!=p||c!=i))return{from:e.Pos(s,i),to:e.Pos(p,c)}}});e.registerHelper("fold","import",function(t,n){function r(n){if(n<t.firstLine()||n>t.lastLine())return null;var r=t.getTokenAt(e.Pos(n,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(n,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var i=n,o=Math.min(t.lastLine(),n+10);o>=i;++i){var s=t.getLine(i),a=s.indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(i,a)}}}var i,n=n.line,o=r(n);if(!o||r(n-1)||(i=r(n-2))&&i.end.line==n-1)return null;for(var s=o.end;;){var a=r(s.line+1);if(null==a)break;s=a.end}return{from:t.clipPos(e.Pos(n,o.startCh+1)),to:s}});e.registerHelper("fold","include",function(t,n){function r(n){if(n<t.firstLine()||n>t.lastLine())return null;var r=t.getTokenAt(e.Pos(n,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(n,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var n=n.line,i=r(n);if(null==i||null!=r(n-1))return null;for(var o=n;;){var s=r(o+1);if(null==s)break;++o}return{from:e.Pos(n,i+1),to:t.clipPos(e.Pos(o))}})})},{codemirror:void 0}],23:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(t,i,o,s){function a(e){var n=l(t,i);if(!n||n.to.line-n.from.line<u)return null;for(var r=t.findMarksAt(n.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==s){if(!e)return null;n.cleared=!0;r[o].clear()}return n}if(o&&o.call){var l=o;o=null}else var l=r(t,o,"rangeFinder");"number"==typeof i&&(i=e.Pos(i,0));var u=r(t,o,"minFoldSize"),p=a(!0);if(r(t,o,"scanUp"))for(;!p&&i.line>t.firstLine();){i=e.Pos(i.line-1,0);p=a(!1)}if(p&&!p.cleared&&"unfold"!==s){var c=n(t,o);e.on(c,"mousedown",function(t){d.clear();e.e_preventDefault(t)});var d=t.markText(p.from,p.to,{replacedWith:c,clearOnEnter:!0,__isFold:!0});d.on("clear",function(n,r){e.signal(t,"unfold",t,n,r)});e.signal(t,"fold",t,p.from,p.to)}}function n(e,t){var n=r(e,t,"widget");if("string"==typeof n){var i=document.createTextNode(n);n=document.createElement("span");n.appendChild(i);n.className="CodeMirror-foldmarker"}return n}function r(e,t,n){if(t&&void 0!==t[n])return t[n];var r=e.options.foldOptions;return r&&void 0!==r[n]?r[n]:i[n]}e.newFoldFunction=function(e,n){return function(r,i){t(r,i,{rangeFinder:e,widget:n})}};e.defineExtension("foldCode",function(e,n,r){t(this,e,n,r)});e.defineExtension("isFolded",function(e){for(var t=this.findMarksAt(e),n=0;n<t.length;++n)if(t[n].__isFold)return!0});e.commands.toggleFold=function(e){e.foldCode(e.getCursor())};e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")};e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")};e.commands.foldAll=function(t){t.operation(function(){for(var n=t.firstLine(),r=t.lastLine();r>=n;n++)t.foldCode(e.Pos(n,0),null,"fold")})};e.commands.unfoldAll=function(t){t.operation(function(){for(var n=t.firstLine(),r=t.lastLine();r>=n;n++)t.foldCode(e.Pos(n,0),null,"unfold")})};e.registerHelper("fold","combine",function(){var e=Array.prototype.slice.call(arguments,0);return function(t,n){for(var r=0;r<e.length;++r){var i=e[r](t,n);if(i)return i}}});e.registerHelper("fold","auto",function(e,t){for(var n=e.getHelpers(t,"fold"),r=0;r<n.length;r++){var i=n[r](e,t);if(i)return i}});var i={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};e.defineOption("foldOptions",null);e.defineExtension("foldOption",function(e,t){return r(this,e,t)})})},{codemirror:void 0}],24:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}(),t("./foldcode")):"function"==typeof e&&e.amd?e(["../../lib/codemirror","./foldcode"],i):i(CodeMirror)})(function(e){"use strict";function t(e){this.options=e;this.from=this.to=0}function n(e){e===!0&&(e={});null==e.gutter&&(e.gutter="CodeMirror-foldgutter");null==e.indicatorOpen&&(e.indicatorOpen="CodeMirror-foldgutter-open");null==e.indicatorFolded&&(e.indicatorFolded="CodeMirror-foldgutter-folded");return e}function r(e,t){for(var n=e.findMarksAt(c(t)),r=0;r<n.length;++r)if(n[r].__isFold&&n[r].find().from.line==t)return!0}function i(e){if("string"==typeof e){var t=document.createElement("div");t.className=e+" CodeMirror-guttermarker-subtle";return t}return e.cloneNode(!0)}function o(e,t,n){var o=e.state.foldGutter.options,s=t,a=e.foldOption(o,"minFoldSize"),l=e.foldOption(o,"rangeFinder");e.eachLine(t,n,function(t){var n=null;if(r(e,s))n=i(o.indicatorFolded);else{var u=c(s,0),p=l&&l(e,u);p&&p.to.line-p.from.line>=a&&(n=i(o.indicatorOpen))}e.setGutterMarker(t,o.gutter,n);++s})}function s(e){var t=e.getViewport(),n=e.state.foldGutter;if(n){e.operation(function(){o(e,t.from,t.to)});n.from=t.from;n.to=t.to}}function a(e,t,n){var r=e.state.foldGutter.options;n==r.gutter&&e.foldCode(c(t,0),r.rangeFinder)}function l(e){var t=e.state.foldGutter,n=e.state.foldGutter.options;t.from=t.to=0;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){s(e)},n.foldOnChangeTimeSpan||600)}function u(e){var t=e.state.foldGutter,n=e.state.foldGutter.options;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){var n=e.getViewport();t.from==t.to||n.from-t.to>20||t.from-n.to>20?s(e):e.operation(function(){if(n.from<t.from){o(e,n.from,t.from);t.from=n.from}if(n.to>t.to){o(e,t.to,n.to);t.to=n.to}})},n.updateViewportTimeSpan||400)}function p(e,t){var n=e.state.foldGutter,r=t.line;r>=n.from&&r<n.to&&o(e,r,r+1)}e.defineOption("foldGutter",!1,function(r,i,o){if(o&&o!=e.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",a);r.off("change",l);r.off("viewportChange",u);r.off("fold",p);r.off("unfold",p);r.off("swapDoc",s)}if(i){r.state.foldGutter=new t(n(i));s(r);r.on("gutterClick",a);r.on("change",l);r.on("viewportChange",u);r.on("fold",p);r.on("unfold",p);r.on("swapDoc",s)}});var c=e.Pos})},{"./foldcode":23,codemirror:void 0}],25:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t){return e.line-t.line||e.ch-t.ch}function n(e,t,n,r){this.line=t;this.ch=n;this.cm=e;this.text=e.getLine(t);this.min=r?r.from:e.firstLine();this.max=r?r.to-1:e.lastLine()}function r(e,t){var n=e.cm.getTokenTypeAt(d(e.line,t));return n&&/\btag\b/.test(n)}function i(e){if(!(e.line>=e.max)){e.ch=0;e.text=e.cm.getLine(++e.line);return!0}}function o(e){if(!(e.line<=e.min)){e.text=e.cm.getLine(--e.line);e.ch=e.text.length;return!0}}function s(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(i(e))continue;return}if(r(e,t+1)){var n=e.text.lastIndexOf("/",t),o=n>-1&&!/\S/.test(e.text.slice(n+1,t));e.ch=t+1;return o?"selfClose":"regular"}e.ch=t+1}}function a(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){g.lastIndex=t;e.ch=t;var n=g.exec(e.text);if(n&&n.index==t)return n}else e.ch=t}}function l(e){for(;;){g.lastIndex=e.ch;var t=g.exec(e.text);if(!t){if(i(e))continue;return}if(r(e,t.index+1)){e.ch=t.index+t[0].length;return t}e.ch=t.index+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){var n=e.text.lastIndexOf("/",t),i=n>-1&&!/\S/.test(e.text.slice(n+1,t));e.ch=t+1;return i?"selfClose":"regular"}e.ch=t}}function p(e,t){for(var n=[];;){var r,i=l(e),o=e.line,a=e.ch-(i?i[0].length:0);if(!i||!(r=s(e)))return;if("selfClose"!=r)if(i[1]){for(var u=n.length-1;u>=0;--u)if(n[u]==i[2]){n.length=u;break}if(0>u&&(!t||t==i[2]))return{tag:i[2],from:d(o,a),to:d(e.line,e.ch)}}else n.push(i[2])}}function c(e,t){for(var n=[];;){var r=u(e);if(!r)return;if("selfClose"!=r){var i=e.line,o=e.ch,s=a(e);if(!s)return;if(s[1])n.push(s[2]);else{for(var l=n.length-1;l>=0;--l)if(n[l]==s[2]){n.length=l;break}if(0>l&&(!t||t==s[2]))return{tag:s[2],from:d(e.line,e.ch),to:d(i,o)}}}else a(e)}}var d=e.Pos,h="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",f=h+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",g=new RegExp("<(/?)(["+h+"]["+f+"]*)","g");e.registerHelper("fold","xml",function(e,t){for(var r=new n(e,t.line,0);;){var i,o=l(r);if(!o||r.line!=t.line||!(i=s(r)))return;if(!o[1]&&"selfClose"!=i){var t=d(r.line,r.ch),a=p(r,o[2]);return a&&{from:t,to:a.from}}}});e.findMatchingTag=function(e,r,i){var o=new n(e,r.line,r.ch,i);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=s(o),u=l&&d(o.line,o.ch),h=l&&a(o);if(l&&h&&!(t(o,r)>0)){var f={from:d(o.line,o.ch),to:u,tag:h[2]};if("selfClose"==l)return{open:f,close:null,at:"open"};if(h[1])return{open:c(o,h[2]),close:f,at:"close"};o=new n(e,u.line,u.ch,i);return{open:f,close:p(o,h[2]),at:"open"}}}};e.findEnclosingTag=function(e,t,r){for(var i=new n(e,t.line,t.ch,r);;){var o=c(i);if(!o)break;var s=new n(e,t.line,t.ch,r),a=p(s,o.tag);if(a)return{open:o,close:a}}};e.scanForClosingTag=function(e,t,r,i){var o=new n(e,t.line,t.ch,i?{from:0,to:i}:null);return p(o,r)}})},{codemirror:void 0}],26:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t){this.cm=e;this.options=this.buildOptions(t);this.widget=this.onClose=null}function n(e){return"string"==typeof e?e:e.text}function r(e,t){function n(e,n){var i;i="string"!=typeof n?function(e){return n(e,t)}:r.hasOwnProperty(n)?r[n]:n;o[e]=i}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},i=e.options.customKeys,o=i?{}:r;if(i)for(var s in i)i.hasOwnProperty(s)&&n(s,i[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&n(s,a[s]);return o}function i(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t;this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints";this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var h=p.appendChild(document.createElement("li")),f=c[d],g=s+(d!=this.selectedHint?"":" "+a);null!=f.className&&(g=f.className+" "+g);h.className=g;f.render?f.render(h,o,f):h.appendChild(document.createTextNode(f.displayText||n(f)));h.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),E=m.left,v=m.bottom,x=!0;p.style.left=E+"px";p.style.top=v+"px";var y=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),N=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var I=p.getBoundingClientRect(),A=I.bottom-N;if(A>0){var T=I.bottom-I.top,L=m.top-(m.bottom-I.top);if(L-T>0){p.style.top=(v=m.top-T)+"px";x=!1}else if(T>N){p.style.height=N-5+"px";p.style.top=(v=m.bottom-I.top)+"px";var S=u.getCursor();if(o.from.ch!=S.ch){m=u.cursorCoords(S);p.style.left=(E=m.left)+"px";I=p.getBoundingClientRect()}}}var b=I.right-y;if(b>0){if(I.right-I.left>y){p.style.width=y-5+"px";b-=I.right-I.left-y}p.style.left=(E=m.left-b)+"px"}u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o}));if(t.options.closeOnUnfocus){var C;u.on("blur",this.onBlur=function(){C=setTimeout(function(){t.close()},100)});u.on("focus",this.onFocus=function(){clearTimeout(C)})}var R=u.getScrollInfo();u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),n=u.getWrapperElement().getBoundingClientRect(),r=v+R.top-e.top,i=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);x||(i+=p.offsetHeight);if(i<=n.top||i>=n.bottom)return t.close();p.style.top=r+"px";p.style.left=E+R.left-e.left+"px"});e.on(p,"dblclick",function(e){var t=i(p,e.target||e.srcElement);if(t&&null!=t.hintId){l.changeActive(t.hintId);l.pick()}});e.on(p,"click",function(e){var n=i(p,e.target||e.srcElement);if(n&&null!=n.hintId){l.changeActive(n.hintId);t.options.completeOnSingleClick&&l.pick()}});e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)});e.signal(o,"select",c[0],p.firstChild);return!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,n){if(!t)return e.showHint(n);n&&n.async&&(t.async=!0);var r={hint:t};if(n)for(var i in n)r[i]=n[i];return e.showHint(r)};e.defineExtension("showHint",function(n){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,n),i=r.options.hint;if(i){e.signal(this,"startCompletion",this);if(!i.async)return r.showHints(i(this,r.options));i(this,function(e){r.showHints(e)},r.options);return void 0}}});t.prototype={close:function(){if(this.active()){this.cm.state.completionActive=null;this.widget&&this.widget.close();this.onClose&&this.onClose();e.signal(this.cm,"endCompletion",this.cm)}},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var i=t.list[r];i.hint?i.hint(this.cm,t,i):this.cm.replaceRange(n(i),i.from||t.from,i.to||t.to,"complete");e.signal(t,"pick",i);this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e);return void 0},showWidget:function(t){function n(){if(!l){l=!0;p.close();p.cm.off("cursorActivity",a);t&&e.signal(t,"close")}}function r(){if(!l){e.signal(t,"update");var n=p.options.hint;n.async?n(p.cm,i,p.options):i(n(p.cm,p.options))}}function i(e){t=e;if(!l){if(!t||!t.list.length)return n();p.widget&&p.widget.close();p.widget=new o(p,t)}}function s(){if(u){g(u);u=0}}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);if(e.line!=d.line||t.length-e.ch!=h-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1)))p.close();else{u=f(r);p.widget&&p.widget.close()}}this.widget=new o(this,t);e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),h=this.cm.getLine(d.line).length,f=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},g=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a);this.onClose=n},buildOptions:function(e){var t=this.cm.options.hintOptions,n={};for(var r in l)n[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(n[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(n[r]=e[r]);return n}};o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null;this.hints.parentNode.removeChild(this.hints);this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;if(this.completion.options.closeOnUnfocus){e.off("blur",this.onBlur);e.off("focus",this.onFocus)}e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,n){t>=this.data.list.length?t=n?this.data.list.length-1:0:0>t&&(t=n?0:this.data.list.length-1);if(this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,"");r=this.hints.childNodes[this.selectedHint=t];r.className+=" "+a;r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3);e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}};e.registerHelper("hint","auto",function(t,n){var r,i=t.getHelpers(t.getCursor(),"hint");if(i.length)for(var o=0;o<i.length;o++){var s=i[o](t,n);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,n)});e.registerHelper("hint","fromList",function(t,n){for(var r=t.getCursor(),i=t.getTokenAt(r),o=[],s=0;s<n.words.length;s++){var a=n.words[s];a.slice(0,i.string.length)==i.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,i.start),to:e.Pos(r.line,i.end)}:void 0});e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{codemirror:void 0}],27:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.runMode=function(t,n,r,i){var o=e.getMode(e.defaults,n),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=i&&i.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="";r=function(e,t){if("\n"!=e){for(var n="",r=0;;){var i=e.indexOf(" ",r);if(-1==i){n+=e.slice(r);p+=e.length-r;break}p+=i-r;n+=e.slice(r,i);var o=l-p%l;p+=o;for(var s=0;o>s;++s)n+=" ";r=i+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-");c.appendChild(document.createTextNode(n))}else u.appendChild(document.createTextNode(n))}else{u.appendChild(document.createTextNode(a?"\r":e));p=0}}}for(var c=e.splitLines(t),d=i&&i.state||e.startState(o),h=0,f=c.length;f>h;++h){h&&r("\n");var g=new e.StringStream(c[h]);!g.string&&o.blankLine&&o.blankLine(d);for(;!g.eol();){var m=o.token(g,d);r(g.current(),m,h,g.start,d);g.start=g.pos}}}})},{codemirror:void 0}],28:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t,i,o){this.atOccurrence=!1;this.doc=e;null==o&&"string"==typeof t&&(o=!1);i=i?e.clipPos(i):r(0,0);this.pos={from:i,to:i};if("string"!=typeof t){t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g"));this.matches=function(n,i){if(n){t.lastIndex=0;for(var o,s,a=e.getLine(i.line).slice(0,i.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;o=u;s=o.index;l=o.index+(o[0].length||1);if(l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(i.line).length&&p++)}else{t.lastIndex=i.ch;var a=e.getLine(i.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(i.line,s),to:r(i.line,s+p),match:o}:void 0}}else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(i,o){if(i){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1){p=n(l,u,p);return{from:r(o.line,p),to:r(o.line,p+s.length)}}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1){p=n(l,u,p)+o.ch;return{from:r(o.line,p),to:r(o.line,p+s.length)}}}}:function(){};else{var u=s.split("\n");this.matches=function(t,n){var i=l.length-1;if(t){if(n.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(n.line).slice(0,u[i].length))!=l[l.length-1])return;for(var o=r(n.line,u[i].length),s=n.line-1,p=i-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(n.line+(l.length-1)>e.lastLine())){var c=e.getLine(n.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var h=r(n.line,d),s=n.line+1,p=1;i>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,u[i].length))==l[i])return{from:h,to:r(s,u[i].length)}}}}}}}function n(e,t,n){if(e.length==t.length)return n;for(var r=Math.min(n,e.length);;){var i=e.slice(0,r).toLowerCase().length;if(n>i)++r;else{if(!(i>n))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);n.pos={from:t,to:t};n.atOccurrence=!1;return!1}for(var n=this,i=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,i)){this.atOccurrence=!0;return this.pos.match||!0}if(e){if(!i.line)return t(0);i=r(i.line-1,this.doc.getLine(i.line-1).length)}else{var o=this.doc.lineCount();if(i.line==o-1)return t(o);i=r(i.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var n=e.splitLines(t);this.doc.replaceRange(n,this.pos.from,this.pos.to);this.pos.to=r(this.pos.from.line+n.length-1,n[n.length-1].length+(1==n.length?this.pos.from.ch:0))}}};e.defineExtension("getSearchCursor",function(e,n,r){return new t(this.doc,e,n,r)});e.defineDocExtension("getSearchCursor",function(e,n,r){return new t(this,e,n,r)});e.defineExtension("selectMatches",function(t,n){for(var r,i=[],o=this.getSearchCursor(t,this.getCursor("from"),n);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)i.push({anchor:o.from(),head:o.to()});i.length&&this.setSelections(i,0)})})},{codemirror:void 0}],29:[function(e,t){t.exports=e(12)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/node_modules/store/store.js":12}],30:[function(e,t){t.exports=e(13)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/package.json":13}],31:[function(e,t){t.exports=e(14)},{"../package.json":30,"./storage.js":32,"./svg.js":33,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/main.js":14}],32:[function(e,t){t.exports=e(15)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/storage.js":15,store:29}],33:[function(e,t){t.exports=e(16)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/svg.js":16}],34:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.3.8",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasqe.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasqe.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],35:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("../utils.js"),i=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e,t){var a={},l={},u={};t.on("cursorActivity",function(){d(!0)});t.on("change",function(){var e=[];for(var r in a)a[r].is(":visible")&&e.push(a[r]);if(e.length>0){var i=n(t.getWrapperElement()).find(".CodeMirror-vscrollbar"),o=0;i.is(":visible")&&(o=i.outerWidth());e.forEach(function(e){e.css("right",o)})}});var p=function(e,n){u[e.name]=new o;for(var s=0;s<n.length;s++)u[e.name].insert(n[s]);var a=r.getPersistencyId(t,e.persistent);a&&i.storage.set(a,n,"month")},c=function(e,n){var o=l[e]=new n(t,e);o.name=e;if(o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&p(o,e)};if(o.get instanceof Array)s(o.get);else{var a=null,u=r.getPersistencyId(t,o.persistent);u&&(a=i.storage.get(u));a&&a.length>0?s(a):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},d=function(r){if(!t.somethingSelected()){var i=function(n){if(r&&(!n.autoShow||!n.bulk&&n.async))return!1;var i={closeCharacters:/(?=a)b/,completeSingle:!1};!n.bulk&&n.async&&(i.async=!0);{var o=function(e,t){return h(n,t)};e.showHint(t,o,i)}return!0};for(var o in l)if(-1!=n.inArray(o,t.options.autocompleters)){var s=l[o];if(s.isValidCompletionPosition)if(s.isValidCompletionPosition()){if(!s.callbacks||!s.callbacks.validPosition||s.callbacks.validPosition(t,s)!==!1){var a=i(s);if(a)break}}else s.callbacks&&s.callbacks.invalidPosition&&s.callbacks.invalidPosition(t,s)}}},h=function(e,n){var r=function(t){var n=t.autocompletionString||t.string,r=[];if(u[e.name])r=u[e.name].autoComplete(n);else if("function"==typeof e.get&&0==e.async)r=e.get(n);else if("object"==typeof e.get)for(var i=n.length,o=0;o<e.get.length;o++){var s=e.get[o];s.slice(0,i)==n&&r.push(s)}return f(r,e,t)},i=t.getCompleteToken();e.preProcessToken&&(i=e.preProcessToken(i));if(i){if(e.bulk||!e.async)return r(i);var o=function(t){n(f(t,e,i))};e.get(i,o)}},f=function(e,n,r){for(var i=[],o=0;o<e.length;o++){var a=e[o];n.postProcessToken&&(a=n.postProcessToken(r,a));
i.push({text:a,displayText:a,hint:s})}var l=t.getCursor(),u={completionToken:r.string,list:i,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(n.callbacks)for(var p in n.callbacks)n.callbacks[p]&&t.on(u,p,n.callbacks[p]);return u};return{init:c,completers:l,notifications:{getEl:function(e){return n(a[e.name])},show:function(e,t){if(!t.autoshow){a[t.name]||(a[t.name]=n("<div class='completionNotification'></div>"));a[t.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(n(e.getWrapperElement()))}},hide:function(e,t){a[t.name]&&a[t.name].hide()}},autoComplete:d,getTrie:function(e){return"string"==typeof e?u[e]:u[e.name]}}};var s=function(e,t,n){n.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(n.text,t.from,t.to)}},{"../../lib/trie.js":19,"../utils.js":48,jquery:void 0,"yasgui-utils":31}],36:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})();t.exports=function(n,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(n)},get:function(t,r){return e("./utils").fetchFromLov(n,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(n,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(n,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:n.autocompleters.notifications.show,invalidPosition:n.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.indexOf("?"))return!1;var n=e.getCursor(),r=e.getPreviousNonWsToken(n.line,t);return"a"==r.string?!0:"rdf:type"==r.string?!0:"rdfs:domain"==r.string?!0:"rdfs:range"==r.string?!0:!1};t.exports.preProcessToken=function(t,n){return e("./utils.js").preprocessResourceTokenForCompletion(t,n)};t.exports.postProcessToken=function(t,n,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,n,r)}},{"./utils":39,"./utils.js":39,jquery:void 0}],37:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r={"string-2":"prefixed",atom:"var"};t.exports=function(e,r){e.on("change",function(){t.exports.appendPrefixIfNeeded(e,r)});return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(e)},get:function(e,t){n.get("http://prefix.cc/popular/all.file.json",function(e){var n=[];for(var r in e)if("bif"!=r){var i=r+": <"+e[r]+">";n.push(i)}n.sort();t(n)})},preProcessToken:function(n){return t.exports.preprocessPrefixTokenForCompletion(e,n)},async:!0,bulk:!0,autoShow:!0,persistent:r}};t.exports.isValidCompletionPosition=function(e){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;"ws"!=r.type&&(r=e.getCompleteToken());if(0==!r.string.indexOf("a")&&-1==n.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var i=e.getPreviousNonWsToken(t.line,r);return i&&"PREFIX"==i.string.toUpperCase()?!0:!1};t.exports.preprocessPrefixTokenForCompletion=function(e,t){var n=e.getPreviousNonWsToken(e.getCursor().line,t);n&&n.string&&":"==n.string.slice(-1)&&(t={start:n.start,end:t.end,string:n.string+" "+t.string,state:t.state});return t};t.exports.appendPrefixIfNeeded=function(e,t){if(e.autocompleters.getTrie(t)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(t)){var n=e.getCursor(),i=e.getTokenAt(n);if("prefixed"==r[i.type]){var o=i.string.indexOf(":");if(-1!==o){var s=e.getPreviousNonWsToken(n.line,i).string.toUpperCase(),a=e.getTokenAt({line:n.line,ch:i.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var l=i.string.substring(0,o+1),u=e.getPrefixesFromQuery();if(null==u[l.slice(0,-1)]){var p=e.autocompleters.getTrie(t).autoComplete(l);p.length>0&&e.addPrefixes(p[0])}}}}}}},{jquery:void 0}],38:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports=function(n,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(n)},get:function(t,r){return e("./utils").fetchFromLov(n,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(n,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(n,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:n.autocompleters.notifications.show,invalidPosition:n.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(n.inArray("a",t.state.possibleCurrent)>=0)return!0;var r=e.getCursor(),i=e.getPreviousNonWsToken(r.line,t);return"rdfs:subPropertyOf"==i.string?!0:!1};t.exports.preProcessToken=function(t,n){return e("./utils.js").preprocessResourceTokenForCompletion(t,n)};t.exports.postProcessToken=function(t,n,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,n,r)}},{"./utils":39,"./utils.js":39,jquery:void 0}],39:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=(e("./utils.js"),e("yasgui-utils")),i=function(e,t){var n=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")){t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1);null!=n[t.tokenPrefix.slice(0,-1)]&&(t.tokenPrefixUri=n[t.tokenPrefix.slice(0,-1)])}t.autocompletionString=t.string.trim();if(0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in n)if(0==t.string.indexOf(r)){t.autocompletionString=n[r];t.autocompletionString+=t.string.substring(r.length+1);break}0==t.autocompletionString.indexOf("<")&&(t.autocompletionString=t.autocompletionString.substring(1));-1!==t.autocompletionString.indexOf(">",t.length-1)&&(t.autocompletionString=t.autocompletionString.substring(0,t.autocompletionString.length-1));return t},o=function(e,t,n){n=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+n.substring(t.tokenPrefixUri.length):"<"+n+">";return n},s=function(t,i,o,s){if(!o||!o.string||0==o.string.trim().length){t.autocompleters.notifications.getEl(i).empty().append("Nothing to autocomplete yet!");return!1}var a=50,l={q:o.autocompletionString,page:1};l.type="classes"==i.name?"class":"property";var u=[],p="",c=function(){p="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+n.param(l)};c();var d=function(){l.page++;c()},h=function(){n.get(p,function(e){for(var r=0;r<e.results.length;r++)u.push(n.isArray(e.results[r].uri)&&e.results[r].uri.length>0?e.results[r].uri[0]:e.results[r].uri);if(u.length<e.total_results&&u.length<a){d();h()}else{u.length>0?t.autocompleters.notifications.hide(t,i):t.autocompleters.notifications.getEl(i).text("0 matches found...");s(u)}}).fail(function(){t.autocompleters.notifications.getEl(i).empty().append("Failed fetching suggestions..")})};t.autocompleters.notifications.getEl(i).empty().append(n("<span>Fetchting autocompletions </span>")).append(n(r.svg.getElement(e("../imgs.js").loader)).addClass("notificationLoader"));h()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:i,postprocessResourceTokenForCompletion:o}},{"../imgs.js":42,"./utils.js":39,jquery:void 0,"yasgui-utils":31}],40:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());if("ws"!=t.type){t=e.getCompleteToken(t);if(t&&0==t.string.indexOf("?"))return!0}return!1},get:function(t){if(0==t.trim().length)return[];var r={};n(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var i=n(this).next(),o=i.attr("class");o&&i.attr("class").indexOf("cm-atom")>=0&&(e+=i.text());if(e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var i=[];for(var o in r)i.push(o);i.sort();return i},async:!1,bulk:!1,autoShow:!0}}},{jquery:void 0}],41:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=e("./main.js");n.defaults=t.extend(!0,{},n.defaults,{mode:"sparql11",value:"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nSELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,lineWrapping:!0,backdrop:!1,foldGutter:{rangeFinder:n.fold.brace},gutters:["gutterErrorBar","CodeMirror-linenumbers","CodeMirror-foldgutter"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":n.autoComplete,"Cmd-Space":n.autoComplete,"Ctrl-D":n.deleteLine,"Ctrl-K":n.deleteLine,"Cmd-D":n.deleteLine,"Cmd-K":n.deleteLine,"Ctrl-/":n.commentLines,"Cmd-/":n.commentLines,"Ctrl-Alt-Down":n.copyLineDown,"Ctrl-Alt-Up":n.copyLineUp,"Cmd-Alt-Down":n.copyLineDown,"Cmd-Alt-Up":n.copyLineUp,"Shift-Ctrl-F":n.doAutoFormat,"Shift-Cmd-F":n.doAutoFormat,"Ctrl-]":n.indentMore,"Cmd-]":n.indentMore,"Ctrl-[":n.indentLess,"Cmd-[":n.indentLess,"Ctrl-S":n.storeQuery,"Cmd-S":n.storeQuery,"Ctrl-Enter":n.executeQuery,"Cmd-Enter":n.executeQuery,F11:function(e){e.setOption("fullScreen",!e.getOption("fullScreen"))},Esc:function(e){e.getOption("fullScreen")&&e.setOption("fullScreen",!1)}},cursorHeight:.9,createShareLink:n.createShareLink,consumeShareLink:n.consumeShareLink,persistent:function(e){return"yasqe_"+t(e.getWrapperElement()).closest("[id]").attr("id")+"_queryVal"},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})},{"./main.js":43,jquery:void 0}],42:[function(e,t){"use strict";t.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g ></g><g > <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="warning.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" inkscape:zoom="3.1936344" inkscape:cx="36.8135" inkscape:cy="36.9485" inkscape:window-x="2625" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /><g transform="translate(-2.995,-2.411)" /><g transform="translate(-2.995,-2.411)" ><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" inkscape:connector-curvature="0" /></g><path d="M 66.129381,65.903784 H 49.769875 c -1.64721,0 -2.889385,-0.581146 -3.498678,-1.63595 -0.609293,-1.055608 -0.491079,-2.422161 0.332391,-3.848223 l 8.179753,-14.167069 c 0.822934,-1.42633 1.9477,-2.211737 3.166018,-2.211737 1.218319,0 2.343086,0.785407 3.166019,2.211737 l 8.179751,14.167069 c 0.823472,1.426062 0.941686,2.792615 0.33239,3.848223 -0.609023,1.054804 -1.851197,1.63595 -3.498138,1.63595 z M 59.618815,60.91766 c 0,-0.850276 -0.68944,-1.539719 -1.539717,-1.539719 -0.850276,0 -1.539718,0.689443 -1.539718,1.539719 0,0.850277 0.689442,1.539718 1.539718,1.539718 0.850277,0 1.539717,-0.689441 1.539717,-1.539718 z m 0.04155,-9.265919 c 0,-0.873061 -0.707939,-1.580998 -1.580999,-1.580998 -0.873061,0 -1.580999,0.707937 -1.580999,1.580998 l 0.373403,5.610965 h 0.0051 c 0.05415,0.619747 0.568548,1.10761 1.202504,1.10761 0.586239,0 1.075443,-0.415756 1.188563,-0.968489 0.0092,-0.04476 0.0099,-0.09248 0.01392,-0.138854 h 0.01072 l 0.367776,-5.611232 z" inkscape:connector-curvature="0" style="fill:#aa8800" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g ></g><g > <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}},{}],43:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=function(){try{return e("codemirror")}catch(t){return window.CodeMirror}}(),i=e("./utils.js"),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/hint/show-hint.js");e("codemirror/addon/search/searchcursor.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/addon/runmode/runmode.js");e("codemirror/addon/display/fullscreen.js");e("../lib/flint.js");var a=t.exports=function(e,t){var i=n("<div>",{"class":"yasqe"}).appendTo(n(e));t=l(t);var o=u(r(i[0],t));d(o);return o},l=function(e){var t=n.extend(!0,{},a.defaults,e);return t},u=function(t){t.autocompleters=e("./autocompleters/autocompleterBase.js")(a,t);t.options.autocompleters&&t.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])});t.getCompleteToken=function(n,r){return e("./tokenUtils.js").getCompleteToken(t,n,r)};t.getPreviousNonWsToken=function(n,r){return e("./tokenUtils.js").getPreviousNonWsToken(t,n,r)};t.getNextNonWsToken=function(n,r){return e("./tokenUtils.js").getNextNonWsToken(t,n,r)};var r=null,i=null;t.setBackdrop=function(e){if(t.options.backdrop||0===t.options.backdrop||"0"===t.options.backdrop){if(null===i){i=+t.options.backdrop;1===i&&(i=400)}r||(r=n("<div>",{"class":"backdrop"}).click(function(){n(this).hide()}).insertAfter(n(t.getWrapperElement())));e?r.show(i):r.hide(i)}};t.query=function(e){a.executeQuery(t,e)};t.getUrlArguments=function(e){return a.getUrlArguments(t,e)};t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)};t.addPrefixes=function(n){return e("./prefixUtils.js").addPrefixes(t,n)};t.removePrefixes=function(n){return e("./prefixUtils.js").removePrefixes(t,n)};t.getValueWithoutComments=function(){var e="";a.runMode(t.getValue(),"sparql11",function(t,n){"comment"!=n&&(e+=t)});return e};t.getQueryType=function(){return t.queryType};t.getQueryMode=function(){var e=t.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"};t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e;f(t)};t.enableCompleter=function(e){p(t.options,e);a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])};t.disableCompleter=function(e){c(t.options,e)};return t},p=function(e,t){e.autocompleters||(e.autocompleters=[]);e.autocompleters.push(t)},c=function(e,t){if("object"==typeof e.autocompleters){var r=n.inArray(t,e.autocompleters);if(r>=0){e.autocompleters.splice(r,1);c(e,t)}}},d=function(e){var t=i.getPersistencyId(e,e.options.persistent);if(t){var r=o.storage.get(t);r&&e.setValue(r)}a.drawButtons(e);e.on("blur",function(e){a.storeQuery(e)});e.on("change",function(e){f(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("changes",function(){f(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("cursorActivity",function(e){h(e)});e.prevQueryValid=!1;f(e);a.positionButtons(e);if(e.options.consumeShareLink){var s=n.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},h=function(e){e.cursor=n(".CodeMirror-cursor");e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(i.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},f=function(t,r){t.queryValid=!0;t.clearGutter("gutterErrorBar");for(var i=null,a=0;a<t.lineCount();++a){var l=!1;t.prevQueryValid||(l=!0);var u=t.getTokenAt({line:a,ch:t.getLine(a).length},l),i=u.state;t.queryType=i.queryType;if(0==i.OK){if(!t.options.syntaxErrorCheck){n(t.getWrapperElement).find(".sp-error").css("color","black");return}var p=o.svg.getElement(s.warning);i.possibleCurrent&&i.possibleCurrent.length>0&&e("./tooltip")(t,p,function(){var e=[];i.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+n("<div/>").text(t).html()+"</strong>")});return"This line is invalid. Expected: "+e.join(", ")});p.style.marginTop="2px";p.style.marginLeft="2px";p.className="parseErrorIcon";t.setGutterMarker(a,"gutterErrorBar",p);t.queryValid=!1;break}}t.prevQueryValid=t.queryValid;if(r&&null!=i&&void 0!=i.stack){var c=i.stack,d=i.stack.length;d>1?t.queryValid=!1:1==d&&"solutionModifier"!=c[0]&&"?limitOffsetClauses"!=c[0]&&"?offsetClause"!=c[0]&&(t.queryValid=!1)}};n.extend(a,r);a.Autocompleters={};a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t;p(a.defaults,e)};a.autoComplete=function(e){e.autocompleters.autoComplete(!1)};a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js"));a.registerAutocompleter("properties",e("./autocompleters/properties.js"));a.registerAutocompleter("classes",e("./autocompleters/classes.js"));a.registerAutocompleter("variables",e("./autocompleters/variables.js"));a.positionButtons=function(e){var t=n(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),r=0;t.is(":visible")&&(r=t.outerWidth());e.buttons.is(":visible")&&e.buttons.css("right",r+6)};a.createShareLink=function(e){var t=n.deparam(window.location.search.substring(1));t.query=e.getValue();return t};a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)};a.drawButtons=function(e){e.buttons=n("<div class='yasqe_buttons'></div>").appendTo(n(e.getWrapperElement()));if(e.options.createShareLink){var t=n(o.svg.getElement(s.share));t.click(function(r){r.stopPropagation();var i=n("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);n("html").click(function(){i&&i.remove()});i.click(function(e){e.stopPropagation()});var o=n("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+n.param(e.options.createShareLink(e)));o.focus(function(){var e=n(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});i.empty().append(o);var s=t.position();i.css("top",s.top+t.outerHeight()+"px").css("left",s.left+t.outerWidth()-i.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}var r=n("<div>",{"class":"fullscreenToggleBtns"}).append(n(o.svg.getElement(s.fullscreen)).addClass("yasqe_fullscreenBtn").attr("title","Set editor full screen").click(function(){e.setOption("fullScreen",!0)})).append(n(o.svg.getElement(s.smallscreen)).addClass("yasqe_smallscreenBtn").attr("title","Set editor to normale size").click(function(){e.setOption("fullScreen",!1)}));e.buttons.append(r);if(e.options.sparql.showQueryButton){n("<div>",{"class":"yasqe_queryButton"}).click(function(){if(n(this).hasClass("query_busy")){e.xhr&&e.xhr.abort();a.updateQueryButton(e)}else e.query()}).appendTo(e.buttons);a.updateQueryButton(e)}};var g={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var r=n(e.getWrapperElement()).find(".yasqe_queryButton");if(0!=r.length){if(!t){t="valid";e.queryValid===!1&&(t="error")}if(t!=e.queryStatus&&("busy"==t||"valid"==t||"error"==t)){r.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t);o.svg.draw(r,s[g[t]]);e.queryStatus=t}}};a.fromTextArea=function(e,t){t=l(t);var i=(n("<div>",{"class":"yasqe"}).insertBefore(n(e)).append(n(e)),u(r.fromTextArea(e,t)));d(i);return i};a.storeQuery=function(e){var t=i.getPersistencyId(e,e.options.persistent);t&&o.storage.set(t,e.getValue(),"month")};a.commentLines=function(e){for(var t=e.getCursor(!0).line,n=e.getCursor(!1).line,r=Math.min(t,n),i=Math.max(t,n),o=!0,s=r;i>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;i>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})};a.copyLineUp=function(e){var t=e.getCursor(),n=e.lineCount();e.replaceRange("\n",{line:n-1,ch:e.getLine(n-1).length});for(var r=n;r>t.line;r--){var i=e.getLine(r-1);e.replaceRange(i,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}};a.copyLineDown=function(e){a.copyLineUp(e);var t=e.getCursor();t.line++;e.setCursor(t)};a.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};m(e,e.getCursor(!0),t)}else{var n=e.lineCount(),r=e.getTextArea().value.length;m(e,{line:0,ch:0},{line:n,ch:r})}};var m=function(e,t,n){var r=e.indexFromPos(t),i=e.indexFromPos(n),o=E(e.getValue(),r,i);e.operation(function(){e.replaceRange(o,t,n);for(var i=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=i;s>=a;a++)e.indentLine(a,"smart")})},E=function(e,t,i){e=e.substring(t,i);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=n.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];r.runMode(e,"sparql11",function(e,t){c.push(t);var n=l(e,t);if(0!=n){if(1==n){u+=e+"\n";p=""}else{u+="\n"+e;p=e}c=[]}else{p+=e;u+=e}1==c.length&&"sp-ws"==c[0]&&(c=[])});return n.trim(u.replace(/\n\s*\n/g,"\n"))
};e("./sparql.js"),e("./defaults.js");a.version={CodeMirror:r.version,YASQE:e("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":17,"../lib/flint.js":18,"../package.json":34,"./autocompleters/autocompleterBase.js":35,"./autocompleters/classes.js":36,"./autocompleters/prefixes.js":37,"./autocompleters/properties.js":38,"./autocompleters/variables.js":40,"./defaults.js":41,"./imgs.js":42,"./prefixUtils.js":44,"./sparql.js":45,"./tokenUtils.js":46,"./tooltip":47,"./utils.js":48,codemirror:void 0,"codemirror/addon/display/fullscreen.js":20,"codemirror/addon/edit/matchbrackets.js":21,"codemirror/addon/fold/brace-fold.js":22,"codemirror/addon/fold/foldcode.js":23,"codemirror/addon/fold/foldgutter.js":24,"codemirror/addon/fold/xml-fold.js":25,"codemirror/addon/hint/show-hint.js":26,"codemirror/addon/runmode/runmode.js":27,"codemirror/addon/search/searchcursor.js":28,jquery:void 0,"yasgui-utils":31}],44:[function(e,t){"use strict";var n=function(e,t){var n=e.getPrefixesFromQuery();if("string"==typeof t)r(e,t);else for(var i in t)i in n||r(e,i+": <"+t[i]+">")},r=function(e,t){for(var n=null,r=0,i=e.lineCount(),o=0;i>o;o++){var a=e.getNextNonWsToken(o);if(null!=a&&("PREFIX"==a.string||"BASE"==a.string)){n=a;r=o}}if(null==n)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=s(e,r);e.replaceRange("\n"+l+"PREFIX "+t,{line:r})}},i=function(e,t){var n=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var r in t)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+r+":\\s*"+n("<"+t[r]+">")+"\\s*","ig"),""))},o=function(e){for(var t={},n=!0,r=function(i,s){if(n){s||(s=1);var a=e.getNextNonWsToken(o,s);if(a){-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(n=!1);if("PREFIX"==a.string.toUpperCase()){var l=e.getNextNonWsToken(o,a.end+1);if(l){var u=e.getNextNonWsToken(o,l.end+1);if(u){var p=u.string;0==p.indexOf("<")&&(p=p.substring(1));">"==p.slice(-1)&&(p=p.substring(0,p.length-1));t[l.string.slice(0,-1)]=p;r(i,u.end+1)}else r(i,l.end+1)}else r(i,a.end+1)}else r(i,a.end+1)}}},i=e.lineCount(),o=0;i>o&&n;o++)r(o);return t},s=function(e,t,n){void 0==n&&(n=1);var r=e.getTokenAt({line:t,ch:n});return null==r||void 0==r||"ws"!=r.type?"":r.string+s(e,t,r.end+1)};t.exports={addPrefixes:n,getPrefixesFromQuery:o,removePrefixes:i}},{}],45:[function(e){"use strict";var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=e("./main.js");n.executeQuery=function(e,i){var o="function"==typeof i?i:null,s="object"==typeof i?i:{};e.options.sparql&&(s=t.extend({},e.options.sparql,s));s.handlers&&t.extend(!0,s.callbacks,s.handlers);if(s.endpoint&&0!=s.endpoint.length){var a={url:"function"==typeof s.endpoint?s.endpoint(e):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(e):s.requestMethod,headers:{Accept:r(e,s)}},l=!1;if(s.callbacks)for(var u in s.callbacks)if(s.callbacks[u]){l=!0;a[u]=s.callbacks[u]}a.data=e.getUrlArguments(s);if(l||o){o&&(a.complete=o);s.headers&&!t.isEmptyObject(s.headers)&&t.extend(a.headers,s.headers);n.updateQueryButton(e,"busy");e.setBackdrop(!0);var p=function(){n.updateQueryButton(e);e.setBackdrop(!1)};a.complete=a.complete?[p,a.complete]:p;e.xhr=t.ajax(a)}}};n.getUrlArguments=function(e,n){var r=e.getQueryMode(),i=[{name:e.getQueryMode(),value:e.getValue()}];if(n.namedGraphs&&n.namedGraphs.length>0)for(var o="query"==r?"named-graph-uri":"using-named-graph-uri ",s=0;s<n.namedGraphs.length;s++)i.push({name:o,value:n.namedGraphs[s]});if(n.defaultGraphs&&n.defaultGraphs.length>0)for(var o="query"==r?"default-graph-uri":"using-graph-uri ",s=0;s<n.defaultGraphs.length;s++)i.push({name:o,value:n.defaultGraphs[s]});n.args&&n.args.length>0&&t.merge(i,n.args);return i};var r=function(e,t){var n=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())n="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var r=e.getQueryType();n="DESCRIBE"==r||"CONSTRUCT"==r?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else n="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return n}},{"./main.js":43,jquery:void 0}],46:[function(e,t){"use strict";var n=function(e,t,r){r||(r=e.getCursor());t||(t=e.getTokenAt(r));var i=e.getTokenAt({line:r.line,ch:t.start});if(null!=i.type&&"ws"!=i.type&&null!=t.type&&"ws"!=t.type){t.start=i.start;t.string=i.string+t.string;return n(e,t,{line:r.line,ch:i.start})}if(null!=t.type&&"ws"==t.type){t.start=t.start+1;t.string=t.string.substring(1);return t}return t},r=function(e,t,n){var i=e.getTokenAt({line:t,ch:n.start});null!=i&&"ws"==i.type&&(i=r(e,t,i));return i},i=function(e,t,n){void 0==n&&(n=1);var r=e.getTokenAt({line:t,ch:n});return null==r||void 0==r||r.end<n?null:"ws"==r.type?i(e,t,r.end+1):r};t.exports={getPreviousNonWsToken:r,getCompleteToken:n,getNextNonWsToken:i}},{}],47:[function(e,t){"use strict";{var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("./utils.js")}t.exports=function(e,t,r){var i,t=n(t);t.hover(function(){"function"==typeof r&&(r=r());i=n("<div>").addClass("yasqe_tooltip").html(r).appendTo(t);o()},function(){n(".yasqe_tooltip").remove()});var o=function(){if(n(e.getWrapperElement()).offset().top>=i.offset().top){i.css("bottom","auto");i.css("top","26px")}}}},{"./utils.js":48,jquery:void 0}],48:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=function(e,t){var n=!1;try{void 0!==e[t]&&(n=!0)}catch(r){}return n},i=function(e,t){var n=null;t&&(n="string"==typeof t?t:t(e));return n},o=function(){function e(e){var t,r,i;t=n(e).offset();r=n(e).width();i=n(e).height();return[[t.left,t.left+r],[t.top,t.top+i]]}function t(e,t){var n,r;n=e[0]<t[0]?e:t;r=e[0]<t[0]?t:e;return n[1]>r[0]||n[0]===r[0]}return function(n,r){var i=e(n),o=e(r);return t(i[0],o[0])&&t(i[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:i,elementsOverlap:o}},{jquery:void 0}],49:[function(e){var t,n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=n(document),i=n("head"),o=null,s=[],a=0,l="id",u="px",p="JColResizer",c=parseInt,d=Math,h=navigator.userAgent.indexOf("Trident/4.0")>0;try{t=sessionStorage}catch(f){}i.append("<style type='text/css'> .JColResizer{table-layout:fixed;} .JColResizer td, .JColResizer th{overflow:hidden;padding-left:0!important; padding-right:0!important;} .JCLRgrips{ height:0px; position:relative;} .JCLRgrip{margin-left:-5px; position:absolute; z-index:5; } .JCLRgrip .JColResizer{position:absolute;background-color:red;filter:alpha(opacity=1);opacity:0;width:10px;height:100%;top:0px} .JCLRLastGrip{position:absolute; width:1px; } .JCLRgripDrag{ border-left:1px dotted black; }</style>");var g=function(e,t){var r=n(e);if(t.disable)return m(r);var i=r.id=r.attr(l)||p+a++;r.p=t.postbackSafe;if(r.is("table")&&!s[i]){r.addClass(p).attr(l,i).before('<div class="JCLRgrips"/>');r.opt=t;r.g=[];r.c=[];r.w=r.width();r.gc=r.prev();t.marginLeft&&r.gc.css("marginLeft",t.marginLeft);t.marginRight&&r.gc.css("marginRight",t.marginRight);r.cs=c(h?e.cellSpacing||e.currentStyle.borderSpacing:r.css("border-spacing"))||2;r.b=c(h?e.border||e.currentStyle.borderLeftWidth:r.css("border-left-width"))||1;s[i]=r;E(r)}},m=function(e){var t=e.attr(l),e=s[t];if(e&&e.is("table")){e.removeClass(p).gc.remove();delete s[t]}},E=function(e){var r=e.find(">thead>tr>th,>thead>tr>td");r.length||(r=e.find(">tbody>tr:first>th,>tr:first>th,>tbody>tr:first>td, >tr:first>td"));e.cg=e.find("col");e.ln=r.length;e.p&&t&&t[e.id]&&v(e,r);r.each(function(t){var r=n(this),i=n(e.gc.append('<div class="JCLRgrip"></div>')[0].lastChild);i.t=e;i.i=t;i.c=r;r.w=r.width();e.g.push(i);e.c.push(r);r.width(r.w).removeAttr("width");t<e.ln-1?i.bind("touchstart mousedown",A).append(e.opt.gripInnerHtml).append('<div class="'+p+'" style="cursor:'+e.opt.hoverCursor+'"></div>'):i.addClass("JCLRLastGrip").removeClass("JCLRgrip");i.data(p,{i:t,t:e.attr(l)})});e.cg.removeAttr("width");x(e);e.find("td, th").not(r).not("table th, table td").each(function(){n(this).removeAttr("width")})},v=function(e,n){var r,i=0,o=0,s=[];if(n){e.cg.removeAttr("width");if(e.opt.flush){t[e.id]="";return}r=t[e.id].split(";");for(;o<e.ln;o++){s.push(100*r[o]/r[e.ln]+"%");n.eq(o).css("width",s[o])}for(o=0;o<e.ln;o++)e.cg.eq(o).css("width",s[o])}else{t[e.id]="";for(;o<e.c.length;o++){r=e.c[o].width();t[e.id]+=r+";";i+=r}t[e.id]+=i}},x=function(e){e.gc.width(e.w);for(var t=0;t<e.ln;t++){var n=e.c[t];e.g[t].css({left:n.offset().left-e.offset().left+n.outerWidth(!1)+e.cs/2+u,height:e.opt.headerOnly?e.c[0].outerHeight(!1):e.outerHeight(!1)})}},y=function(e,t,n){var r=o.x-o.l,i=e.c[t],s=e.c[t+1],a=i.w+r,l=s.w-r;i.width(a+u);s.width(l+u);e.cg.eq(t).width(a+u);e.cg.eq(t+1).width(l+u);if(n){i.w=a;s.w=l}},N=function(e){if(o){var t=o.t;if(e.originalEvent.touches)var n=e.originalEvent.touches[0].pageX-o.ox+o.l;else var n=e.pageX-o.ox+o.l;var r=t.opt.minWidth,i=o.i,s=1.5*t.cs+r+t.b,a=i==t.ln-1?t.w-s:t.g[i+1].position().left-t.cs-r,l=i?t.g[i-1].position().left+t.cs+r:s;n=d.max(l,d.min(a,n));o.x=n;o.css("left",n+u);if(t.opt.liveDrag){y(t,i);x(t);var p=t.opt.onDrag;if(p){e.currentTarget=t[0];p(e)}}return!1}},I=function(e){r.unbind("touchend."+p+" mouseup."+p).unbind("touchmove."+p+" mousemove."+p);n("head :last-child").remove();if(o){o.removeClass(o.t.opt.draggingClass);var i=o.t,s=i.opt.onResize;if(o.x){y(i,o.i,!0);x(i);if(s){e.currentTarget=i[0];s(e)}}i.p&&t&&v(i);o=null}},A=function(e){var t=n(this).data(p),a=s[t.t],l=a.g[t.i];l.ox=e.originalEvent.touches?e.originalEvent.touches[0].pageX:e.pageX;l.l=l.position().left;r.bind("touchmove."+p+" mousemove."+p,N).bind("touchend."+p+" mouseup."+p,I);i.append("<style type='text/css'>*{cursor:"+a.opt.dragCursor+"!important}</style>");l.addClass(a.opt.draggingClass);o=l;if(a.c[t.i].l)for(var u,c=0;c<a.ln;c++){u=a.c[c];u.l=!1;u.w=u.width()}return!1},T=function(){for(t in s){var e,t=s[t],n=0;t.removeClass(p);if(t.w!=t.width()){t.w=t.width();for(e=0;e<t.ln;e++)n+=t.c[e].w;for(e=0;e<t.ln;e++)t.c[e].css("width",d.round(1e3*t.c[e].w/n)/10+"%").l=!0}x(t.addClass(p))}};n(window).bind("resize."+p,T);n.fn.extend({colResizable:function(e){var t={draggingClass:"JCLRgripDrag",gripInnerHtml:"",liveDrag:!1,minWidth:15,headerOnly:!1,hoverCursor:"e-resize",dragCursor:"e-resize",postbackSafe:!1,flush:!1,marginLeft:null,marginRight:null,disable:!1,onDrag:null,onResize:null},e=n.extend(t,e);return this.each(function(){g(this,e)})}})},{jquery:void 0}],50:[function(e){RegExp.escape=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.csv={defaults:{separator:",",delimiter:'"',headers:!0},hooks:{castToScalar:function(e){var t=/\./;if(isNaN(e))return e;if(t.test(e))return parseFloat(e);var n=parseInt(e);return isNaN(n)?null:n}},parsers:{parse:function(e,t){function n(){l=0;u="";if(t.start&&t.state.rowNum<t.start){a=[];t.state.rowNum++;t.state.colNum=1}else{if(void 0===t.onParseEntry)s.push(a);else{var e=t.onParseEntry(a,t.state);e!==!1&&s.push(e)}a=[];t.end&&t.state.rowNum>=t.end&&(p=!0);t.state.rowNum++;t.state.colNum=1}}function r(){if(void 0===t.onParseValue)a.push(u);else{var e=t.onParseValue(u,t.state);e!==!1&&a.push(e)}u="";l=0;t.state.colNum++}var i=t.separator,o=t.delimiter;t.state.rowNum||(t.state.rowNum=1);t.state.colNum||(t.state.colNum=1);var s=[],a=[],l=0,u="",p=!1,c=RegExp.escape(i),d=RegExp.escape(o),h=/(D|S|\n|\r|[^DS\r\n]+)/,f=h.source;f=f.replace(/S/g,c);f=f.replace(/D/g,d);h=RegExp(f,"gm");e.replace(h,function(e){if(!p)switch(l){case 0:if(e===i){u+="";r();break}if(e===o){l=1;break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;u+=e;l=3;break;case 1:if(e===o){l=2;break}u+=e;l=1;break;case 2:if(e===o){u+=e;l=1;break}if(e===i){r();break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===i){r();break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;if(e===o)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}});if(0!==a.length){r();n()}return s},splitLines:function(e,t){function n(){s=0;if(t.start&&t.state.rowNum<t.start){a="";t.state.rowNum++}else{if(void 0===t.onParseEntry)o.push(a);else{var e=t.onParseEntry(a,t.state);e!==!1&&o.push(e)}a="";t.end&&t.state.rowNum>=t.end&&(l=!0);t.state.rowNum++}}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1);var o=[],s=0,a="",l=!1,u=RegExp.escape(r),p=RegExp.escape(i),c=/(D|S|\n|\r|[^DS\r\n]+)/,d=c.source;d=d.replace(/S/g,u);d=d.replace(/D/g,p);c=RegExp(d,"gm");e.replace(c,function(e){if(!l)switch(s){case 0:if(e===r){a+=e;s=0;break}if(e===i){a+=e;s=1;break}if("\n"===e){n();break}if(/^\r$/.test(e))break;a+=e;s=3;break;case 1:if(e===i){a+=e;s=2;break}a+=e;s=1;break;case 2:var o=a.substr(a.length-1);if(e===i&&o===i){a+=e;s=1;break}if(e===r){a+=e;s=0;break}if("\n"===e){n();break}if("\r"===e)break;throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");case 3:if(e===r){a+=e;s=0;break}if("\n"===e){n();break}if("\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal quote [Row:"+t.state.rowNum+"]");throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");default:throw new Error("CSVDataError: Unknown state [Row:"+t.state.rowNum+"]")}});""!==a&&n();return o},parseEntry:function(e,t){function n(){if(void 0===t.onParseValue)o.push(a);else{var e=t.onParseValue(a,t.state);e!==!1&&o.push(e)}a="";s=0;t.state.colNum++}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1);t.state.colNum||(t.state.colNum=1);var o=[],s=0,a="";if(!t.match){var l=RegExp.escape(r),u=RegExp.escape(i),p=/(D|S|\n|\r|[^DS\r\n]+)/,c=p.source;c=c.replace(/S/g,l);c=c.replace(/D/g,u);t.match=RegExp(c,"gm")}e.replace(t.match,function(e){switch(s){case 0:if(e===r){a+="";n();break}if(e===i){s=1;break}if("\n"===e||"\r"===e)break;a+=e;s=3;break;case 1:if(e===i){s=2;break}a+=e;s=1;break;case 2:if(e===i){a+=e;s=1;break}if(e===r){n();break}if("\n"===e||"\r"===e)break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===r){n();break}if("\n"===e||"\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}});n();return o}},toArray:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;var o=void 0!==n.state?n.state:{},n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,state:o},s=t.csv.parsers.parseEntry(e,n);if(!i.callback)return s;i.callback("",s);return void 0},toArrays:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;var o=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1}};o=t.csv.parsers.parse(e,n);if(!i.callback)return o;i.callback("",o);return void 0},toObjects:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;i.headers="headers"in n?n.headers:t.csv.defaults.headers;n.start="start"in n?n.start:1;i.headers&&n.start++;n.end&&i.headers&&n.end++;var o=[],s=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1},match:!1},a={delimiter:i.delimiter,separator:i.separator,start:1,end:1,state:{rowNum:1,colNum:1}},l=t.csv.parsers.splitLines(e,a),u=t.csv.toArray(l[0],n),o=t.csv.parsers.splitLines(e,n);n.state.colNum=1;n.state.rowNum=u?2:1;for(var p=0,c=o.length;c>p;p++){var d=t.csv.toArray(o[p],n),h={};for(var f in u)h[u[f]]=d[f];s.push(h);n.state.rowNum++}if(!i.callback)return s;i.callback("",s);return void 0},fromArrays:function(e,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:t.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;o.escaper="escaper"in n?n.escaper:t.csv.defaults.escaper;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var s=[];for(i in e)s.push(e[i]);if(!o.callback)return s;o.callback("",s);return void 0},fromObjects2CSV:function(e,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:t.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var s=[];for(i in e)s.push(arrays[i]);if(!o.callback)return s;o.callback("",s);return void 0}};t.csvEntry2Array=t.csv.toArray;t.csv2Array=t.csv.toArrays;t.csv2Dictionary=t.csv.toObjects},{jquery:void 0}],51:[function(e,t){t.exports=e(21)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/edit/matchbrackets.js":21,codemirror:void 0}],52:[function(e,t){t.exports=e(22)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/brace-fold.js":22,codemirror:void 0}],53:[function(e,t){t.exports=e(23)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/foldcode.js":23,codemirror:void 0}],54:[function(e,t){t.exports=e(24)},{"./foldcode":53,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/foldgutter.js":24,codemirror:void 0}],55:[function(e,t){t.exports=e(25)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/xml-fold.js":25,codemirror:void 0}],56:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("javascript",function(t,n){function r(e){for(var t,n=!1,r=!1;null!=(t=e.next());){if(!n){if("/"==t&&!r)return;"["==t?r=!0:r&&"]"==t&&(r=!1)}n=!n&&"\\"==t}}function i(e,t,n){gt=e;mt=n;return t}function o(e,t){var n=e.next();if('"'==n||"'"==n){t.tokenize=s(n);return t.tokenize(e,t)}if("."==n&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return i("number","number");if("."==n&&e.match(".."))return i("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return i(n);if("="==n&&e.eat(">"))return i("=>","operator");if("0"==n&&e.eat(/x/i)){e.eatWhile(/[\da-f]/i);return i("number","number")}if(/\d/.test(n)){e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);return i("number","number")}if("/"==n){if(e.eat("*")){t.tokenize=a;return a(e,t)}if(e.eat("/")){e.skipToEnd();return i("comment","comment")}if("operator"==t.lastType||"keyword c"==t.lastType||"sof"==t.lastType||/^[\[{}\(,;:]$/.test(t.lastType)){r(e);e.eatWhile(/[gimy]/);return i("regexp","string-2")}e.eatWhile(Tt);return i("operator","operator",e.current())}if("`"==n){t.tokenize=l;return l(e,t)}if("#"==n){e.skipToEnd();return i("error","error")}if(Tt.test(n)){e.eatWhile(Tt);return i("operator","operator",e.current())}if(It.test(n)){e.eatWhile(It);var o=e.current(),u=At.propertyIsEnumerable(o)&&At[o];return u&&"."!=t.lastType?i(u.type,u.style,o):i("variable","variable",o)}}function s(e){return function(t,n){var r,s=!1;if(xt&&"@"==t.peek()&&t.match(Lt)){n.tokenize=o;return i("jsonld-keyword","meta")}for(;null!=(r=t.next())&&(r!=e||s);)s=!s&&"\\"==r;s||(n.tokenize=o);return i("string","string")}}function a(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=o;break}r="*"==n}return i("comment","comment")}function l(e,t){for(var n,r=!1;null!=(n=e.next());){if(!r&&("`"==n||"$"==n&&e.eat("{"))){t.tokenize=o;break}r=!r&&"\\"==n}return i("quasi","string-2",e.current())}function u(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(!(0>n)){for(var r=0,i=!1,o=n-1;o>=0;--o){var s=e.string.charAt(o),a=St.indexOf(s);if(a>=0&&3>a){if(!r){++o;break}if(0==--r)break}else if(a>=3&&6>a)++r;else if(It.test(s))i=!0;else{if(/["'\/]/.test(s))return;if(i&&!r){++o;break}}}i&&!r&&(t.fatArrowAt=o)}}function p(e,t,n,r,i,o){this.indented=e;this.column=t;this.type=n;this.prev=i;this.info=o;null!=r&&(this.align=r)}function c(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==t)return!0}function d(e,t,n,r,i){var o=e.cc;Ct.state=e;Ct.stream=i;Ct.marked=null,Ct.cc=o;Ct.style=t;e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);for(;;){var s=o.length?o.pop():yt?I:N;if(s(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return Ct.marked?Ct.marked:"variable"==n&&c(e,r)?"variable-2":t}}}function h(){for(var e=arguments.length-1;e>=0;e--)Ct.cc.push(arguments[e])}function f(){h.apply(null,arguments);return!0}function g(e){function t(t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}var r=Ct.state;if(r.context){Ct.marked="def";if(t(r.localVars))return;r.localVars={name:e,next:r.localVars}}else{if(t(r.globalVars))return;n.globalVars&&(r.globalVars={name:e,next:r.globalVars})}}function m(){Ct.state.context={prev:Ct.state.context,vars:Ct.state.localVars};Ct.state.localVars=Rt}function E(){Ct.state.localVars=Ct.state.context.vars;Ct.state.context=Ct.state.context.prev}function v(e,t){var n=function(){var n=Ct.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new p(r,Ct.stream.column(),e,null,n.lexical,t)};n.lex=!0;return n}function x(){var e=Ct.state;if(e.lexical.prev){")"==e.lexical.type&&(e.indented=e.lexical.indented);e.lexical=e.lexical.prev}}function y(e){function t(n){return n==e?f():";"==e?h():f(t)}return t}function N(e,t){if("var"==e)return f(v("vardef",t.length),V,y(";"),x);if("keyword a"==e)return f(v("form"),I,N,x);if("keyword b"==e)return f(v("form"),N,x);if("{"==e)return f(v("}"),U,x);if(";"==e)return f();if("if"==e){"else"==Ct.state.lexical.info&&Ct.state.cc[Ct.state.cc.length-1]==x&&Ct.state.cc.pop()();return f(v("form"),I,N,x,K)}return"function"==e?f(et):"for"==e?f(v("form"),Y,N,x):"variable"==e?f(v("stat"),F):"switch"==e?f(v("form"),I,v("}","switch"),y("{"),U,x,x):"case"==e?f(I,y(":")):"default"==e?f(y(":")):"catch"==e?f(v("form"),m,y("("),tt,y(")"),N,x,E):"module"==e?f(v("form"),m,st,E,x):"class"==e?f(v("form"),nt,x):"export"==e?f(v("form"),at,x):"import"==e?f(v("form"),lt,x):h(v("stat"),I,y(";"),x)}function I(e){return T(e,!1)}function A(e){return T(e,!0)}function T(e,t){if(Ct.state.fatArrowAt==Ct.stream.start){var n=t?_:O;if("("==e)return f(m,v(")"),G(H,")"),x,y("=>"),n,E);if("variable"==e)return h(m,H,y("=>"),n,E)}var r=t?C:b;return bt.hasOwnProperty(e)?f(r):"function"==e?f(et,r):"keyword c"==e?f(t?S:L):"("==e?f(v(")"),L,ht,y(")"),x,r):"operator"==e||"spread"==e?f(t?A:I):"["==e?f(v("]"),ct,x,r):"{"==e?j(k,"}",null,r):"quasi"==e?h(R,r):f()}function L(e){return e.match(/[;\}\)\],]/)?h():h(I)}function S(e){return e.match(/[;\}\)\],]/)?h():h(A)}function b(e,t){return","==e?f(I):C(e,t,!1)}function C(e,t,n){var r=0==n?b:C,i=0==n?I:A;return"=>"==e?f(m,n?_:O,E):"operator"==e?/\+\+|--/.test(t)?f(r):"?"==t?f(I,y(":"),i):f(i):"quasi"==e?h(R,r):";"!=e?"("==e?j(A,")","call",r):"."==e?f(P,r):"["==e?f(v("]"),L,y("]"),x,r):void 0:void 0}function R(e,t){return"quasi"!=e?h():"${"!=t.slice(t.length-2)?f(R):f(I,w)}function w(e){if("}"==e){Ct.marked="string-2";Ct.state.tokenize=l;return f(R)}}function O(e){u(Ct.stream,Ct.state);return h("{"==e?N:I)}function _(e){u(Ct.stream,Ct.state);return h("{"==e?N:A)}function F(e){return":"==e?f(x,N):h(b,y(";"),x)}function P(e){if("variable"==e){Ct.marked="property";return f()}}function k(e,t){if("variable"==e||"keyword"==Ct.style){Ct.marked="property";return f("get"==t||"set"==t?M:D)}if("number"==e||"string"==e){Ct.marked=xt?"property":Ct.style+" property";return f(D)}return"jsonld-keyword"==e?f(D):"["==e?f(I,y("]"),D):void 0}function M(e){if("variable"!=e)return h(D);Ct.marked="property";return f(et)}function D(e){return":"==e?f(A):"("==e?h(et):void 0}function G(e,t){function n(r){if(","==r){var i=Ct.state.lexical;"call"==i.info&&(i.pos=(i.pos||0)+1);return f(e,n)}return r==t?f():f(y(t))}return function(r){return r==t?f():h(e,n)}}function j(e,t,n){for(var r=3;r<arguments.length;r++)Ct.cc.push(arguments[r]);return f(v(t,n),G(e,t),x)}function U(e){return"}"==e?f():h(N,U)}function q(e){return Nt&&":"==e?f(B):void 0}function B(e){if("variable"==e){Ct.marked="variable-3";return f()}}function V(){return h(H,q,W,$)}function H(e,t){if("variable"==e){g(t);return f()}return"["==e?j(H,"]"):"{"==e?j(z,"}"):void 0}function z(e,t){if("variable"==e&&!Ct.stream.match(/^\s*:/,!1)){g(t);return f(W)}"variable"==e&&(Ct.marked="property");return f(y(":"),H,W)}function W(e,t){return"="==t?f(A):void 0}function $(e){return","==e?f(V):void 0}function K(e,t){return"keyword b"==e&&"else"==t?f(v("form","else"),N,x):void 0}function Y(e){return"("==e?f(v(")"),Q,y(")"),x):void 0}function Q(e){return"var"==e?f(V,y(";"),Z):";"==e?f(Z):"variable"==e?f(X):h(I,y(";"),Z)}function X(e,t){if("in"==t||"of"==t){Ct.marked="keyword";return f(I)}return f(b,Z)}function Z(e,t){if(";"==e)return f(J);if("in"==t||"of"==t){Ct.marked="keyword";return f(I)}return h(I,y(";"),J)}function J(e){")"!=e&&f(I)}function et(e,t){if("*"==t){Ct.marked="keyword";return f(et)}if("variable"==e){g(t);return f(et)}return"("==e?f(m,v(")"),G(tt,")"),x,N,E):void 0}function tt(e){return"spread"==e?f(tt):h(H,q)}function nt(e,t){if("variable"==e){g(t);return f(rt)}}function rt(e,t){return"extends"==t?f(I,rt):"{"==e?f(v("}"),it,x):void 0}function it(e,t){if("variable"==e||"keyword"==Ct.style){Ct.marked="property";return"get"==t||"set"==t?f(ot,et,it):f(et,it)}if("*"==t){Ct.marked="keyword";return f(it)}return";"==e?f(it):"}"==e?f():void 0}function ot(e){if("variable"!=e)return h();Ct.marked="property";return f()}function st(e,t){if("string"==e)return f(N);if("variable"==e){g(t);return f(pt)}}function at(e,t){if("*"==t){Ct.marked="keyword";return f(pt,y(";"))}if("default"==t){Ct.marked="keyword";return f(I,y(";"))}return h(N)}function lt(e){return"string"==e?f():h(ut,pt)}function ut(e,t){if("{"==e)return j(ut,"}");"variable"==e&&g(t);return f()}function pt(e,t){if("from"==t){Ct.marked="keyword";return f(I)}}function ct(e){return"]"==e?f():h(A,dt)}function dt(e){return"for"==e?h(ht,y("]")):","==e?f(G(S,"]")):h(G(A,"]"))}function ht(e){return"for"==e?f(Y,ht):"if"==e?f(I,ht):void 0}function ft(e,t){return"operator"==e.lastType||","==e.lastType||Tt.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}var gt,mt,Et=t.indentUnit,vt=n.statementIndent,xt=n.jsonld,yt=n.json||xt,Nt=n.typescript,It=n.wordCharacters||/[\w$\xa1-\uffff]/,At=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),n=e("keyword b"),r=e("keyword c"),i=e("operator"),o={type:"atom",style:"atom"},s={"if":e("if"),"while":t,"with":t,"else":n,"do":n,"try":n,"finally":n,"return":r,"break":r,"continue":r,"new":r,"delete":r,"throw":r,"debugger":r,"var":e("var"),"const":e("var"),let:e("var"),"function":e("function"),"catch":e("catch"),"for":e("for"),"switch":e("switch"),"case":e("case"),"default":e("default"),"in":i,"typeof":i,"instanceof":i,"true":o,"false":o,"null":o,undefined:o,NaN:o,Infinity:o,"this":e("this"),module:e("module"),"class":e("class"),"super":e("atom"),"yield":r,"export":e("export"),"import":e("import"),"extends":r};if(Nt){var a={type:"variable",style:"variable-3"},l={"interface":e("interface"),"extends":e("extends"),constructor:e("constructor"),"public":e("public"),"private":e("private"),"protected":e("protected"),"static":e("static"),string:a,number:a,bool:a,any:a};for(var u in l)s[u]=l[u]}return s}(),Tt=/[+\-*&%=<>!?|~^]/,Lt=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,St="([{}])",bt={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},Ct={state:null,column:null,marked:null,cc:null},Rt={name:"this",next:{name:"arguments"}};x.lex=!0;return{startState:function(e){var t={tokenize:o,lastType:"sof",cc:[],lexical:new p((e||0)-Et,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars);return t},token:function(e,t){if(e.sol()){t.lexical.hasOwnProperty("align")||(t.lexical.align=!1);t.indented=e.indentation();u(e,t)}if(t.tokenize!=a&&e.eatSpace())return null;var n=t.tokenize(e,t);if("comment"==gt)return n;t.lastType="operator"!=gt||"++"!=mt&&"--"!=mt?gt:"incdec";return d(t,n,gt,mt,e)},indent:function(t,r){if(t.tokenize==a)return e.Pass;if(t.tokenize!=o)return 0;var i=r&&r.charAt(0),s=t.lexical;if(!/^\s*else\b/.test(r))for(var l=t.cc.length-1;l>=0;--l){var u=t.cc[l];if(u==x)s=s.prev;else if(u!=K)break}"stat"==s.type&&"}"==i&&(s=s.prev);vt&&")"==s.type&&"stat"==s.prev.type&&(s=s.prev);var p=s.type,c=i==p;return"vardef"==p?s.indented+("operator"==t.lastType||","==t.lastType?s.info+1:0):"form"==p&&"{"==i?s.indented:"form"==p?s.indented+Et:"stat"==p?s.indented+(ft(t,r)?vt||Et:0):"switch"!=s.info||c||0==n.doubleIndentSwitch?s.align?s.column+(c?0:1):s.indented+(c?0:Et):s.indented+(/^(?:case|default)\b/.test(r)?Et:2*Et)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:yt?null:"/*",blockCommentEnd:yt?null:"*/",lineComment:yt?null:"//",fold:"brace",helperType:yt?"json":"javascript",jsonldMode:xt,jsonMode:yt}});e.registerHelper("wordChars","javascript",/[\w$]/);e.defineMIME("text/javascript","javascript");e.defineMIME("text/ecmascript","javascript");e.defineMIME("application/javascript","javascript");e.defineMIME("application/x-javascript","javascript");e.defineMIME("application/ecmascript","javascript");e.defineMIME("application/json",{name:"javascript",json:!0});e.defineMIME("application/x-json",{name:"javascript",json:!0});e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});e.defineMIME("text/typescript",{name:"javascript",typescript:!0});e.defineMIME("application/typescript",{name:"javascript",typescript:!0})})},{codemirror:void 0}],57:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("xml",function(t,n){function r(e,t){function n(n){t.tokenize=n;return n(e,t)}var r=e.next();if("<"==r){if(e.eat("!")){if(e.eat("["))return e.match("CDATA[")?n(s("atom","]]>")):null;if(e.match("--"))return n(s("comment","-->"));if(e.match("DOCTYPE",!0,!0)){e.eatWhile(/[\w\._\-]/);return n(a(1))}return null}if(e.eat("?")){e.eatWhile(/[\w\._\-]/);t.tokenize=s("meta","?>");return"meta"}A=e.eat("/")?"closeTag":"openTag";t.tokenize=i;return"tag bracket"}if("&"==r){var o;o=e.eat("#")?e.eat("x")?e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):e.eatWhile(/[\d]/)&&e.eat(";"):e.eatWhile(/[\w\.\-:]/)&&e.eat(";");return o?"atom":"error"}e.eatWhile(/[^&<]/);return null}function i(e,t){var n=e.next();if(">"==n||"/"==n&&e.eat(">")){t.tokenize=r;A=">"==n?"endTag":"selfcloseTag";
return"tag bracket"}if("="==n){A="equals";return null}if("<"==n){t.tokenize=r;t.state=c;t.tagName=t.tagStart=null;var i=t.tokenize(e,t);return i?i+" tag error":"tag error"}if(/[\'\"]/.test(n)){t.tokenize=o(n);t.stringStartCol=e.column();return t.tokenize(e,t)}e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);return"word"}function o(e){var t=function(t,n){for(;!t.eol();)if(t.next()==e){n.tokenize=i;break}return"string"};t.isInAttribute=!0;return t}function s(e,t){return function(n,i){for(;!n.eol();){if(n.match(t)){i.tokenize=r;break}n.next()}return e}}function a(e){return function(t,n){for(var i;null!=(i=t.next());){if("<"==i){n.tokenize=a(e+1);return n.tokenize(t,n)}if(">"==i){if(1==e){n.tokenize=r;break}n.tokenize=a(e-1);return n.tokenize(t,n)}}return"meta"}}function l(e,t,n){this.prev=e.context;this.tagName=t;this.indent=e.indented;this.startOfLine=n;(L.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function u(e){e.context&&(e.context=e.context.prev)}function p(e,t){for(var n;;){if(!e.context)return;n=e.context.tagName;if(!L.contextGrabbers.hasOwnProperty(n)||!L.contextGrabbers[n].hasOwnProperty(t))return;u(e)}}function c(e,t,n){if("openTag"==e){n.tagStart=t.column();return d}return"closeTag"==e?h:c}function d(e,t,n){if("word"==e){n.tagName=t.current();T="tag";return m}T="error";return d}function h(e,t,n){if("word"==e){var r=t.current();n.context&&n.context.tagName!=r&&L.implicitlyClosed.hasOwnProperty(n.context.tagName)&&u(n);if(n.context&&n.context.tagName==r){T="tag";return f}T="tag error";return g}T="error";return g}function f(e,t,n){if("endTag"!=e){T="error";return f}u(n);return c}function g(e,t,n){T="error";return f(e,t,n)}function m(e,t,n){if("word"==e){T="attribute";return E}if("endTag"==e||"selfcloseTag"==e){var r=n.tagName,i=n.tagStart;n.tagName=n.tagStart=null;if("selfcloseTag"==e||L.autoSelfClosers.hasOwnProperty(r))p(n,r);else{p(n,r);n.context=new l(n,r,i==n.indented)}return c}T="error";return m}function E(e,t,n){if("equals"==e)return v;L.allowMissing||(T="error");return m(e,t,n)}function v(e,t,n){if("string"==e)return x;if("word"==e&&L.allowUnquoted){T="string";return m}T="error";return m(e,t,n)}function x(e,t,n){return"string"==e?x:m(e,t,n)}var y=t.indentUnit,N=n.multilineTagIndentFactor||1,I=n.multilineTagIndentPastTag;null==I&&(I=!0);var A,T,L=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},S=n.alignCDATA;return{startState:function(){return{tokenize:r,state:c,indented:0,tagName:null,tagStart:null,context:null}},token:function(e,t){!t.tagName&&e.sol()&&(t.indented=e.indentation());if(e.eatSpace())return null;A=null;var n=t.tokenize(e,t);if((n||A)&&"comment"!=n){T=null;t.state=t.state(A||n,e,t);T&&(n="error"==T?n+" error":T)}return n},indent:function(t,n,o){var s=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+y;if(s&&s.noIndent)return e.Pass;if(t.tokenize!=i&&t.tokenize!=r)return o?o.match(/^(\s*)/)[0].length:0;if(t.tagName)return I?t.tagStart+t.tagName.length+2:t.tagStart+y*N;if(S&&/<!\[CDATA\[/.test(n))return 0;var a=n&&/^<(\/)?([\w_:\.-]*)/.exec(n);if(a&&a[1])for(;s;){if(s.tagName==a[2]){s=s.prev;break}if(!L.implicitlyClosed.hasOwnProperty(s.tagName))break;s=s.prev}else if(a)for(;s;){var l=L.contextGrabbers[s.tagName];if(!l||!l.hasOwnProperty(a[2]))break;s=s.prev}for(;s&&!s.startOfLine;)s=s.prev;return s?s.indent+y:0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"}});e.defineMIME("text/xml","xml");e.defineMIME("application/xml","xml");e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})})},{codemirror:void 0}],58:[function(t,n){!function(){function t(e){return e&&(e.ownerDocument||e.document||e).documentElement}function r(e){return e&&(e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView)}function i(e,t){return t>e?-1:e>t?1:e>=t?0:0/0}function o(e){return null===e?0/0:+e}function s(e){return!isNaN(e)}function a(e){return{left:function(t,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=t.length);for(;i>r;){var o=r+i>>>1;e(t[o],n)<0?r=o+1:i=o}return r},right:function(t,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=t.length);for(;i>r;){var o=r+i>>>1;e(t[o],n)>0?i=o:r=o+1}return r}}}function l(e){return e.length}function u(e){for(var t=1;e*t%1;)t*=10;return t}function p(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function c(){this._=Object.create(null)}function d(e){return(e+="")===Ea||e[0]===va?va+e:e}function h(e){return(e+="")[0]===va?e.slice(1):e}function f(e){return d(e)in this._}function g(e){return(e=d(e))in this._&&delete this._[e]}function m(){var e=[];for(var t in this._)e.push(h(t));return e}function E(){var e=0;for(var t in this._)++e;return e}function v(){for(var e in this._)return!1;return!0}function x(){this._=Object.create(null)}function y(e){return e}function N(e,t,n){return function(){var r=n.apply(t,arguments);return r===t?e:r}}function I(e,t){if(t in e)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var n=0,r=xa.length;r>n;++n){var i=xa[n]+t;if(i in e)return i}}function A(){}function T(){}function L(e){function t(){for(var t,r=n,i=-1,o=r.length;++i<o;)(t=r[i].on)&&t.apply(this,arguments);return e}var n=[],r=new c;t.on=function(t,i){var o,s=r.get(t);if(arguments.length<2)return s&&s.on;if(s){s.on=null;n=n.slice(0,o=n.indexOf(s)).concat(n.slice(o+1));r.remove(t)}i&&n.push(r.set(t,{on:i}));return e};return t}function S(){ia.event.preventDefault()}function b(){for(var e,t=ia.event;e=t.sourceEvent;)t=e;return t}function C(e){for(var t=new T,n=0,r=arguments.length;++n<r;)t[arguments[n]]=L(t);t.of=function(n,r){return function(i){try{var o=i.sourceEvent=ia.event;i.target=e;ia.event=i;t[i.type].apply(n,r)}finally{ia.event=o}}};return t}function R(e){Na(e,La);return e}function w(e){return"function"==typeof e?e:function(){return Ia(e,this)}}function O(e){return"function"==typeof e?e:function(){return Aa(e,this)}}function _(e,t){function n(){this.removeAttribute(e)}function r(){this.removeAttributeNS(e.space,e.local)}function i(){this.setAttribute(e,t)}function o(){this.setAttributeNS(e.space,e.local,t)}function s(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}function a(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}e=ia.ns.qualify(e);return null==t?e.local?r:n:"function"==typeof t?e.local?a:s:e.local?o:i}function F(e){return e.trim().replace(/\s+/g," ")}function P(e){return new RegExp("(?:^|\\s+)"+ia.requote(e)+"(?:\\s+|$)","g")}function k(e){return(e+"").trim().split(/^|\s+/)}function M(e,t){function n(){for(var n=-1;++n<i;)e[n](this,t)}function r(){for(var n=-1,r=t.apply(this,arguments);++n<i;)e[n](this,r)}e=k(e).map(D);var i=e.length;return"function"==typeof t?r:n}function D(e){var t=P(e);return function(n,r){if(i=n.classList)return r?i.add(e):i.remove(e);var i=n.getAttribute("class")||"";if(r){t.lastIndex=0;t.test(i)||n.setAttribute("class",F(i+" "+e))}else n.setAttribute("class",F(i.replace(t," ")))}}function G(e,t,n){function r(){this.style.removeProperty(e)}function i(){this.style.setProperty(e,t,n)}function o(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}return null==t?r:"function"==typeof t?o:i}function j(e,t){function n(){delete this[e]}function r(){this[e]=t}function i(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}return null==t?n:"function"==typeof t?i:r}function U(e){function t(){var t=this.ownerDocument,n=this.namespaceURI;return n?t.createElementNS(n,e):t.createElement(e)}function n(){return this.ownerDocument.createElementNS(e.space,e.local)}return"function"==typeof e?e:(e=ia.ns.qualify(e)).local?n:t}function q(){var e=this.parentNode;e&&e.removeChild(this)}function B(e){return{__data__:e}}function V(e){return function(){return Ta(this,e)}}function H(e){arguments.length||(e=i);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}function z(e,t){for(var n=0,r=e.length;r>n;n++)for(var i,o=e[n],s=0,a=o.length;a>s;s++)(i=o[s])&&t(i,s,n);return e}function W(e){Na(e,ba);return e}function $(e){var t,n;return function(r,i,o){var s,a=e[o].update,l=a.length;o!=n&&(n=o,t=0);i>=t&&(t=i+1);for(;!(s=a[t])&&++t<l;);return s}}function K(e,t,n){function r(){var t=this[s];if(t){this.removeEventListener(e,t,t.$);delete this[s]}}function i(){var i=l(t,sa(arguments));r.call(this);this.addEventListener(e,this[s]=i,i.$=n);i._=t}function o(){var t,n=new RegExp("^__on([^.]+)"+ia.requote(e)+"$");for(var r in this)if(t=r.match(n)){var i=this[r];this.removeEventListener(t[1],i,i.$);delete this[r]}}var s="__on"+e,a=e.indexOf("."),l=Y;a>0&&(e=e.slice(0,a));var u=Ca.get(e);u&&(e=u,l=Q);return a?t?i:r:t?A:o}function Y(e,t){return function(n){var r=ia.event;ia.event=n;t[0]=this.__data__;try{e.apply(this,t)}finally{ia.event=r}}}function Q(e,t){var n=Y(e,t);return function(e){var t=this,r=e.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||n.call(t,e)}}function X(e){var n=".dragsuppress-"+ ++wa,i="click"+n,o=ia.select(r(e)).on("touchmove"+n,S).on("dragstart"+n,S).on("selectstart"+n,S);null==Ra&&(Ra="onselectstart"in e?!1:I(e.style,"userSelect"));if(Ra){var s=t(e).style,a=s[Ra];s[Ra]="none"}return function(e){o.on(n,null);Ra&&(s[Ra]=a);if(e){var t=function(){o.on(i,null)};o.on(i,function(){S();t()},!0);setTimeout(t,0)}}}function Z(e,t){t.changedTouches&&(t=t.changedTouches[0]);var n=e.ownerSVGElement||e;if(n.createSVGPoint){var i=n.createSVGPoint();if(0>Oa){var o=r(e);if(o.scrollX||o.scrollY){n=ia.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var s=n[0][0].getScreenCTM();Oa=!(s.f||s.e);n.remove()}}Oa?(i.x=t.pageX,i.y=t.pageY):(i.x=t.clientX,i.y=t.clientY);i=i.matrixTransform(e.getScreenCTM().inverse());return[i.x,i.y]}var a=e.getBoundingClientRect();return[t.clientX-a.left-e.clientLeft,t.clientY-a.top-e.clientTop]}function J(){return ia.event.changedTouches[0].identifier}function et(e){return e>0?1:0>e?-1:0}function tt(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function nt(e){return e>1?0:-1>e?Pa:Math.acos(e)}function rt(e){return e>1?Da:-1>e?-Da:Math.asin(e)}function it(e){return((e=Math.exp(e))-1/e)/2}function ot(e){return((e=Math.exp(e))+1/e)/2}function st(e){return((e=Math.exp(2*e))-1)/(e+1)}function at(e){return(e=Math.sin(e/2))*e}function lt(){}function ut(e,t,n){return this instanceof ut?void(this.h=+e,this.s=+t,this.l=+n):arguments.length<2?e instanceof ut?new ut(e.h,e.s,e.l):At(""+e,Tt,ut):new ut(e,t,n)}function pt(e,t,n){function r(e){e>360?e-=360:0>e&&(e+=360);return 60>e?o+(s-o)*e/60:180>e?s:240>e?o+(s-o)*(240-e)/60:o}function i(e){return Math.round(255*r(e))}var o,s;e=isNaN(e)?0:(e%=360)<0?e+360:e;t=isNaN(t)?0:0>t?0:t>1?1:t;n=0>n?0:n>1?1:n;s=.5>=n?n*(1+t):n+t-n*t;o=2*n-s;return new xt(i(e+120),i(e),i(e-120))}function ct(e,t,n){return this instanceof ct?void(this.h=+e,this.c=+t,this.l=+n):arguments.length<2?e instanceof ct?new ct(e.h,e.c,e.l):e instanceof ht?gt(e.l,e.a,e.b):gt((e=Lt((e=ia.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new ct(e,t,n)}function dt(e,t,n){isNaN(e)&&(e=0);isNaN(t)&&(t=0);return new ht(n,Math.cos(e*=Ga)*t,Math.sin(e)*t)}function ht(e,t,n){return this instanceof ht?void(this.l=+e,this.a=+t,this.b=+n):arguments.length<2?e instanceof ht?new ht(e.l,e.a,e.b):e instanceof ct?dt(e.h,e.c,e.l):Lt((e=xt(e)).r,e.g,e.b):new ht(e,t,n)}function ft(e,t,n){var r=(e+16)/116,i=r+t/500,o=r-n/200;i=mt(i)*Ya;r=mt(r)*Qa;o=mt(o)*Xa;return new xt(vt(3.2404542*i-1.5371385*r-.4985314*o),vt(-.969266*i+1.8760108*r+.041556*o),vt(.0556434*i-.2040259*r+1.0572252*o))}function gt(e,t,n){return e>0?new ct(Math.atan2(n,t)*ja,Math.sqrt(t*t+n*n),e):new ct(0/0,0/0,e)}function mt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function Et(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function vt(e){return Math.round(255*(.00304>=e?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function xt(e,t,n){return this instanceof xt?void(this.r=~~e,this.g=~~t,this.b=~~n):arguments.length<2?e instanceof xt?new xt(e.r,e.g,e.b):At(""+e,xt,pt):new xt(e,t,n)}function yt(e){return new xt(e>>16,e>>8&255,255&e)}function Nt(e){return yt(e)+""}function It(e){return 16>e?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function At(e,t,n){var r,i,o,s=0,a=0,l=0;r=/([a-z]+)\((.*)\)/i.exec(e);if(r){i=r[2].split(",");switch(r[1]){case"hsl":return n(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return t(bt(i[0]),bt(i[1]),bt(i[2]))}}if(o=el.get(e.toLowerCase()))return t(o.r,o.g,o.b);if(null!=e&&"#"===e.charAt(0)&&!isNaN(o=parseInt(e.slice(1),16)))if(4===e.length){s=(3840&o)>>4;s=s>>4|s;a=240&o;a=a>>4|a;l=15&o;l=l<<4|l}else if(7===e.length){s=(16711680&o)>>16;a=(65280&o)>>8;l=255&o}return t(s,a,l)}function Tt(e,t,n){var r,i,o=Math.min(e/=255,t/=255,n/=255),s=Math.max(e,t,n),a=s-o,l=(s+o)/2;if(a){i=.5>l?a/(s+o):a/(2-s-o);r=e==s?(t-n)/a+(n>t?6:0):t==s?(n-e)/a+2:(e-t)/a+4;r*=60}else{r=0/0;i=l>0&&1>l?0:r}return new ut(r,i,l)}function Lt(e,t,n){e=St(e);t=St(t);n=St(n);var r=Et((.4124564*e+.3575761*t+.1804375*n)/Ya),i=Et((.2126729*e+.7151522*t+.072175*n)/Qa),o=Et((.0193339*e+.119192*t+.9503041*n)/Xa);return ht(116*i-16,500*(r-i),200*(i-o))}function St(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function bt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}function Ct(e){return"function"==typeof e?e:function(){return e}}function Rt(e){return function(t,n,r){2===arguments.length&&"function"==typeof n&&(r=n,n=null);return wt(t,n,e,r)}}function wt(e,t,n,r){function i(){var e,t=l.status;if(!t&&_t(l)||t>=200&&300>t||304===t){try{e=n.call(o,l)}catch(r){s.error.call(o,r);return}s.load.call(o,e)}else s.error.call(o,l)}var o={},s=ia.dispatch("beforesend","progress","load","error"),a={},l=new XMLHttpRequest,u=null;!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(e)||(l=new XDomainRequest);"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()};l.onprogress=function(e){var t=ia.event;ia.event=e;try{s.progress.call(o,l)}finally{ia.event=t}};o.header=function(e,t){e=(e+"").toLowerCase();if(arguments.length<2)return a[e];null==t?delete a[e]:a[e]=t+"";return o};o.mimeType=function(e){if(!arguments.length)return t;t=null==e?null:e+"";return o};o.responseType=function(e){if(!arguments.length)return u;u=e;return o};o.response=function(e){n=e;return o};["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(sa(arguments)))}});o.send=function(n,r,i){2===arguments.length&&"function"==typeof r&&(i=r,r=null);l.open(n,e,!0);null==t||"accept"in a||(a.accept=t+",*/*");if(l.setRequestHeader)for(var p in a)l.setRequestHeader(p,a[p]);null!=t&&l.overrideMimeType&&l.overrideMimeType(t);null!=u&&(l.responseType=u);null!=i&&o.on("error",i).on("load",function(e){i(null,e)});s.beforesend.call(o,l);l.send(null==r?null:r);return o};o.abort=function(){l.abort();return o};ia.rebind(o,s,"on");return null==r?o:o.get(Ot(r))}function Ot(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}function _t(e){var t=e.responseType;return t&&"text"!==t?e.response:e.responseText}function Ft(){var e=Pt(),t=kt()-e;if(t>24){if(isFinite(t)){clearTimeout(il);il=setTimeout(Ft,t)}rl=0}else{rl=1;sl(Ft)}}function Pt(){var e=Date.now();ol=tl;for(;ol;){e>=ol.t&&(ol.f=ol.c(e-ol.t));ol=ol.n}return e}function kt(){for(var e,t=tl,n=1/0;t;)if(t.f)t=e?e.n=t.n:tl=t.n;else{t.t<n&&(n=t.t);t=(e=t).n}nl=e;return n}function Mt(e,t){return t-(e?Math.ceil(Math.log(e)/Math.LN10):1)}function Dt(e,t){var n=Math.pow(10,3*ma(8-t));return{scale:t>8?function(e){return e/n}:function(e){return e*n},symbol:e}}function Gt(e){var t=e.decimal,n=e.thousands,r=e.grouping,i=e.currency,o=r&&n?function(e,t){for(var i=e.length,o=[],s=0,a=r[0],l=0;i>0&&a>0;){l+a+1>t&&(a=Math.max(1,t-l));o.push(e.substring(i-=a,i+a));if((l+=a+1)>t)break;a=r[s=(s+1)%r.length]}return o.reverse().join(n)}:y;return function(e){var n=ll.exec(e),r=n[1]||" ",s=n[2]||">",a=n[3]||"-",l=n[4]||"",u=n[5],p=+n[6],c=n[7],d=n[8],h=n[9],f=1,g="",m="",E=!1,v=!0;d&&(d=+d.substring(1));if(u||"0"===r&&"="===s){u=r="0";s="="}switch(h){case"n":c=!0;h="g";break;case"%":f=100;m="%";h="f";break;case"p":f=100;m="%";h="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+h.toLowerCase());case"c":v=!1;case"d":E=!0;d=0;break;case"s":f=-1;h="r"}"$"===l&&(g=i[0],m=i[1]);"r"!=h||d||(h="g");null!=d&&("g"==h?d=Math.max(1,Math.min(21,d)):("e"==h||"f"==h)&&(d=Math.max(0,Math.min(20,d))));h=ul.get(h)||jt;var x=u&&c;return function(e){var n=m;if(E&&e%1)return"";var i=0>e||0===e&&0>1/e?(e=-e,"-"):"-"===a?"":a;if(0>f){var l=ia.formatPrefix(e,d);e=l.scale(e);n=l.symbol+m}else e*=f;e=h(e,d);var y,N,I=e.lastIndexOf(".");if(0>I){var A=v?e.lastIndexOf("e"):-1;0>A?(y=e,N=""):(y=e.substring(0,A),N=e.substring(A))}else{y=e.substring(0,I);N=t+e.substring(I+1)}!u&&c&&(y=o(y,1/0));var T=g.length+y.length+N.length+(x?0:i.length),L=p>T?new Array(T=p-T+1).join(r):"";x&&(y=o(L+y,L.length?p-N.length:1/0));i+=g;e=y+N;return("<"===s?i+e+L:">"===s?L+i+e:"^"===s?L.substring(0,T>>=1)+i+e+L.substring(T):i+(x?e:L+e))+n}}}function jt(e){return e+""}function Ut(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function qt(e,t,n){function r(t){var n=e(t),r=o(n,1);return r-t>t-n?n:r}function i(n){t(n=e(new cl(n-1)),1);return n}function o(e,n){t(e=new cl(+e),n);return e}function s(e,r,o){var s=i(e),a=[];if(o>1)for(;r>s;){n(s)%o||a.push(new Date(+s));t(s,1)}else for(;r>s;)a.push(new Date(+s)),t(s,1);return a}function a(e,t,n){try{cl=Ut;var r=new Ut;r._=e;return s(r,t,n)}finally{cl=Date}}e.floor=e;e.round=r;e.ceil=i;e.offset=o;e.range=s;var l=e.utc=Bt(e);l.floor=l;l.round=Bt(r);l.ceil=Bt(i);l.offset=Bt(o);l.range=a;return e}function Bt(e){return function(t,n){try{cl=Ut;var r=new Ut;r._=t;return e(r,n)._}finally{cl=Date}}}function Vt(e){function t(e){function t(t){for(var n,i,o,s=[],a=-1,l=0;++a<r;)if(37===e.charCodeAt(a)){s.push(e.slice(l,a));null!=(i=hl[n=e.charAt(++a)])&&(n=e.charAt(++a));(o=C[n])&&(n=o(t,null==i?"e"===n?" ":"0":i));s.push(n);l=a+1}s.push(e.slice(l,a));return s.join("")}var r=e.length;t.parse=function(t){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},i=n(r,e,t,0);if(i!=t.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var o=null!=r.Z&&cl!==Ut,s=new(o?Ut:cl);if("j"in r)s.setFullYear(r.y,0,r.j);else if("w"in r&&("W"in r||"U"in r)){s.setFullYear(r.y,0,1);s.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(s.getDay()+5)%7:r.w+7*r.U-(s.getDay()+6)%7)}else s.setFullYear(r.y,r.m,r.d);s.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L);return o?s._:s};t.toString=function(){return e};return t}function n(e,t,n,r){for(var i,o,s,a=0,l=t.length,u=n.length;l>a;){if(r>=u)return-1;i=t.charCodeAt(a++);if(37===i){s=t.charAt(a++);o=R[s in hl?t.charAt(a++):s];if(!o||(r=o(e,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}function r(e,t,n){I.lastIndex=0;var r=I.exec(t.slice(n));return r?(e.w=A.get(r[0].toLowerCase()),n+r[0].length):-1}function i(e,t,n){y.lastIndex=0;var r=y.exec(t.slice(n));return r?(e.w=N.get(r[0].toLowerCase()),n+r[0].length):-1}function o(e,t,n){S.lastIndex=0;var r=S.exec(t.slice(n));return r?(e.m=b.get(r[0].toLowerCase()),n+r[0].length):-1}function s(e,t,n){T.lastIndex=0;var r=T.exec(t.slice(n));return r?(e.m=L.get(r[0].toLowerCase()),n+r[0].length):-1}function a(e,t,r){return n(e,C.c.toString(),t,r)}function l(e,t,r){return n(e,C.x.toString(),t,r)}function u(e,t,r){return n(e,C.X.toString(),t,r)}function p(e,t,n){var r=x.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)}var c=e.dateTime,d=e.date,h=e.time,f=e.periods,g=e.days,m=e.shortDays,E=e.months,v=e.shortMonths;t.utc=function(e){function n(e){try{cl=Ut;var t=new cl;t._=e;return r(t)}finally{cl=Date}}var r=t(e);n.parse=function(e){try{cl=Ut;var t=r.parse(e);return t&&t._}finally{cl=Date}};n.toString=r.toString;return n};t.multi=t.utc.multi=pn;var x=ia.map(),y=zt(g),N=Wt(g),I=zt(m),A=Wt(m),T=zt(E),L=Wt(E),S=zt(v),b=Wt(v);f.forEach(function(e,t){x.set(e.toLowerCase(),t)});var C={a:function(e){return m[e.getDay()]},A:function(e){return g[e.getDay()]},b:function(e){return v[e.getMonth()]},B:function(e){return E[e.getMonth()]},c:t(c),d:function(e,t){return Ht(e.getDate(),t,2)},e:function(e,t){return Ht(e.getDate(),t,2)},H:function(e,t){return Ht(e.getHours(),t,2)},I:function(e,t){return Ht(e.getHours()%12||12,t,2)},j:function(e,t){return Ht(1+pl.dayOfYear(e),t,3)},L:function(e,t){return Ht(e.getMilliseconds(),t,3)},m:function(e,t){return Ht(e.getMonth()+1,t,2)},M:function(e,t){return Ht(e.getMinutes(),t,2)},p:function(e){return f[+(e.getHours()>=12)]},S:function(e,t){return Ht(e.getSeconds(),t,2)},U:function(e,t){return Ht(pl.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return Ht(pl.mondayOfYear(e),t,2)},x:t(d),X:t(h),y:function(e,t){return Ht(e.getFullYear()%100,t,2)},Y:function(e,t){return Ht(e.getFullYear()%1e4,t,4)},Z:ln,"%":function(){return"%"}},R={a:r,A:i,b:o,B:s,c:a,d:tn,e:tn,H:rn,I:rn,j:nn,L:an,m:en,M:on,p:p,S:sn,U:Kt,w:$t,W:Yt,x:l,X:u,y:Xt,Y:Qt,Z:Zt,"%":un};return t}function Ht(e,t,n){var r=0>e?"-":"",i=(r?-e:e)+"",o=i.length;return r+(n>o?new Array(n-o+1).join(t)+i:i)}function zt(e){return new RegExp("^(?:"+e.map(ia.requote).join("|")+")","i")}function Wt(e){for(var t=new c,n=-1,r=e.length;++n<r;)t.set(e[n].toLowerCase(),n);return t}function $t(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function Kt(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n));return r?(e.U=+r[0],n+r[0].length):-1}function Yt(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n));return r?(e.W=+r[0],n+r[0].length):-1}function Qt(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function Xt(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+2));return r?(e.y=Jt(+r[0]),n+r[0].length):-1}function Zt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Jt(e){return e+(e>68?1900:2e3)}function en(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function tn(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function nn(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function rn(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function on(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function sn(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function an(e,t,n){fl.lastIndex=0;var r=fl.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function ln(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=ma(t)/60|0,i=ma(t)%60;return n+Ht(r,"0",2)+Ht(i,"0",2)}function un(e,t,n){gl.lastIndex=0;var r=gl.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function pn(e){for(var t=e.length,n=-1;++n<t;)e[n][0]=this(e[n][0]);return function(t){for(var n=0,r=e[n];!r[1](t);)r=e[++n];return r[0](t)}}function cn(){}function dn(e,t,n){var r=n.s=e+t,i=r-e,o=r-i;n.t=e-o+(t-i)}function hn(e,t){e&&xl.hasOwnProperty(e.type)&&xl[e.type](e,t)}function fn(e,t,n){var r,i=-1,o=e.length-n;t.lineStart();for(;++i<o;)r=e[i],t.point(r[0],r[1],r[2]);t.lineEnd()}function gn(e,t){var n=-1,r=e.length;t.polygonStart();for(;++n<r;)fn(e[n],t,1);t.polygonEnd()}function mn(){function e(e,t){e*=Ga;t=t*Ga/2+Pa/4;var n=e-r,s=n>=0?1:-1,a=s*n,l=Math.cos(t),u=Math.sin(t),p=o*u,c=i*l+p*Math.cos(a),d=p*s*Math.sin(a);Nl.add(Math.atan2(d,c));r=e,i=l,o=u}var t,n,r,i,o;Il.point=function(s,a){Il.point=e;r=(t=s)*Ga,i=Math.cos(a=(n=a)*Ga/2+Pa/4),o=Math.sin(a)};Il.lineEnd=function(){e(t,n)}}function En(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function vn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function xn(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function yn(e,t){e[0]+=t[0];e[1]+=t[1];e[2]+=t[2]}function Nn(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function In(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t;e[1]/=t;e[2]/=t}function An(e){return[Math.atan2(e[1],e[0]),rt(e[2])]}function Tn(e,t){return ma(e[0]-t[0])<_a&&ma(e[1]-t[1])<_a}function Ln(e,t){e*=Ga;var n=Math.cos(t*=Ga);Sn(n*Math.cos(e),n*Math.sin(e),Math.sin(t))}function Sn(e,t,n){++Al;Ll+=(e-Ll)/Al;Sl+=(t-Sl)/Al;bl+=(n-bl)/Al}function bn(){function e(e,i){e*=Ga;var o=Math.cos(i*=Ga),s=o*Math.cos(e),a=o*Math.sin(e),l=Math.sin(i),u=Math.atan2(Math.sqrt((u=n*l-r*a)*u+(u=r*s-t*l)*u+(u=t*a-n*s)*u),t*s+n*a+r*l);Tl+=u;Cl+=u*(t+(t=s));Rl+=u*(n+(n=a));wl+=u*(r+(r=l));Sn(t,n,r)}var t,n,r;Pl.point=function(i,o){i*=Ga;var s=Math.cos(o*=Ga);t=s*Math.cos(i);n=s*Math.sin(i);r=Math.sin(o);Pl.point=e;Sn(t,n,r)}}function Cn(){Pl.point=Ln}function Rn(){function e(e,t){e*=Ga;var n=Math.cos(t*=Ga),s=n*Math.cos(e),a=n*Math.sin(e),l=Math.sin(t),u=i*l-o*a,p=o*s-r*l,c=r*a-i*s,d=Math.sqrt(u*u+p*p+c*c),h=r*s+i*a+o*l,f=d&&-nt(h)/d,g=Math.atan2(d,h);Ol+=f*u;_l+=f*p;Fl+=f*c;Tl+=g;Cl+=g*(r+(r=s));Rl+=g*(i+(i=a));wl+=g*(o+(o=l));Sn(r,i,o)}var t,n,r,i,o;Pl.point=function(s,a){t=s,n=a;Pl.point=e;s*=Ga;var l=Math.cos(a*=Ga);r=l*Math.cos(s);i=l*Math.sin(s);o=Math.sin(a);Sn(r,i,o)};Pl.lineEnd=function(){e(t,n);Pl.lineEnd=Cn;Pl.point=Ln}}function wn(e,t){function n(n,r){return n=e(n,r),t(n[0],n[1])}e.invert&&t.invert&&(n.invert=function(n,r){return n=t.invert(n,r),n&&e.invert(n[0],n[1])});return n}function On(){return!0}function _n(e,t,n,r,i){var o=[],s=[];e.forEach(function(e){if(!((t=e.length-1)<=0)){var t,n=e[0],r=e[t];if(Tn(n,r)){i.lineStart();for(var a=0;t>a;++a)i.point((n=e[a])[0],n[1]);i.lineEnd()}else{var l=new Pn(n,e,null,!0),u=new Pn(n,null,l,!1);l.o=u;o.push(l);s.push(u);l=new Pn(r,e,null,!1);u=new Pn(r,null,l,!0);l.o=u;o.push(l);s.push(u)}}});s.sort(t);Fn(o);Fn(s);if(o.length){for(var a=0,l=n,u=s.length;u>a;++a)s[a].e=l=!l;for(var p,c,d=o[0];;){for(var h=d,f=!0;h.v;)if((h=h.n)===d)return;p=h.z;i.lineStart();do{h.v=h.o.v=!0;if(h.e){if(f)for(var a=0,u=p.length;u>a;++a)i.point((c=p[a])[0],c[1]);else r(h.x,h.n.x,1,i);h=h.n}else{if(f){p=h.p.z;for(var a=p.length-1;a>=0;--a)i.point((c=p[a])[0],c[1])}else r(h.x,h.p.x,-1,i);h=h.p}h=h.o;p=h.z;f=!f}while(!h.v);i.lineEnd()}}}function Fn(e){if(t=e.length){for(var t,n,r=0,i=e[0];++r<t;){i.n=n=e[r];n.p=i;i=n}i.n=n=e[0];n.p=i}}function Pn(e,t,n,r){this.x=e;this.z=t;this.o=n;this.e=r;this.v=!1;this.n=this.p=null}function kn(e,t,n,r){return function(i,o){function s(t,n){var r=i(t,n);e(t=r[0],n=r[1])&&o.point(t,n)}function a(e,t){var n=i(e,t);m.point(n[0],n[1])}function l(){v.point=a;m.lineStart()}function u(){v.point=s;m.lineEnd()}function p(e,t){g.push([e,t]);var n=i(e,t);y.point(n[0],n[1])}function c(){y.lineStart();g=[]}function d(){p(g[0][0],g[0][1]);y.lineEnd();var e,t=y.clean(),n=x.buffer(),r=n.length;g.pop();f.push(g);g=null;if(r)if(1&t){e=n[0];var i,r=e.length-1,s=-1;if(r>0){N||(o.polygonStart(),N=!0);o.lineStart();for(;++s<r;)o.point((i=e[s])[0],i[1]);o.lineEnd()}}else{r>1&&2&t&&n.push(n.pop().concat(n.shift()));h.push(n.filter(Mn))}}var h,f,g,m=t(o),E=i.invert(r[0],r[1]),v={point:s,lineStart:l,lineEnd:u,polygonStart:function(){v.point=p;v.lineStart=c;v.lineEnd=d;h=[];f=[]},polygonEnd:function(){v.point=s;v.lineStart=l;v.lineEnd=u;h=ia.merge(h);var e=Bn(E,f);if(h.length){N||(o.polygonStart(),N=!0);_n(h,Gn,e,n,o)}else if(e){N||(o.polygonStart(),N=!0);o.lineStart();n(null,null,1,o);o.lineEnd()}N&&(o.polygonEnd(),N=!1);h=f=null},sphere:function(){o.polygonStart();o.lineStart();n(null,null,1,o);o.lineEnd();o.polygonEnd()}},x=Dn(),y=t(x),N=!1;return v}}function Mn(e){return e.length>1}function Dn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:A,buffer:function(){var n=t;t=[];e=null;return n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Gn(e,t){return((e=e.x)[0]<0?e[1]-Da-_a:Da-e[1])-((t=t.x)[0]<0?t[1]-Da-_a:Da-t[1])}function jn(e){var t,n=0/0,r=0/0,i=0/0;return{lineStart:function(){e.lineStart();t=1},point:function(o,s){var a=o>0?Pa:-Pa,l=ma(o-n);if(ma(l-Pa)<_a){e.point(n,r=(r+s)/2>0?Da:-Da);e.point(i,r);e.lineEnd();e.lineStart();e.point(a,r);e.point(o,r);t=0}else if(i!==a&&l>=Pa){ma(n-i)<_a&&(n-=i*_a);ma(o-a)<_a&&(o-=a*_a);r=Un(n,r,o,s);e.point(i,r);e.lineEnd();e.lineStart();e.point(a,r);t=0}e.point(n=o,r=s);i=a},lineEnd:function(){e.lineEnd();n=r=0/0},clean:function(){return 2-t}}}function Un(e,t,n,r){var i,o,s=Math.sin(e-n);return ma(s)>_a?Math.atan((Math.sin(t)*(o=Math.cos(r))*Math.sin(n)-Math.sin(r)*(i=Math.cos(t))*Math.sin(e))/(i*o*s)):(t+r)/2}function qn(e,t,n,r){var i;if(null==e){i=n*Da;r.point(-Pa,i);r.point(0,i);r.point(Pa,i);r.point(Pa,0);r.point(Pa,-i);r.point(0,-i);r.point(-Pa,-i);r.point(-Pa,0);r.point(-Pa,i)}else if(ma(e[0]-t[0])>_a){var o=e[0]<t[0]?Pa:-Pa;i=n*o/2;r.point(-o,i);r.point(0,i);r.point(o,i)}else r.point(t[0],t[1])}function Bn(e,t){var n=e[0],r=e[1],i=[Math.sin(n),-Math.cos(n),0],o=0,s=0;Nl.reset();for(var a=0,l=t.length;l>a;++a){var u=t[a],p=u.length;if(p)for(var c=u[0],d=c[0],h=c[1]/2+Pa/4,f=Math.sin(h),g=Math.cos(h),m=1;;){m===p&&(m=0);e=u[m];var E=e[0],v=e[1]/2+Pa/4,x=Math.sin(v),y=Math.cos(v),N=E-d,I=N>=0?1:-1,A=I*N,T=A>Pa,L=f*x;Nl.add(Math.atan2(L*I*Math.sin(A),g*y+L*Math.cos(A)));o+=T?N+I*ka:N;if(T^d>=n^E>=n){var S=xn(En(c),En(e));In(S);var b=xn(i,S);In(b);var C=(T^N>=0?-1:1)*rt(b[2]);(r>C||r===C&&(S[0]||S[1]))&&(s+=T^N>=0?1:-1)}if(!m++)break;d=E,f=x,g=y,c=e}}return(-_a>o||_a>o&&0>Nl)^1&s}function Vn(e){function t(e,t){return Math.cos(e)*Math.cos(t)>o}function n(e){var n,o,l,u,p;return{lineStart:function(){u=l=!1;p=1},point:function(c,d){var h,f=[c,d],g=t(c,d),m=s?g?0:i(c,d):g?i(c+(0>c?Pa:-Pa),d):0;!n&&(u=l=g)&&e.lineStart();if(g!==l){h=r(n,f);if(Tn(n,h)||Tn(f,h)){f[0]+=_a;f[1]+=_a;g=t(f[0],f[1])}}if(g!==l){p=0;if(g){e.lineStart();h=r(f,n);e.point(h[0],h[1])}else{h=r(n,f);e.point(h[0],h[1]);e.lineEnd()}n=h}else if(a&&n&&s^g){var E;if(!(m&o)&&(E=r(f,n,!0))){p=0;if(s){e.lineStart();e.point(E[0][0],E[0][1]);e.point(E[1][0],E[1][1]);e.lineEnd()}else{e.point(E[1][0],E[1][1]);e.lineEnd();e.lineStart();e.point(E[0][0],E[0][1])}}}!g||n&&Tn(n,f)||e.point(f[0],f[1]);n=f,l=g,o=m},lineEnd:function(){l&&e.lineEnd();n=null},clean:function(){return p|(u&&l)<<1}}}function r(e,t,n){var r=En(e),i=En(t),s=[1,0,0],a=xn(r,i),l=vn(a,a),u=a[0],p=l-u*u;if(!p)return!n&&e;var c=o*l/p,d=-o*u/p,h=xn(s,a),f=Nn(s,c),g=Nn(a,d);yn(f,g);var m=h,E=vn(f,m),v=vn(m,m),x=E*E-v*(vn(f,f)-1);if(!(0>x)){var y=Math.sqrt(x),N=Nn(m,(-E-y)/v);yn(N,f);N=An(N);if(!n)return N;var I,A=e[0],T=t[0],L=e[1],S=t[1];A>T&&(I=A,A=T,T=I);var b=T-A,C=ma(b-Pa)<_a,R=C||_a>b;!C&&L>S&&(I=L,L=S,S=I);if(R?C?L+S>0^N[1]<(ma(N[0]-A)<_a?L:S):L<=N[1]&&N[1]<=S:b>Pa^(A<=N[0]&&N[0]<=T)){var w=Nn(m,(-E+y)/v);yn(w,f);return[N,An(w)]}}}function i(t,n){var r=s?e:Pa-e,i=0;-r>t?i|=1:t>r&&(i|=2);-r>n?i|=4:n>r&&(i|=8);return i}var o=Math.cos(e),s=o>0,a=ma(o)>_a,l=mr(e,6*Ga);return kn(t,n,l,s?[0,-e]:[-Pa,e-Pa])
}function Hn(e,t,n,r){return function(i){var o,s=i.a,a=i.b,l=s.x,u=s.y,p=a.x,c=a.y,d=0,h=1,f=p-l,g=c-u;o=e-l;if(f||!(o>0)){o/=f;if(0>f){if(d>o)return;h>o&&(h=o)}else if(f>0){if(o>h)return;o>d&&(d=o)}o=n-l;if(f||!(0>o)){o/=f;if(0>f){if(o>h)return;o>d&&(d=o)}else if(f>0){if(d>o)return;h>o&&(h=o)}o=t-u;if(g||!(o>0)){o/=g;if(0>g){if(d>o)return;h>o&&(h=o)}else if(g>0){if(o>h)return;o>d&&(d=o)}o=r-u;if(g||!(0>o)){o/=g;if(0>g){if(o>h)return;o>d&&(d=o)}else if(g>0){if(d>o)return;h>o&&(h=o)}d>0&&(i.a={x:l+d*f,y:u+d*g});1>h&&(i.b={x:l+h*f,y:u+h*g});return i}}}}}}function zn(e,t,n,r){function i(r,i){return ma(r[0]-e)<_a?i>0?0:3:ma(r[0]-n)<_a?i>0?2:1:ma(r[1]-t)<_a?i>0?1:0:i>0?3:2}function o(e,t){return s(e.x,t.x)}function s(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}return function(a){function l(e){for(var t=0,n=m.length,r=e[1],i=0;n>i;++i)for(var o,s=1,a=m[i],l=a.length,u=a[0];l>s;++s){o=a[s];u[1]<=r?o[1]>r&&tt(u,o,e)>0&&++t:o[1]<=r&&tt(u,o,e)<0&&--t;u=o}return 0!==t}function u(o,a,l,u){var p=0,c=0;if(null==o||(p=i(o,l))!==(c=i(a,l))||s(o,a)<0^l>0){do u.point(0===p||3===p?e:n,p>1?r:t);while((p=(p+l+4)%4)!==c)}else u.point(a[0],a[1])}function p(i,o){return i>=e&&n>=i&&o>=t&&r>=o}function c(e,t){p(e,t)&&a.point(e,t)}function d(){R.point=f;m&&m.push(E=[]);T=!0;A=!1;N=I=0/0}function h(){if(g){f(v,x);y&&A&&b.rejoin();g.push(b.buffer())}R.point=c;A&&a.lineEnd()}function f(e,t){e=Math.max(-Ml,Math.min(Ml,e));t=Math.max(-Ml,Math.min(Ml,t));var n=p(e,t);m&&E.push([e,t]);if(T){v=e,x=t,y=n;T=!1;if(n){a.lineStart();a.point(e,t)}}else if(n&&A)a.point(e,t);else{var r={a:{x:N,y:I},b:{x:e,y:t}};if(C(r)){if(!A){a.lineStart();a.point(r.a.x,r.a.y)}a.point(r.b.x,r.b.y);n||a.lineEnd();L=!1}else if(n){a.lineStart();a.point(e,t);L=!1}}N=e,I=t,A=n}var g,m,E,v,x,y,N,I,A,T,L,S=a,b=Dn(),C=Hn(e,t,n,r),R={point:c,lineStart:d,lineEnd:h,polygonStart:function(){a=b;g=[];m=[];L=!0},polygonEnd:function(){a=S;g=ia.merge(g);var t=l([e,r]),n=L&&t,i=g.length;if(n||i){a.polygonStart();if(n){a.lineStart();u(null,null,1,a);a.lineEnd()}i&&_n(g,o,t,u,a);a.polygonEnd()}g=m=E=null}};return R}}function Wn(e){var t=0,n=Pa/3,r=lr(e),i=r(t,n);i.parallels=function(e){return arguments.length?r(t=e[0]*Pa/180,n=e[1]*Pa/180):[t/Pa*180,n/Pa*180]};return i}function $n(e,t){function n(e,t){var n=Math.sqrt(o-2*i*Math.sin(t))/i;return[n*Math.sin(e*=i),s-n*Math.cos(e)]}var r=Math.sin(e),i=(r+Math.sin(t))/2,o=1+r*(2*i-r),s=Math.sqrt(o)/i;n.invert=function(e,t){var n=s-t;return[Math.atan2(e,n)/i,rt((o-(e*e+n*n)*i*i)/(2*i))]};return n}function Kn(){function e(e,t){Gl+=i*e-r*t;r=e,i=t}var t,n,r,i;Vl.point=function(o,s){Vl.point=e;t=r=o,n=i=s};Vl.lineEnd=function(){e(t,n)}}function Yn(e,t){jl>e&&(jl=e);e>ql&&(ql=e);Ul>t&&(Ul=t);t>Bl&&(Bl=t)}function Qn(){function e(e,t){s.push("M",e,",",t,o)}function t(e,t){s.push("M",e,",",t);a.point=n}function n(e,t){s.push("L",e,",",t)}function r(){a.point=e}function i(){s.push("Z")}var o=Xn(4.5),s=[],a={point:e,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=r;a.point=e},pointRadius:function(e){o=Xn(e);return a},result:function(){if(s.length){var e=s.join("");s=[];return e}}};return a}function Xn(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}function Zn(e,t){Ll+=e;Sl+=t;++bl}function Jn(){function e(e,r){var i=e-t,o=r-n,s=Math.sqrt(i*i+o*o);Cl+=s*(t+e)/2;Rl+=s*(n+r)/2;wl+=s;Zn(t=e,n=r)}var t,n;zl.point=function(r,i){zl.point=e;Zn(t=r,n=i)}}function er(){zl.point=Zn}function tr(){function e(e,t){var n=e-r,o=t-i,s=Math.sqrt(n*n+o*o);Cl+=s*(r+e)/2;Rl+=s*(i+t)/2;wl+=s;s=i*e-r*t;Ol+=s*(r+e);_l+=s*(i+t);Fl+=3*s;Zn(r=e,i=t)}var t,n,r,i;zl.point=function(o,s){zl.point=e;Zn(t=r=o,n=i=s)};zl.lineEnd=function(){e(t,n)}}function nr(e){function t(t,n){e.moveTo(t+s,n);e.arc(t,n,s,0,ka)}function n(t,n){e.moveTo(t,n);a.point=r}function r(t,n){e.lineTo(t,n)}function i(){a.point=t}function o(){e.closePath()}var s=4.5,a={point:t,lineStart:function(){a.point=n},lineEnd:i,polygonStart:function(){a.lineEnd=o},polygonEnd:function(){a.lineEnd=i;a.point=t},pointRadius:function(e){s=e;return a},result:A};return a}function rr(e){function t(e){return(a?r:n)(e)}function n(t){return sr(t,function(n,r){n=e(n,r);t.point(n[0],n[1])})}function r(t){function n(n,r){n=e(n,r);t.point(n[0],n[1])}function r(){x=0/0;T.point=o;t.lineStart()}function o(n,r){var o=En([n,r]),s=e(n,r);i(x,y,v,N,I,A,x=s[0],y=s[1],v=n,N=o[0],I=o[1],A=o[2],a,t);t.point(x,y)}function s(){T.point=n;t.lineEnd()}function l(){r();T.point=u;T.lineEnd=p}function u(e,t){o(c=e,d=t),h=x,f=y,g=N,m=I,E=A;T.point=o}function p(){i(x,y,v,N,I,A,h,f,c,g,m,E,a,t);T.lineEnd=s;s()}var c,d,h,f,g,m,E,v,x,y,N,I,A,T={point:n,lineStart:r,lineEnd:s,polygonStart:function(){t.polygonStart();T.lineStart=l},polygonEnd:function(){t.polygonEnd();T.lineStart=r}};return T}function i(t,n,r,a,l,u,p,c,d,h,f,g,m,E){var v=p-t,x=c-n,y=v*v+x*x;if(y>4*o&&m--){var N=a+h,I=l+f,A=u+g,T=Math.sqrt(N*N+I*I+A*A),L=Math.asin(A/=T),S=ma(ma(A)-1)<_a||ma(r-d)<_a?(r+d)/2:Math.atan2(I,N),b=e(S,L),C=b[0],R=b[1],w=C-t,O=R-n,_=x*w-v*O;if(_*_/y>o||ma((v*w+x*O)/y-.5)>.3||s>a*h+l*f+u*g){i(t,n,r,a,l,u,C,R,S,N/=T,I/=T,A,m,E);E.point(C,R);i(C,R,S,N,I,A,p,c,d,h,f,g,m,E)}}}var o=.5,s=Math.cos(30*Ga),a=16;t.precision=function(e){if(!arguments.length)return Math.sqrt(o);a=(o=e*e)>0&&16;return t};return t}function ir(e){var t=rr(function(t,n){return e([t*ja,n*ja])});return function(e){return ur(t(e))}}function or(e){this.stream=e}function sr(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function ar(e){return lr(function(){return e})()}function lr(e){function t(e){e=a(e[0]*Ga,e[1]*Ga);return[e[0]*d+l,u-e[1]*d]}function n(e){e=a.invert((e[0]-l)/d,(u-e[1])/d);return e&&[e[0]*ja,e[1]*ja]}function r(){a=wn(s=dr(E,v,x),o);var e=o(g,m);l=h-e[0]*d;u=f+e[1]*d;return i()}function i(){p&&(p.valid=!1,p=null);return t}var o,s,a,l,u,p,c=rr(function(e,t){e=o(e,t);return[e[0]*d+l,u-e[1]*d]}),d=150,h=480,f=250,g=0,m=0,E=0,v=0,x=0,N=kl,I=y,A=null,T=null;t.stream=function(e){p&&(p.valid=!1);p=ur(N(s,c(I(e))));p.valid=!0;return p};t.clipAngle=function(e){if(!arguments.length)return A;N=null==e?(A=e,kl):Vn((A=+e)*Ga);return i()};t.clipExtent=function(e){if(!arguments.length)return T;T=e;I=e?zn(e[0][0],e[0][1],e[1][0],e[1][1]):y;return i()};t.scale=function(e){if(!arguments.length)return d;d=+e;return r()};t.translate=function(e){if(!arguments.length)return[h,f];h=+e[0];f=+e[1];return r()};t.center=function(e){if(!arguments.length)return[g*ja,m*ja];g=e[0]%360*Ga;m=e[1]%360*Ga;return r()};t.rotate=function(e){if(!arguments.length)return[E*ja,v*ja,x*ja];E=e[0]%360*Ga;v=e[1]%360*Ga;x=e.length>2?e[2]%360*Ga:0;return r()};ia.rebind(t,c,"precision");return function(){o=e.apply(this,arguments);t.invert=o.invert&&n;return r()}}function ur(e){return sr(e,function(t,n){e.point(t*Ga,n*Ga)})}function pr(e,t){return[e,t]}function cr(e,t){return[e>Pa?e-ka:-Pa>e?e+ka:e,t]}function dr(e,t,n){return e?t||n?wn(fr(e),gr(t,n)):fr(e):t||n?gr(t,n):cr}function hr(e){return function(t,n){return t+=e,[t>Pa?t-ka:-Pa>t?t+ka:t,n]}}function fr(e){var t=hr(e);t.invert=hr(-e);return t}function gr(e,t){function n(e,t){var n=Math.cos(t),a=Math.cos(e)*n,l=Math.sin(e)*n,u=Math.sin(t),p=u*r+a*i;return[Math.atan2(l*o-p*s,a*r-u*i),rt(p*o+l*s)]}var r=Math.cos(e),i=Math.sin(e),o=Math.cos(t),s=Math.sin(t);n.invert=function(e,t){var n=Math.cos(t),a=Math.cos(e)*n,l=Math.sin(e)*n,u=Math.sin(t),p=u*o-l*s;return[Math.atan2(l*o+u*s,a*r+p*i),rt(p*r-a*i)]};return n}function mr(e,t){var n=Math.cos(e),r=Math.sin(e);return function(i,o,s,a){var l=s*t;if(null!=i){i=Er(n,i);o=Er(n,o);(s>0?o>i:i>o)&&(i+=s*ka)}else{i=e+s*ka;o=e-.5*l}for(var u,p=i;s>0?p>o:o>p;p-=l)a.point((u=An([n,-r*Math.cos(p),-r*Math.sin(p)]))[0],u[1])}}function Er(e,t){var n=En(t);n[0]-=e;In(n);var r=nt(-n[1]);return((-n[2]<0?-r:r)+2*Math.PI-_a)%(2*Math.PI)}function vr(e,t,n){var r=ia.range(e,t-_a,n).concat(t);return function(e){return r.map(function(t){return[e,t]})}}function xr(e,t,n){var r=ia.range(e,t-_a,n).concat(t);return function(e){return r.map(function(t){return[t,e]})}}function yr(e){return e.source}function Nr(e){return e.target}function Ir(e,t,n,r){var i=Math.cos(t),o=Math.sin(t),s=Math.cos(r),a=Math.sin(r),l=i*Math.cos(e),u=i*Math.sin(e),p=s*Math.cos(n),c=s*Math.sin(n),d=2*Math.asin(Math.sqrt(at(r-t)+i*s*at(n-e))),h=1/Math.sin(d),f=d?function(e){var t=Math.sin(e*=d)*h,n=Math.sin(d-e)*h,r=n*l+t*p,i=n*u+t*c,s=n*o+t*a;return[Math.atan2(i,r)*ja,Math.atan2(s,Math.sqrt(r*r+i*i))*ja]}:function(){return[e*ja,t*ja]};f.distance=d;return f}function Ar(){function e(e,i){var o=Math.sin(i*=Ga),s=Math.cos(i),a=ma((e*=Ga)-t),l=Math.cos(a);Wl+=Math.atan2(Math.sqrt((a=s*Math.sin(a))*a+(a=r*o-n*s*l)*a),n*o+r*s*l);t=e,n=o,r=s}var t,n,r;$l.point=function(i,o){t=i*Ga,n=Math.sin(o*=Ga),r=Math.cos(o);$l.point=e};$l.lineEnd=function(){$l.point=$l.lineEnd=A}}function Tr(e,t){function n(t,n){var r=Math.cos(t),i=Math.cos(n),o=e(r*i);return[o*i*Math.sin(t),o*Math.sin(n)]}n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),i=t(r),o=Math.sin(i),s=Math.cos(i);return[Math.atan2(e*o,r*s),Math.asin(r&&n*o/r)]};return n}function Lr(e,t){function n(e,t){s>0?-Da+_a>t&&(t=-Da+_a):t>Da-_a&&(t=Da-_a);var n=s/Math.pow(i(t),o);return[n*Math.sin(o*e),s-n*Math.cos(o*e)]}var r=Math.cos(e),i=function(e){return Math.tan(Pa/4+e/2)},o=e===t?Math.sin(e):Math.log(r/Math.cos(t))/Math.log(i(t)/i(e)),s=r*Math.pow(i(e),o)/o;if(!o)return br;n.invert=function(e,t){var n=s-t,r=et(o)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/o,2*Math.atan(Math.pow(s/r,1/o))-Da]};return n}function Sr(e,t){function n(e,t){var n=o-t;return[n*Math.sin(i*e),o-n*Math.cos(i*e)]}var r=Math.cos(e),i=e===t?Math.sin(e):(r-Math.cos(t))/(t-e),o=r/i+e;if(ma(i)<_a)return pr;n.invert=function(e,t){var n=o-t;return[Math.atan2(e,n)/i,o-et(i)*Math.sqrt(e*e+n*n)]};return n}function br(e,t){return[e,Math.log(Math.tan(Pa/4+t/2))]}function Cr(e){var t,n=ar(e),r=n.scale,i=n.translate,o=n.clipExtent;n.scale=function(){var e=r.apply(n,arguments);return e===n?t?n.clipExtent(null):n:e};n.translate=function(){var e=i.apply(n,arguments);return e===n?t?n.clipExtent(null):n:e};n.clipExtent=function(e){var s=o.apply(n,arguments);if(s===n){if(t=null==e){var a=Pa*r(),l=i();o([[l[0]-a,l[1]-a],[l[0]+a,l[1]+a]])}}else t&&(s=null);return s};return n.clipExtent(null)}function Rr(e,t){return[Math.log(Math.tan(Pa/4+t/2)),-e]}function wr(e){return e[0]}function Or(e){return e[1]}function _r(e){for(var t=e.length,n=[0,1],r=2,i=2;t>i;i++){for(;r>1&&tt(e[n[r-2]],e[n[r-1]],e[i])<=0;)--r;n[r++]=i}return n.slice(0,r)}function Fr(e,t){return e[0]-t[0]||e[1]-t[1]}function Pr(e,t,n){return(n[0]-t[0])*(e[1]-t[1])<(n[1]-t[1])*(e[0]-t[0])}function kr(e,t,n,r){var i=e[0],o=n[0],s=t[0]-i,a=r[0]-o,l=e[1],u=n[1],p=t[1]-l,c=r[1]-u,d=(a*(l-u)-c*(i-o))/(c*s-a*p);return[i+d*s,l+d*p]}function Mr(e){var t=e[0],n=e[e.length-1];return!(t[0]-n[0]||t[1]-n[1])}function Dr(){ii(this);this.edge=this.site=this.circle=null}function Gr(e){var t=ou.pop()||new Dr;t.site=e;return t}function jr(e){Yr(e);nu.remove(e);ou.push(e);ii(e)}function Ur(e){var t=e.circle,n=t.x,r=t.cy,i={x:n,y:r},o=e.P,s=e.N,a=[e];jr(e);for(var l=o;l.circle&&ma(n-l.circle.x)<_a&&ma(r-l.circle.cy)<_a;){o=l.P;a.unshift(l);jr(l);l=o}a.unshift(l);Yr(l);for(var u=s;u.circle&&ma(n-u.circle.x)<_a&&ma(r-u.circle.cy)<_a;){s=u.N;a.push(u);jr(u);u=s}a.push(u);Yr(u);var p,c=a.length;for(p=1;c>p;++p){u=a[p];l=a[p-1];ti(u.edge,l.site,u.site,i)}l=a[0];u=a[c-1];u.edge=Jr(l.site,u.site,null,i);Kr(l);Kr(u)}function qr(e){for(var t,n,r,i,o=e.x,s=e.y,a=nu._;a;){r=Br(a,s)-o;if(r>_a)a=a.L;else{i=o-Vr(a,s);if(!(i>_a)){if(r>-_a){t=a.P;n=a}else if(i>-_a){t=a;n=a.N}else t=n=a;break}if(!a.R){t=a;break}a=a.R}}var l=Gr(e);nu.insert(t,l);if(t||n)if(t!==n)if(n){Yr(t);Yr(n);var u=t.site,p=u.x,c=u.y,d=e.x-p,h=e.y-c,f=n.site,g=f.x-p,m=f.y-c,E=2*(d*m-h*g),v=d*d+h*h,x=g*g+m*m,y={x:(m*v-h*x)/E+p,y:(d*x-g*v)/E+c};ti(n.edge,u,f,y);l.edge=Jr(u,e,null,y);n.edge=Jr(e,f,null,y);Kr(t);Kr(n)}else l.edge=Jr(t.site,l.site);else{Yr(t);n=Gr(t.site);nu.insert(l,n);l.edge=n.edge=Jr(t.site,l.site);Kr(t);Kr(n)}}function Br(e,t){var n=e.site,r=n.x,i=n.y,o=i-t;if(!o)return r;var s=e.P;if(!s)return-1/0;n=s.site;var a=n.x,l=n.y,u=l-t;if(!u)return a;var p=a-r,c=1/o-1/u,d=p/u;return c?(-d+Math.sqrt(d*d-2*c*(p*p/(-2*u)-l+u/2+i-o/2)))/c+r:(r+a)/2}function Vr(e,t){var n=e.N;if(n)return Br(n,t);var r=e.site;return r.y===t?r.x:1/0}function Hr(e){this.site=e;this.edges=[]}function zr(e){for(var t,n,r,i,o,s,a,l,u,p,c=e[0][0],d=e[1][0],h=e[0][1],f=e[1][1],g=tu,m=g.length;m--;){o=g[m];if(o&&o.prepare()){a=o.edges;l=a.length;s=0;for(;l>s;){p=a[s].end(),r=p.x,i=p.y;u=a[++s%l].start(),t=u.x,n=u.y;if(ma(r-t)>_a||ma(i-n)>_a){a.splice(s,0,new ni(ei(o.site,p,ma(r-c)<_a&&f-i>_a?{x:c,y:ma(t-c)<_a?n:f}:ma(i-f)<_a&&d-r>_a?{x:ma(n-f)<_a?t:d,y:f}:ma(r-d)<_a&&i-h>_a?{x:d,y:ma(t-d)<_a?n:h}:ma(i-h)<_a&&r-c>_a?{x:ma(n-h)<_a?t:c,y:h}:null),o.site,null));++l}}}}}function Wr(e,t){return t.angle-e.angle}function $r(){ii(this);this.x=this.y=this.arc=this.site=this.cy=null}function Kr(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,i=e.site,o=n.site;if(r!==o){var s=i.x,a=i.y,l=r.x-s,u=r.y-a,p=o.x-s,c=o.y-a,d=2*(l*c-u*p);if(!(d>=-Fa)){var h=l*l+u*u,f=p*p+c*c,g=(c*h-u*f)/d,m=(l*f-p*h)/d,c=m+a,E=su.pop()||new $r;E.arc=e;E.site=i;E.x=g+s;E.y=c+Math.sqrt(g*g+m*m);E.cy=c;e.circle=E;for(var v=null,x=iu._;x;)if(E.y<x.y||E.y===x.y&&E.x<=x.x){if(!x.L){v=x.P;break}x=x.L}else{if(!x.R){v=x;break}x=x.R}iu.insert(v,E);v||(ru=E)}}}}function Yr(e){var t=e.circle;if(t){t.P||(ru=t.N);iu.remove(t);su.push(t);ii(t);e.circle=null}}function Qr(e){for(var t,n=eu,r=Hn(e[0][0],e[0][1],e[1][0],e[1][1]),i=n.length;i--;){t=n[i];if(!Xr(t,e)||!r(t)||ma(t.a.x-t.b.x)<_a&&ma(t.a.y-t.b.y)<_a){t.a=t.b=null;n.splice(i,1)}}}function Xr(e,t){var n=e.b;if(n)return!0;var r,i,o=e.a,s=t[0][0],a=t[1][0],l=t[0][1],u=t[1][1],p=e.l,c=e.r,d=p.x,h=p.y,f=c.x,g=c.y,m=(d+f)/2,E=(h+g)/2;if(g===h){if(s>m||m>=a)return;if(d>f){if(o){if(o.y>=u)return}else o={x:m,y:l};n={x:m,y:u}}else{if(o){if(o.y<l)return}else o={x:m,y:u};n={x:m,y:l}}}else{r=(d-f)/(g-h);i=E-r*m;if(-1>r||r>1)if(d>f){if(o){if(o.y>=u)return}else o={x:(l-i)/r,y:l};n={x:(u-i)/r,y:u}}else{if(o){if(o.y<l)return}else o={x:(u-i)/r,y:u};n={x:(l-i)/r,y:l}}else if(g>h){if(o){if(o.x>=a)return}else o={x:s,y:r*s+i};n={x:a,y:r*a+i}}else{if(o){if(o.x<s)return}else o={x:a,y:r*a+i};n={x:s,y:r*s+i}}}e.a=o;e.b=n;return!0}function Zr(e,t){this.l=e;this.r=t;this.a=this.b=null}function Jr(e,t,n,r){var i=new Zr(e,t);eu.push(i);n&&ti(i,e,t,n);r&&ti(i,t,e,r);tu[e.i].edges.push(new ni(i,e,t));tu[t.i].edges.push(new ni(i,t,e));return i}function ei(e,t,n){var r=new Zr(e,null);r.a=t;r.b=n;eu.push(r);return r}function ti(e,t,n,r){if(e.a||e.b)e.l===n?e.b=r:e.a=r;else{e.a=r;e.l=t;e.r=n}}function ni(e,t,n){var r=e.a,i=e.b;this.edge=e;this.site=t;this.angle=n?Math.atan2(n.y-t.y,n.x-t.x):e.l===t?Math.atan2(i.x-r.x,r.y-i.y):Math.atan2(r.x-i.x,i.y-r.y)}function ri(){this._=null}function ii(e){e.U=e.C=e.L=e.R=e.P=e.N=null}function oi(e,t){var n=t,r=t.R,i=n.U;i?i.L===n?i.L=r:i.R=r:e._=r;r.U=i;n.U=r;n.R=r.L;n.R&&(n.R.U=n);r.L=n}function si(e,t){var n=t,r=t.L,i=n.U;i?i.L===n?i.L=r:i.R=r:e._=r;r.U=i;n.U=r;n.L=r.R;n.L&&(n.L.U=n);r.R=n}function ai(e){for(;e.L;)e=e.L;return e}function li(e,t){var n,r,i,o=e.sort(ui).pop();eu=[];tu=new Array(e.length);nu=new ri;iu=new ri;for(;;){i=ru;if(o&&(!i||o.y<i.y||o.y===i.y&&o.x<i.x)){if(o.x!==n||o.y!==r){tu[o.i]=new Hr(o);qr(o);n=o.x,r=o.y}o=e.pop()}else{if(!i)break;Ur(i.arc)}}t&&(Qr(t),zr(t));var s={cells:tu,edges:eu};nu=iu=eu=tu=null;return s}function ui(e,t){return t.y-e.y||t.x-e.x}function pi(e,t,n){return(e.x-n.x)*(t.y-e.y)-(e.x-t.x)*(n.y-e.y)}function ci(e){return e.x}function di(e){return e.y}function hi(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function fi(e,t,n,r,i,o){if(!e(t,n,r,i,o)){var s=.5*(n+i),a=.5*(r+o),l=t.nodes;l[0]&&fi(e,l[0],n,r,s,a);l[1]&&fi(e,l[1],s,r,i,a);l[2]&&fi(e,l[2],n,a,s,o);l[3]&&fi(e,l[3],s,a,i,o)}}function gi(e,t,n,r,i,o,s){var a,l=1/0;(function u(e,p,c,d,h){if(!(p>o||c>s||r>d||i>h)){if(f=e.point){var f,g=t-e.x,m=n-e.y,E=g*g+m*m;if(l>E){var v=Math.sqrt(l=E);r=t-v,i=n-v;o=t+v,s=n+v;a=f}}for(var x=e.nodes,y=.5*(p+d),N=.5*(c+h),I=t>=y,A=n>=N,T=A<<1|I,L=T+4;L>T;++T)if(e=x[3&T])switch(3&T){case 0:u(e,p,c,y,N);break;case 1:u(e,y,c,d,N);break;case 2:u(e,p,N,y,h);break;case 3:u(e,y,N,d,h)}}})(e,r,i,o,s);return a}function mi(e,t){e=ia.rgb(e);t=ia.rgb(t);var n=e.r,r=e.g,i=e.b,o=t.r-n,s=t.g-r,a=t.b-i;return function(e){return"#"+It(Math.round(n+o*e))+It(Math.round(r+s*e))+It(Math.round(i+a*e))}}function Ei(e,t){var n,r={},i={};for(n in e)n in t?r[n]=yi(e[n],t[n]):i[n]=e[n];for(n in t)n in e||(i[n]=t[n]);return function(e){for(n in r)i[n]=r[n](e);return i}}function vi(e,t){e=+e,t=+t;return function(n){return e*(1-n)+t*n}}function xi(e,t){var n,r,i,o=lu.lastIndex=uu.lastIndex=0,s=-1,a=[],l=[];e+="",t+="";for(;(n=lu.exec(e))&&(r=uu.exec(t));){if((i=r.index)>o){i=t.slice(o,i);a[s]?a[s]+=i:a[++s]=i}if((n=n[0])===(r=r[0]))a[s]?a[s]+=r:a[++s]=r;else{a[++s]=null;l.push({i:s,x:vi(n,r)})}o=uu.lastIndex}if(o<t.length){i=t.slice(o);a[s]?a[s]+=i:a[++s]=i}return a.length<2?l[0]?(t=l[0].x,function(e){return t(e)+""}):function(){return t}:(t=l.length,function(e){for(var n,r=0;t>r;++r)a[(n=l[r]).i]=n.x(e);return a.join("")})}function yi(e,t){for(var n,r=ia.interpolators.length;--r>=0&&!(n=ia.interpolators[r](e,t)););return n}function Ni(e,t){var n,r=[],i=[],o=e.length,s=t.length,a=Math.min(e.length,t.length);for(n=0;a>n;++n)r.push(yi(e[n],t[n]));for(;o>n;++n)i[n]=e[n];for(;s>n;++n)i[n]=t[n];return function(e){for(n=0;a>n;++n)i[n]=r[n](e);return i}}function Ii(e){return function(t){return 0>=t?0:t>=1?1:e(t)}}function Ai(e){return function(t){return 1-e(1-t)}}function Ti(e){return function(t){return.5*(.5>t?e(2*t):2-e(2-2*t))}}function Li(e){return e*e}function Si(e){return e*e*e}function bi(e){if(0>=e)return 0;if(e>=1)return 1;var t=e*e,n=t*e;return 4*(.5>e?n:3*(e-t)+n-.75)}function Ci(e){return function(t){return Math.pow(t,e)}}function Ri(e){return 1-Math.cos(e*Da)}function wi(e){return Math.pow(2,10*(e-1))}function Oi(e){return 1-Math.sqrt(1-e*e)}function _i(e,t){var n;arguments.length<2&&(t=.45);arguments.length?n=t/ka*Math.asin(1/e):(e=1,n=t/4);return function(r){return 1+e*Math.pow(2,-10*r)*Math.sin((r-n)*ka/t)}}function Fi(e){e||(e=1.70158);return function(t){return t*t*((e+1)*t-e)}}function Pi(e){return 1/2.75>e?7.5625*e*e:2/2.75>e?7.5625*(e-=1.5/2.75)*e+.75:2.5/2.75>e?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ki(e,t){e=ia.hcl(e);t=ia.hcl(t);var n=e.h,r=e.c,i=e.l,o=t.h-n,s=t.c-r,a=t.l-i;isNaN(s)&&(s=0,r=isNaN(r)?t.c:r);isNaN(o)?(o=0,n=isNaN(n)?t.h:n):o>180?o-=360:-180>o&&(o+=360);return function(e){return dt(n+o*e,r+s*e,i+a*e)+""}}function Mi(e,t){e=ia.hsl(e);t=ia.hsl(t);var n=e.h,r=e.s,i=e.l,o=t.h-n,s=t.s-r,a=t.l-i;isNaN(s)&&(s=0,r=isNaN(r)?t.s:r);isNaN(o)?(o=0,n=isNaN(n)?t.h:n):o>180?o-=360:-180>o&&(o+=360);return function(e){return pt(n+o*e,r+s*e,i+a*e)+""}}function Di(e,t){e=ia.lab(e);t=ia.lab(t);var n=e.l,r=e.a,i=e.b,o=t.l-n,s=t.a-r,a=t.b-i;return function(e){return ft(n+o*e,r+s*e,i+a*e)+""}}function Gi(e,t){t-=e;return function(n){return Math.round(e+t*n)}}function ji(e){var t=[e.a,e.b],n=[e.c,e.d],r=qi(t),i=Ui(t,n),o=qi(Bi(n,t,-i))||0;if(t[0]*n[1]<n[0]*t[1]){t[0]*=-1;t[1]*=-1;r*=-1;i*=-1}this.rotate=(r?Math.atan2(t[1],t[0]):Math.atan2(-n[0],n[1]))*ja;this.translate=[e.e,e.f];this.scale=[r,o];this.skew=o?Math.atan2(i,o)*ja:0}function Ui(e,t){return e[0]*t[0]+e[1]*t[1]}function qi(e){var t=Math.sqrt(Ui(e,e));if(t){e[0]/=t;e[1]/=t}return t}function Bi(e,t,n){e[0]+=n*t[0];e[1]+=n*t[1];return e}function Vi(e,t){var n,r=[],i=[],o=ia.transform(e),s=ia.transform(t),a=o.translate,l=s.translate,u=o.rotate,p=s.rotate,c=o.skew,d=s.skew,h=o.scale,f=s.scale;if(a[0]!=l[0]||a[1]!=l[1]){r.push("translate(",null,",",null,")");i.push({i:1,x:vi(a[0],l[0])},{i:3,x:vi(a[1],l[1])})}else r.push(l[0]||l[1]?"translate("+l+")":"");if(u!=p){u-p>180?p+=360:p-u>180&&(u+=360);i.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:vi(u,p)})}else p&&r.push(r.pop()+"rotate("+p+")");c!=d?i.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:vi(c,d)}):d&&r.push(r.pop()+"skewX("+d+")");if(h[0]!=f[0]||h[1]!=f[1]){n=r.push(r.pop()+"scale(",null,",",null,")");i.push({i:n-4,x:vi(h[0],f[0])},{i:n-2,x:vi(h[1],f[1])})}else(1!=f[0]||1!=f[1])&&r.push(r.pop()+"scale("+f+")");n=i.length;return function(e){for(var t,o=-1;++o<n;)r[(t=i[o]).i]=t.x(e);return r.join("")}}function Hi(e,t){t=(t-=e=+e)||1/t;return function(n){return(n-e)/t}}function zi(e,t){t=(t-=e=+e)||1/t;return function(n){return Math.max(0,Math.min(1,(n-e)/t))}}function Wi(e){for(var t=e.source,n=e.target,r=Ki(t,n),i=[t];t!==r;){t=t.parent;i.push(t)}for(var o=i.length;n!==r;){i.splice(o,0,n);n=n.parent}return i}function $i(e){for(var t=[],n=e.parent;null!=n;){t.push(e);e=n;n=n.parent}t.push(e);return t}function Ki(e,t){if(e===t)return e;for(var n=$i(e),r=$i(t),i=n.pop(),o=r.pop(),s=null;i===o;){s=i;i=n.pop();o=r.pop()}return s}function Yi(e){e.fixed|=2}function Qi(e){e.fixed&=-7}function Xi(e){e.fixed|=4;e.px=e.x,e.py=e.y}function Zi(e){e.fixed&=-5}function Ji(e,t,n){var r=0,i=0;e.charge=0;if(!e.leaf)for(var o,s=e.nodes,a=s.length,l=-1;++l<a;){o=s[l];if(null!=o){Ji(o,t,n);e.charge+=o.charge;r+=o.charge*o.cx;i+=o.charge*o.cy}}if(e.point){if(!e.leaf){e.point.x+=Math.random()-.5;e.point.y+=Math.random()-.5}var u=t*n[e.point.index];e.charge+=e.pointCharge=u;r+=u*e.point.x;i+=u*e.point.y}e.cx=r/e.charge;e.cy=i/e.charge}function eo(e,t){ia.rebind(e,t,"sort","children","value");e.nodes=e;e.links=so;return e}function to(e,t){for(var n=[e];null!=(e=n.pop());){t(e);if((i=e.children)&&(r=i.length))for(var r,i;--r>=0;)n.push(i[r])}}function no(e,t){for(var n=[e],r=[];null!=(e=n.pop());){r.push(e);if((o=e.children)&&(i=o.length))for(var i,o,s=-1;++s<i;)n.push(o[s])}for(;null!=(e=r.pop());)t(e)}function ro(e){return e.children}function io(e){return e.value}function oo(e,t){return t.value-e.value}function so(e){return ia.merge(e.map(function(e){return(e.children||[]).map(function(t){return{source:e,target:t}})}))}function ao(e){return e.x}function lo(e){return e.y}function uo(e,t,n){e.y0=t;e.y=n}function po(e){return ia.range(e.length)}function co(e){for(var t=-1,n=e[0].length,r=[];++t<n;)r[t]=0;return r}function ho(e){for(var t,n=1,r=0,i=e[0][1],o=e.length;o>n;++n)if((t=e[n][1])>i){r=n;i=t}return r}function fo(e){return e.reduce(go,0)}function go(e,t){return e+t[1]}function mo(e,t){return Eo(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function Eo(e,t){for(var n=-1,r=+e[0],i=(e[1]-r)/t,o=[];++n<=t;)o[n]=i*n+r;return o}function vo(e){return[ia.min(e),ia.max(e)]}function xo(e,t){return e.value-t.value}function yo(e,t){var n=e._pack_next;e._pack_next=t;t._pack_prev=e;t._pack_next=n;n._pack_prev=t}function No(e,t){e._pack_next=t;t._pack_prev=e}function Io(e,t){var n=t.x-e.x,r=t.y-e.y,i=e.r+t.r;return.999*i*i>n*n+r*r}function Ao(e){function t(e){p=Math.min(e.x-e.r,p);c=Math.max(e.x+e.r,c);d=Math.min(e.y-e.r,d);h=Math.max(e.y+e.r,h)}if((n=e.children)&&(u=n.length)){var n,r,i,o,s,a,l,u,p=1/0,c=-1/0,d=1/0,h=-1/0;n.forEach(To);r=n[0];r.x=-r.r;r.y=0;t(r);if(u>1){i=n[1];i.x=i.r;i.y=0;t(i);if(u>2){o=n[2];bo(r,i,o);t(o);yo(r,o);r._pack_prev=o;yo(o,i);i=r._pack_next;for(s=3;u>s;s++){bo(r,i,o=n[s]);var f=0,g=1,m=1;for(a=i._pack_next;a!==i;a=a._pack_next,g++)if(Io(a,o)){f=1;break}if(1==f)for(l=r._pack_prev;l!==a._pack_prev&&!Io(l,o);l=l._pack_prev,m++);if(f){m>g||g==m&&i.r<r.r?No(r,i=a):No(r=l,i);s--}else{yo(r,o);i=o;t(o)}}}}var E=(p+c)/2,v=(d+h)/2,x=0;for(s=0;u>s;s++){o=n[s];o.x-=E;o.y-=v;x=Math.max(x,o.r+Math.sqrt(o.x*o.x+o.y*o.y))}e.r=x;n.forEach(Lo)}}function To(e){e._pack_next=e._pack_prev=e}function Lo(e){delete e._pack_next;delete e._pack_prev}function So(e,t,n,r){var i=e.children;e.x=t+=r*e.x;e.y=n+=r*e.y;e.r*=r;if(i)for(var o=-1,s=i.length;++o<s;)So(i[o],t,n,r)}function bo(e,t,n){var r=e.r+n.r,i=t.x-e.x,o=t.y-e.y;if(r&&(i||o)){var s=t.r+n.r,a=i*i+o*o;s*=s;r*=r;var l=.5+(r-s)/(2*a),u=Math.sqrt(Math.max(0,2*s*(r+a)-(r-=a)*r-s*s))/(2*a);n.x=e.x+l*i+u*o;n.y=e.y+l*o-u*i}else{n.x=e.x+r;n.y=e.y}}function Co(e,t){return e.parent==t.parent?1:2}function Ro(e){var t=e.children;return t.length?t[0]:e.t}function wo(e){var t,n=e.children;return(t=n.length)?n[t-1]:e.t}function Oo(e,t,n){var r=n/(t.i-e.i);t.c-=r;t.s+=n;e.c+=r;t.z+=n;t.m+=n}function _o(e){for(var t,n=0,r=0,i=e.children,o=i.length;--o>=0;){t=i[o];t.z+=n;t.m+=n;n+=t.s+(r+=t.c)}}function Fo(e,t,n){return e.a.parent===t.parent?e.a:n}function Po(e){return 1+ia.max(e,function(e){return e.y})}function ko(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}function Mo(e){var t=e.children;return t&&t.length?Mo(t[0]):e}function Do(e){var t,n=e.children;return n&&(t=n.length)?Do(n[t-1]):e}function Go(e){return{x:e.x,y:e.y,dx:e.dx,dy:e.dy}}function jo(e,t){var n=e.x+t[3],r=e.y+t[0],i=e.dx-t[1]-t[3],o=e.dy-t[0]-t[2];if(0>i){n+=i/2;i=0}if(0>o){r+=o/2;o=0}return{x:n,y:r,dx:i,dy:o}}function Uo(e){var t=e[0],n=e[e.length-1];return n>t?[t,n]:[n,t]}function qo(e){return e.rangeExtent?e.rangeExtent():Uo(e.range())}function Bo(e,t,n,r){var i=n(e[0],e[1]),o=r(t[0],t[1]);return function(e){return o(i(e))}}function Vo(e,t){var n,r=0,i=e.length-1,o=e[r],s=e[i];if(o>s){n=r,r=i,i=n;n=o,o=s,s=n}e[r]=t.floor(o);e[i]=t.ceil(s);return e}function Ho(e){return e?{floor:function(t){return Math.floor(t/e)*e},ceil:function(t){return Math.ceil(t/e)*e}}:yu}function zo(e,t,n,r){var i=[],o=[],s=0,a=Math.min(e.length,t.length)-1;if(e[a]<e[0]){e=e.slice().reverse();t=t.slice().reverse()}for(;++s<=a;){i.push(n(e[s-1],e[s]));o.push(r(t[s-1],t[s]))}return function(t){var n=ia.bisect(e,t,1,a)-1;return o[n](i[n](t))}}function Wo(e,t,n,r){function i(){var i=Math.min(e.length,t.length)>2?zo:Bo,l=r?zi:Hi;s=i(e,t,l,n);a=i(t,e,l,yi);return o}function o(e){return s(e)}var s,a;o.invert=function(e){return a(e)};o.domain=function(t){if(!arguments.length)return e;e=t.map(Number);return i()};o.range=function(e){if(!arguments.length)return t;t=e;return i()};o.rangeRound=function(e){return o.range(e).interpolate(Gi)};o.clamp=function(e){if(!arguments.length)return r;r=e;return i()};o.interpolate=function(e){if(!arguments.length)return n;n=e;return i()};o.ticks=function(t){return Qo(e,t)};o.tickFormat=function(t,n){return Xo(e,t,n)};o.nice=function(t){Ko(e,t);return i()};o.copy=function(){return Wo(e,t,n,r)};return i()}function $o(e,t){return ia.rebind(e,t,"range","rangeRound","interpolate","clamp")}function Ko(e,t){return Vo(e,Ho(Yo(e,t)[2]))}function Yo(e,t){null==t&&(t=10);var n=Uo(e),r=n[1]-n[0],i=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),o=t/r*i;.15>=o?i*=10:.35>=o?i*=5:.75>=o&&(i*=2);n[0]=Math.ceil(n[0]/i)*i;n[1]=Math.floor(n[1]/i)*i+.5*i;n[2]=i;return n}function Qo(e,t){return ia.range.apply(ia,Yo(e,t))}function Xo(e,t,n){var r=Yo(e,t);if(n){var i=ll.exec(n);i.shift();if("s"===i[8]){var o=ia.formatPrefix(Math.max(ma(r[0]),ma(r[1])));i[7]||(i[7]="."+Zo(o.scale(r[2])));i[8]="f";n=ia.format(i.join(""));return function(e){return n(o.scale(e))+o.symbol}}i[7]||(i[7]="."+Jo(i[8],r));n=i.join("")}else n=",."+Zo(r[2])+"f";return ia.format(n)}function Zo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}function Jo(e,t){var n=Zo(t[2]);return e in Nu?Math.abs(n-Zo(Math.max(ma(t[0]),ma(t[1]))))+ +("e"!==e):n-2*("%"===e)}function es(e,t,n,r){function i(e){return(n?Math.log(0>e?0:e):-Math.log(e>0?0:-e))/Math.log(t)}function o(e){return n?Math.pow(t,e):-Math.pow(t,-e)}function s(t){return e(i(t))}s.invert=function(t){return o(e.invert(t))};s.domain=function(t){if(!arguments.length)return r;n=t[0]>=0;e.domain((r=t.map(Number)).map(i));return s};s.base=function(n){if(!arguments.length)return t;t=+n;e.domain(r.map(i));return s};s.nice=function(){var t=Vo(r.map(i),n?Math:Au);e.domain(t);r=t.map(o);return s};s.ticks=function(){var e=Uo(r),s=[],a=e[0],l=e[1],u=Math.floor(i(a)),p=Math.ceil(i(l)),c=t%1?2:t;if(isFinite(p-u)){if(n){for(;p>u;u++)for(var d=1;c>d;d++)s.push(o(u)*d);s.push(o(u))}else{s.push(o(u));for(;u++<p;)for(var d=c-1;d>0;d--)s.push(o(u)*d)}for(u=0;s[u]<a;u++);for(p=s.length;s[p-1]>l;p--);s=s.slice(u,p)}return s};s.tickFormat=function(e,t){if(!arguments.length)return Iu;arguments.length<2?t=Iu:"function"!=typeof t&&(t=ia.format(t));var r,a=Math.max(.1,e/s.ticks().length),l=n?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(e){return e/o(l(i(e)+r))<=a?t(e):""}};s.copy=function(){return es(e.copy(),t,n,r)};return $o(s,e)}function ts(e,t,n){function r(t){return e(i(t))}var i=ns(t),o=ns(1/t);r.invert=function(t){return o(e.invert(t))};r.domain=function(t){if(!arguments.length)return n;e.domain((n=t.map(Number)).map(i));return r};r.ticks=function(e){return Qo(n,e)};r.tickFormat=function(e,t){return Xo(n,e,t)};r.nice=function(e){return r.domain(Ko(n,e))};r.exponent=function(s){if(!arguments.length)return t;i=ns(t=s);o=ns(1/t);e.domain(n.map(i));return r};r.copy=function(){return ts(e.copy(),t,n)};return $o(r,e)}function ns(e){return function(t){return 0>t?-Math.pow(-t,e):Math.pow(t,e)}}function rs(e,t){function n(n){return o[((i.get(n)||("range"===t.t?i.set(n,e.push(n)):0/0))-1)%o.length]}function r(t,n){return ia.range(e.length).map(function(e){return t+n*e})}var i,o,s;n.domain=function(r){if(!arguments.length)return e;e=[];i=new c;for(var o,s=-1,a=r.length;++s<a;)i.has(o=r[s])||i.set(o,e.push(o));return n[t.t].apply(n,t.a)};n.range=function(e){if(!arguments.length)return o;o=e;s=0;t={t:"range",a:arguments};return n};n.rangePoints=function(i,a){arguments.length<2&&(a=0);var l=i[0],u=i[1],p=e.length<2?(l=(l+u)/2,0):(u-l)/(e.length-1+a);o=r(l+p*a/2,p);s=0;t={t:"rangePoints",a:arguments};return n};n.rangeRoundPoints=function(i,a){arguments.length<2&&(a=0);var l=i[0],u=i[1],p=e.length<2?(l=u=Math.round((l+u)/2),0):(u-l)/(e.length-1+a)|0;o=r(l+Math.round(p*a/2+(u-l-(e.length-1+a)*p)/2),p);s=0;t={t:"rangeRoundPoints",a:arguments};return n};n.rangeBands=function(i,a,l){arguments.length<2&&(a=0);arguments.length<3&&(l=a);var u=i[1]<i[0],p=i[u-0],c=i[1-u],d=(c-p)/(e.length-a+2*l);o=r(p+d*l,d);u&&o.reverse();s=d*(1-a);t={t:"rangeBands",a:arguments};return n};n.rangeRoundBands=function(i,a,l){arguments.length<2&&(a=0);arguments.length<3&&(l=a);var u=i[1]<i[0],p=i[u-0],c=i[1-u],d=Math.floor((c-p)/(e.length-a+2*l));o=r(p+Math.round((c-p-(e.length-a)*d)/2),d);u&&o.reverse();s=Math.round(d*(1-a));t={t:"rangeRoundBands",a:arguments};return n};n.rangeBand=function(){return s};n.rangeExtent=function(){return Uo(t.a[0])};n.copy=function(){return rs(e,t)};return n.domain(e)}function is(e,t){function n(){var n=0,i=t.length;a=[];for(;++n<i;)a[n-1]=ia.quantile(e,n/i);return r}function r(e){return isNaN(e=+e)?void 0:t[ia.bisect(a,e)]}var a;r.domain=function(t){if(!arguments.length)return e;e=t.map(o).filter(s).sort(i);return n()};r.range=function(e){if(!arguments.length)return t;t=e;return n()};r.quantiles=function(){return a};r.invertExtent=function(n){n=t.indexOf(n);return 0>n?[0/0,0/0]:[n>0?a[n-1]:e[0],n<a.length?a[n]:e[e.length-1]]};r.copy=function(){return is(e,t)};return n()}function os(e,t,n){function r(t){return n[Math.max(0,Math.min(s,Math.floor(o*(t-e))))]}function i(){o=n.length/(t-e);s=n.length-1;return r}var o,s;r.domain=function(n){if(!arguments.length)return[e,t];e=+n[0];t=+n[n.length-1];return i()};r.range=function(e){if(!arguments.length)return n;n=e;return i()};r.invertExtent=function(t){t=n.indexOf(t);t=0>t?0/0:t/o+e;return[t,t+1/o]};r.copy=function(){return os(e,t,n)};return i()}function ss(e,t){function n(n){return n>=n?t[ia.bisect(e,n)]:void 0}n.domain=function(t){if(!arguments.length)return e;e=t;return n};n.range=function(e){if(!arguments.length)return t;t=e;return n};n.invertExtent=function(n){n=t.indexOf(n);return[e[n-1],e[n]]};n.copy=function(){return ss(e,t)};return n}function as(e){function t(e){return+e}t.invert=t;t.domain=t.range=function(n){if(!arguments.length)return e;
e=n.map(t);return t};t.ticks=function(t){return Qo(e,t)};t.tickFormat=function(t,n){return Xo(e,t,n)};t.copy=function(){return as(e)};return t}function ls(){return 0}function us(e){return e.innerRadius}function ps(e){return e.outerRadius}function cs(e){return e.startAngle}function ds(e){return e.endAngle}function hs(e){return e&&e.padAngle}function fs(e,t,n,r){return(e-n)*t-(t-r)*e>0?0:1}function gs(e,t,n,r,i){var o=e[0]-t[0],s=e[1]-t[1],a=(i?r:-r)/Math.sqrt(o*o+s*s),l=a*s,u=-a*o,p=e[0]+l,c=e[1]+u,d=t[0]+l,h=t[1]+u,f=(p+d)/2,g=(c+h)/2,m=d-p,E=h-c,v=m*m+E*E,x=n-r,y=p*h-d*c,N=(0>E?-1:1)*Math.sqrt(x*x*v-y*y),I=(y*E-m*N)/v,A=(-y*m-E*N)/v,T=(y*E+m*N)/v,L=(-y*m+E*N)/v,S=I-f,b=A-g,C=T-f,R=L-g;S*S+b*b>C*C+R*R&&(I=T,A=L);return[[I-l,A-u],[I*n/x,A*n/x]]}function ms(e){function t(t){function s(){u.push("M",o(e(p),a))}for(var l,u=[],p=[],c=-1,d=t.length,h=Ct(n),f=Ct(r);++c<d;)if(i.call(this,l=t[c],c))p.push([+h.call(this,l,c),+f.call(this,l,c)]);else if(p.length){s();p=[]}p.length&&s();return u.length?u.join(""):null}var n=wr,r=Or,i=On,o=Es,s=o.key,a=.7;t.x=function(e){if(!arguments.length)return n;n=e;return t};t.y=function(e){if(!arguments.length)return r;r=e;return t};t.defined=function(e){if(!arguments.length)return i;i=e;return t};t.interpolate=function(e){if(!arguments.length)return s;s="function"==typeof e?o=e:(o=Ru.get(e)||Es).key;return t};t.tension=function(e){if(!arguments.length)return a;a=e;return t};return t}function Es(e){return e.join("L")}function vs(e){return Es(e)+"Z"}function xs(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("H",(r[0]+(r=e[t])[0])/2,"V",r[1]);n>1&&i.push("H",r[0]);return i.join("")}function ys(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("V",(r=e[t])[1],"H",r[0]);return i.join("")}function Ns(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("H",(r=e[t])[0],"V",r[1]);return i.join("")}function Is(e,t){return e.length<4?Es(e):e[1]+Ls(e.slice(1,-1),Ss(e,t))}function As(e,t){return e.length<3?Es(e):e[0]+Ls((e.push(e[0]),e),Ss([e[e.length-2]].concat(e,[e[1]]),t))}function Ts(e,t){return e.length<3?Es(e):e[0]+Ls(e,Ss(e,t))}function Ls(e,t){if(t.length<1||e.length!=t.length&&e.length!=t.length+2)return Es(e);var n=e.length!=t.length,r="",i=e[0],o=e[1],s=t[0],a=s,l=1;if(n){r+="Q"+(o[0]-2*s[0]/3)+","+(o[1]-2*s[1]/3)+","+o[0]+","+o[1];i=e[1];l=2}if(t.length>1){a=t[1];o=e[l];l++;r+="C"+(i[0]+s[0])+","+(i[1]+s[1])+","+(o[0]-a[0])+","+(o[1]-a[1])+","+o[0]+","+o[1];for(var u=2;u<t.length;u++,l++){o=e[l];a=t[u];r+="S"+(o[0]-a[0])+","+(o[1]-a[1])+","+o[0]+","+o[1]}}if(n){var p=e[l];r+="Q"+(o[0]+2*a[0]/3)+","+(o[1]+2*a[1]/3)+","+p[0]+","+p[1]}return r}function Ss(e,t){for(var n,r=[],i=(1-t)/2,o=e[0],s=e[1],a=1,l=e.length;++a<l;){n=o;o=s;s=e[a];r.push([i*(s[0]-n[0]),i*(s[1]-n[1])])}return r}function bs(e){if(e.length<3)return Es(e);var t=1,n=e.length,r=e[0],i=r[0],o=r[1],s=[i,i,i,(r=e[1])[0]],a=[o,o,o,r[1]],l=[i,",",o,"L",Os(_u,s),",",Os(_u,a)];e.push(e[n-1]);for(;++t<=n;){r=e[t];s.shift();s.push(r[0]);a.shift();a.push(r[1]);_s(l,s,a)}e.pop();l.push("L",r);return l.join("")}function Cs(e){if(e.length<4)return Es(e);for(var t,n=[],r=-1,i=e.length,o=[0],s=[0];++r<3;){t=e[r];o.push(t[0]);s.push(t[1])}n.push(Os(_u,o)+","+Os(_u,s));--r;for(;++r<i;){t=e[r];o.shift();o.push(t[0]);s.shift();s.push(t[1]);_s(n,o,s)}return n.join("")}function Rs(e){for(var t,n,r=-1,i=e.length,o=i+4,s=[],a=[];++r<4;){n=e[r%i];s.push(n[0]);a.push(n[1])}t=[Os(_u,s),",",Os(_u,a)];--r;for(;++r<o;){n=e[r%i];s.shift();s.push(n[0]);a.shift();a.push(n[1]);_s(t,s,a)}return t.join("")}function ws(e,t){var n=e.length-1;if(n)for(var r,i,o=e[0][0],s=e[0][1],a=e[n][0]-o,l=e[n][1]-s,u=-1;++u<=n;){r=e[u];i=u/n;r[0]=t*r[0]+(1-t)*(o+i*a);r[1]=t*r[1]+(1-t)*(s+i*l)}return bs(e)}function Os(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}function _s(e,t,n){e.push("C",Os(wu,t),",",Os(wu,n),",",Os(Ou,t),",",Os(Ou,n),",",Os(_u,t),",",Os(_u,n))}function Fs(e,t){return(t[1]-e[1])/(t[0]-e[0])}function Ps(e){for(var t=0,n=e.length-1,r=[],i=e[0],o=e[1],s=r[0]=Fs(i,o);++t<n;)r[t]=(s+(s=Fs(i=o,o=e[t+1])))/2;r[t]=s;return r}function ks(e){for(var t,n,r,i,o=[],s=Ps(e),a=-1,l=e.length-1;++a<l;){t=Fs(e[a],e[a+1]);if(ma(t)<_a)s[a]=s[a+1]=0;else{n=s[a]/t;r=s[a+1]/t;i=n*n+r*r;if(i>9){i=3*t/Math.sqrt(i);s[a]=i*n;s[a+1]=i*r}}}a=-1;for(;++a<=l;){i=(e[Math.min(l,a+1)][0]-e[Math.max(0,a-1)][0])/(6*(1+s[a]*s[a]));o.push([i||0,s[a]*i||0])}return o}function Ms(e){return e.length<3?Es(e):e[0]+Ls(e,ks(e))}function Ds(e){for(var t,n,r,i=-1,o=e.length;++i<o;){t=e[i];n=t[0];r=t[1]-Da;t[0]=n*Math.cos(r);t[1]=n*Math.sin(r)}return e}function Gs(e){function t(t){function l(){g.push("M",a(e(E),c),p,u(e(m.reverse()),c),"Z")}for(var d,h,f,g=[],m=[],E=[],v=-1,x=t.length,y=Ct(n),N=Ct(i),I=n===r?function(){return h}:Ct(r),A=i===o?function(){return f}:Ct(o);++v<x;)if(s.call(this,d=t[v],v)){m.push([h=+y.call(this,d,v),f=+N.call(this,d,v)]);E.push([+I.call(this,d,v),+A.call(this,d,v)])}else if(m.length){l();m=[];E=[]}m.length&&l();return g.length?g.join(""):null}var n=wr,r=wr,i=0,o=Or,s=On,a=Es,l=a.key,u=a,p="L",c=.7;t.x=function(e){if(!arguments.length)return r;n=r=e;return t};t.x0=function(e){if(!arguments.length)return n;n=e;return t};t.x1=function(e){if(!arguments.length)return r;r=e;return t};t.y=function(e){if(!arguments.length)return o;i=o=e;return t};t.y0=function(e){if(!arguments.length)return i;i=e;return t};t.y1=function(e){if(!arguments.length)return o;o=e;return t};t.defined=function(e){if(!arguments.length)return s;s=e;return t};t.interpolate=function(e){if(!arguments.length)return l;l="function"==typeof e?a=e:(a=Ru.get(e)||Es).key;u=a.reverse||a;p=a.closed?"M":"L";return t};t.tension=function(e){if(!arguments.length)return c;c=e;return t};return t}function js(e){return e.radius}function Us(e){return[e.x,e.y]}function qs(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-Da;return[n*Math.cos(r),n*Math.sin(r)]}}function Bs(){return 64}function Vs(){return"circle"}function Hs(e){var t=Math.sqrt(e/Pa);return"M0,"+t+"A"+t+","+t+" 0 1,1 0,"+-t+"A"+t+","+t+" 0 1,1 0,"+t+"Z"}function zs(e){return function(){var t,n;if((t=this[e])&&(n=t[t.active])){--t.count?delete t[t.active]:delete this[e];t.active+=.5;n.event&&n.event.interrupt.call(this,this.__data__,n.index)}}}function Ws(e,t,n){Na(e,ju);e.namespace=t;e.id=n;return e}function $s(e,t,n,r){var i=e.id,o=e.namespace;return z(e,"function"==typeof n?function(e,s,a){e[o][i].tween.set(t,r(n.call(e,e.__data__,s,a)))}:(n=r(n),function(e){e[o][i].tween.set(t,n)}))}function Ks(e){null==e&&(e="");return function(){this.textContent=e}}function Ys(e){return null==e?"__transition__":"__transition_"+e+"__"}function Qs(e,t,n,r,i){var o=e[n]||(e[n]={active:0,count:0}),s=o[r];if(!s){var a=i.time;s=o[r]={tween:new c,time:a,delay:i.delay,duration:i.duration,ease:i.ease,index:t};i=null;++o.count;ia.timer(function(i){function l(n){if(o.active>r)return p();var i=o[o.active];if(i){--o.count;delete o[o.active];i.event&&i.event.interrupt.call(e,e.__data__,i.index)}o.active=r;s.event&&s.event.start.call(e,e.__data__,t);s.tween.forEach(function(n,r){(r=r.call(e,e.__data__,t))&&g.push(r)});d=s.ease;c=s.duration;ia.timer(function(){f.c=u(n||1)?On:u;return 1},0,a)}function u(n){if(o.active!==r)return 1;for(var i=n/c,a=d(i),l=g.length;l>0;)g[--l].call(e,a);if(i>=1){s.event&&s.event.end.call(e,e.__data__,t);return p()}}function p(){--o.count?delete o[r]:delete e[n];return 1}var c,d,h=s.delay,f=ol,g=[];f.t=h+a;if(i>=h)return l(i-h);f.c=l;return void 0},0,a)}}function Xs(e,t,n){e.attr("transform",function(e){var r=t(e);return"translate("+(isFinite(r)?r:n(e))+",0)"})}function Zs(e,t,n){e.attr("transform",function(e){var r=t(e);return"translate(0,"+(isFinite(r)?r:n(e))+")"})}function Js(e){return e.toISOString()}function ea(e,t,n){function r(t){return e(t)}function i(e,n){var r=e[1]-e[0],i=r/n,o=ia.bisect(Ku,i);return o==Ku.length?[t.year,Yo(e.map(function(e){return e/31536e6}),n)[2]]:o?t[i/Ku[o-1]<Ku[o]/i?o-1:o]:[Xu,Yo(e,n)[2]]}r.invert=function(t){return ta(e.invert(t))};r.domain=function(t){if(!arguments.length)return e.domain().map(ta);e.domain(t);return r};r.nice=function(e,t){function n(n){return!isNaN(n)&&!e.range(n,ta(+n+1),t).length}var o=r.domain(),s=Uo(o),a=null==e?i(s,10):"number"==typeof e&&i(s,e);a&&(e=a[0],t=a[1]);return r.domain(Vo(o,t>1?{floor:function(t){for(;n(t=e.floor(t));)t=ta(t-1);return t},ceil:function(t){for(;n(t=e.ceil(t));)t=ta(+t+1);return t}}:e))};r.ticks=function(e,t){var n=Uo(r.domain()),o=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];o&&(e=o[0],t=o[1]);return e.range(n[0],ta(+n[1]+1),1>t?1:t)};r.tickFormat=function(){return n};r.copy=function(){return ea(e.copy(),t,n)};return $o(r,e)}function ta(e){return new Date(e)}function na(e){return JSON.parse(e.responseText)}function ra(e){var t=aa.createRange();t.selectNode(aa.body);return t.createContextualFragment(e.responseText)}var ia={version:"3.5.5"},oa=[].slice,sa=function(e){return oa.call(e)},aa=this.document;if(aa)try{sa(aa.documentElement.childNodes)[0].nodeType}catch(la){sa=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}Date.now||(Date.now=function(){return+new Date});if(aa)try{aa.createElement("DIV").style.setProperty("opacity",0,"")}catch(ua){var pa=this.Element.prototype,ca=pa.setAttribute,da=pa.setAttributeNS,ha=this.CSSStyleDeclaration.prototype,fa=ha.setProperty;pa.setAttribute=function(e,t){ca.call(this,e,t+"")};pa.setAttributeNS=function(e,t,n){da.call(this,e,t,n+"")};ha.setProperty=function(e,t,n){fa.call(this,e,t+"",n)}}ia.ascending=i;ia.descending=function(e,t){return e>t?-1:t>e?1:t>=e?0:0/0};ia.min=function(e,t){var n,r,i=-1,o=e.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=e[i])&&r>=r){n=r;break}for(;++i<o;)null!=(r=e[i])&&n>r&&(n=r)}else{for(;++i<o;)if(null!=(r=t.call(e,e[i],i))&&r>=r){n=r;break}for(;++i<o;)null!=(r=t.call(e,e[i],i))&&n>r&&(n=r)}return n};ia.max=function(e,t){var n,r,i=-1,o=e.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=e[i])&&r>=r){n=r;break}for(;++i<o;)null!=(r=e[i])&&r>n&&(n=r)}else{for(;++i<o;)if(null!=(r=t.call(e,e[i],i))&&r>=r){n=r;break}for(;++i<o;)null!=(r=t.call(e,e[i],i))&&r>n&&(n=r)}return n};ia.extent=function(e,t){var n,r,i,o=-1,s=e.length;if(1===arguments.length){for(;++o<s;)if(null!=(r=e[o])&&r>=r){n=i=r;break}for(;++o<s;)if(null!=(r=e[o])){n>r&&(n=r);r>i&&(i=r)}}else{for(;++o<s;)if(null!=(r=t.call(e,e[o],o))&&r>=r){n=i=r;break}for(;++o<s;)if(null!=(r=t.call(e,e[o],o))){n>r&&(n=r);r>i&&(i=r)}}return[n,i]};ia.sum=function(e,t){var n,r=0,i=e.length,o=-1;if(1===arguments.length)for(;++o<i;)s(n=+e[o])&&(r+=n);else for(;++o<i;)s(n=+t.call(e,e[o],o))&&(r+=n);return r};ia.mean=function(e,t){var n,r=0,i=e.length,a=-1,l=i;if(1===arguments.length)for(;++a<i;)s(n=o(e[a]))?r+=n:--l;else for(;++a<i;)s(n=o(t.call(e,e[a],a)))?r+=n:--l;return l?r/l:void 0};ia.quantile=function(e,t){var n=(e.length-1)*t+1,r=Math.floor(n),i=+e[r-1],o=n-r;return o?i+o*(e[r]-i):i};ia.median=function(e,t){var n,r=[],a=e.length,l=-1;if(1===arguments.length)for(;++l<a;)s(n=o(e[l]))&&r.push(n);else for(;++l<a;)s(n=o(t.call(e,e[l],l)))&&r.push(n);return r.length?ia.quantile(r.sort(i),.5):void 0};ia.variance=function(e,t){var n,r,i=e.length,a=0,l=0,u=-1,p=0;if(1===arguments.length){for(;++u<i;)if(s(n=o(e[u]))){r=n-a;a+=r/++p;l+=r*(n-a)}}else for(;++u<i;)if(s(n=o(t.call(e,e[u],u)))){r=n-a;a+=r/++p;l+=r*(n-a)}return p>1?l/(p-1):void 0};ia.deviation=function(){var e=ia.variance.apply(this,arguments);return e?Math.sqrt(e):e};var ga=a(i);ia.bisectLeft=ga.left;ia.bisect=ia.bisectRight=ga.right;ia.bisector=function(e){return a(1===e.length?function(t,n){return i(e(t),n)}:e)};ia.shuffle=function(e,t,n){if((o=arguments.length)<3){n=e.length;2>o&&(t=0)}for(var r,i,o=n-t;o;){i=Math.random()*o--|0;r=e[o+t],e[o+t]=e[i+t],e[i+t]=r}return e};ia.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r};ia.pairs=function(e){for(var t,n=0,r=e.length-1,i=e[0],o=new Array(0>r?0:r);r>n;)o[n]=[t=i,i=e[++n]];return o};ia.zip=function(){if(!(r=arguments.length))return[];for(var e=-1,t=ia.min(arguments,l),n=new Array(t);++e<t;)for(var r,i=-1,o=n[e]=new Array(r);++i<r;)o[i]=arguments[i][e];return n};ia.transpose=function(e){return ia.zip.apply(ia,e)};ia.keys=function(e){var t=[];for(var n in e)t.push(n);return t};ia.values=function(e){var t=[];for(var n in e)t.push(e[n]);return t};ia.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t};ia.merge=function(e){for(var t,n,r,i=e.length,o=-1,s=0;++o<i;)s+=e[o].length;n=new Array(s);for(;--i>=0;){r=e[i];t=r.length;for(;--t>=0;)n[--s]=r[t]}return n};var ma=Math.abs;ia.range=function(e,t,n){if(arguments.length<3){n=1;if(arguments.length<2){t=e;e=0}}if((t-e)/n===1/0)throw new Error("infinite range");var r,i=[],o=u(ma(n)),s=-1;e*=o,t*=o,n*=o;if(0>n)for(;(r=e+n*++s)>t;)i.push(r/o);else for(;(r=e+n*++s)<t;)i.push(r/o);return i};ia.map=function(e,t){var n=new c;if(e instanceof c)e.forEach(function(e,t){n.set(e,t)});else if(Array.isArray(e)){var r,i=-1,o=e.length;if(1===arguments.length)for(;++i<o;)n.set(i,e[i]);else for(;++i<o;)n.set(t.call(e,r=e[i],i),r)}else for(var s in e)n.set(s,e[s]);return n};var Ea="__proto__",va="\x00";p(c,{has:f,get:function(e){return this._[d(e)]},set:function(e,t){return this._[d(e)]=t},remove:g,keys:m,values:function(){var e=[];for(var t in this._)e.push(this._[t]);return e},entries:function(){var e=[];for(var t in this._)e.push({key:h(t),value:this._[t]});return e},size:E,empty:v,forEach:function(e){for(var t in this._)e.call(this,h(t),this._[t])}});ia.nest=function(){function e(t,s,a){if(a>=o.length)return r?r.call(i,s):n?s.sort(n):s;for(var l,u,p,d,h=-1,f=s.length,g=o[a++],m=new c;++h<f;)(d=m.get(l=g(u=s[h])))?d.push(u):m.set(l,[u]);if(t){u=t();p=function(n,r){u.set(n,e(t,r,a))}}else{u={};p=function(n,r){u[n]=e(t,r,a)}}m.forEach(p);return u}function t(e,n){if(n>=o.length)return e;var r=[],i=s[n++];e.forEach(function(e,i){r.push({key:e,values:t(i,n)})});return i?r.sort(function(e,t){return i(e.key,t.key)}):r}var n,r,i={},o=[],s=[];i.map=function(t,n){return e(n,t,0)};i.entries=function(n){return t(e(ia.map,n,0),0)};i.key=function(e){o.push(e);return i};i.sortKeys=function(e){s[o.length-1]=e;return i};i.sortValues=function(e){n=e;return i};i.rollup=function(e){r=e;return i};return i};ia.set=function(e){var t=new x;if(e)for(var n=0,r=e.length;r>n;++n)t.add(e[n]);return t};p(x,{has:f,add:function(e){this._[d(e+="")]=!0;return e},remove:g,values:m,size:E,empty:v,forEach:function(e){for(var t in this._)e.call(this,h(t))}});ia.behavior={};ia.rebind=function(e,t){for(var n,r=1,i=arguments.length;++r<i;)e[n=arguments[r]]=N(e,t,t[n]);return e};var xa=["webkit","ms","moz","Moz","o","O"];ia.dispatch=function(){for(var e=new T,t=-1,n=arguments.length;++t<n;)e[arguments[t]]=L(e);return e};T.prototype.on=function(e,t){var n=e.indexOf("."),r="";if(n>=0){r=e.slice(n+1);e=e.slice(0,n)}if(e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}};ia.event=null;ia.requote=function(e){return e.replace(ya,"\\$&")};var ya=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Na={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]},Ia=function(e,t){return t.querySelector(e)},Aa=function(e,t){return t.querySelectorAll(e)},Ta=function(e,t){var n=e.matches||e[I(e,"matchesSelector")];Ta=function(e,t){return n.call(e,t)};return Ta(e,t)};if("function"==typeof Sizzle){Ia=function(e,t){return Sizzle(e,t)[0]||null};Aa=Sizzle;Ta=Sizzle.matchesSelector}ia.selection=function(){return ia.select(aa.documentElement)};var La=ia.selection.prototype=[];La.select=function(e){var t,n,r,i,o=[];e=w(e);for(var s=-1,a=this.length;++s<a;){o.push(t=[]);t.parentNode=(r=this[s]).parentNode;for(var l=-1,u=r.length;++l<u;)if(i=r[l]){t.push(n=e.call(i,i.__data__,l,s));n&&"__data__"in i&&(n.__data__=i.__data__)}else t.push(null)}return R(o)};La.selectAll=function(e){var t,n,r=[];e=O(e);for(var i=-1,o=this.length;++i<o;)for(var s=this[i],a=-1,l=s.length;++a<l;)if(n=s[a]){r.push(t=sa(e.call(n,n.__data__,a,i)));t.parentNode=n}return R(r)};var Sa={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};ia.ns={prefix:Sa,qualify:function(e){var t=e.indexOf(":"),n=e;if(t>=0){n=e.slice(0,t);e=e.slice(t+1)}return Sa.hasOwnProperty(n)?{space:Sa[n],local:e}:e}};La.attr=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node();e=ia.ns.qualify(e);return e.local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(t in e)this.each(_(t,e[t]));return this}return this.each(_(e,t))};La.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=k(e)).length,i=-1;if(t=n.classList){for(;++i<r;)if(!t.contains(e[i]))return!1}else{t=n.getAttribute("class");for(;++i<r;)if(!P(e[i]).test(t))return!1}return!0}for(t in e)this.each(M(t,e[t]));return this}return this.each(M(e,t))};La.style=function(e,t,n){var i=arguments.length;if(3>i){if("string"!=typeof e){2>i&&(t="");for(n in e)this.each(G(n,e[n],t));return this}if(2>i){var o=this.node();return r(o).getComputedStyle(o,null).getPropertyValue(e)}n=""}return this.each(G(e,t,n))};La.property=function(e,t){if(arguments.length<2){if("string"==typeof e)return this.node()[e];for(t in e)this.each(j(t,e[t]));return this}return this.each(j(e,t))};La.text=function(e){return arguments.length?this.each("function"==typeof e?function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}:null==e?function(){this.textContent=""}:function(){this.textContent=e}):this.node().textContent};La.html=function(e){return arguments.length?this.each("function"==typeof e?function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}:null==e?function(){this.innerHTML=""}:function(){this.innerHTML=e}):this.node().innerHTML};La.append=function(e){e=U(e);return this.select(function(){return this.appendChild(e.apply(this,arguments))})};La.insert=function(e,t){e=U(e);t=w(t);return this.select(function(){return this.insertBefore(e.apply(this,arguments),t.apply(this,arguments)||null)})};La.remove=function(){return this.each(q)};La.data=function(e,t){function n(e,n){var r,i,o,s=e.length,p=n.length,d=Math.min(s,p),h=new Array(p),f=new Array(p),g=new Array(s);if(t){var m,E=new c,v=new Array(s);for(r=-1;++r<s;){E.has(m=t.call(i=e[r],i.__data__,r))?g[r]=i:E.set(m,i);v[r]=m}for(r=-1;++r<p;){if(i=E.get(m=t.call(n,o=n[r],r))){if(i!==!0){h[r]=i;i.__data__=o}}else f[r]=B(o);E.set(m,!0)}for(r=-1;++r<s;)E.get(v[r])!==!0&&(g[r]=e[r])}else{for(r=-1;++r<d;){i=e[r];o=n[r];if(i){i.__data__=o;h[r]=i}else f[r]=B(o)}for(;p>r;++r)f[r]=B(n[r]);for(;s>r;++r)g[r]=e[r]}f.update=h;f.parentNode=h.parentNode=g.parentNode=e.parentNode;a.push(f);l.push(h);u.push(g)}var r,i,o=-1,s=this.length;if(!arguments.length){e=new Array(s=(r=this[0]).length);for(;++o<s;)(i=r[o])&&(e[o]=i.__data__);return e}var a=W([]),l=R([]),u=R([]);if("function"==typeof e)for(;++o<s;)n(r=this[o],e.call(r,r.parentNode.__data__,o));else for(;++o<s;)n(r=this[o],e);l.enter=function(){return a};l.exit=function(){return u};return l};La.datum=function(e){return arguments.length?this.property("__data__",e):this.property("__data__")};La.filter=function(e){var t,n,r,i=[];"function"!=typeof e&&(e=V(e));for(var o=0,s=this.length;s>o;o++){i.push(t=[]);t.parentNode=(n=this[o]).parentNode;for(var a=0,l=n.length;l>a;a++)(r=n[a])&&e.call(r,r.__data__,a,o)&&t.push(r)}return R(i)};La.order=function(){for(var e=-1,t=this.length;++e<t;)for(var n,r=this[e],i=r.length-1,o=r[i];--i>=0;)if(n=r[i]){o&&o!==n.nextSibling&&o.parentNode.insertBefore(n,o);o=n}return this};La.sort=function(e){e=H.apply(this,arguments);for(var t=-1,n=this.length;++t<n;)this[t].sort(e);return this.order()};La.each=function(e){return z(this,function(t,n,r){e.call(t,t.__data__,n,r)})};La.call=function(e){var t=sa(arguments);e.apply(t[0]=this,t);return this};La.empty=function(){return!this.node()};La.node=function(){for(var e=0,t=this.length;t>e;e++)for(var n=this[e],r=0,i=n.length;i>r;r++){var o=n[r];if(o)return o}return null};La.size=function(){var e=0;z(this,function(){++e});return e};var ba=[];ia.selection.enter=W;ia.selection.enter.prototype=ba;ba.append=La.append;ba.empty=La.empty;ba.node=La.node;ba.call=La.call;ba.size=La.size;ba.select=function(e){for(var t,n,r,i,o,s=[],a=-1,l=this.length;++a<l;){r=(i=this[a]).update;s.push(t=[]);t.parentNode=i.parentNode;for(var u=-1,p=i.length;++u<p;)if(o=i[u]){t.push(r[u]=n=e.call(i.parentNode,o.__data__,u,a));n.__data__=o.__data__}else t.push(null)}return R(s)};ba.insert=function(e,t){arguments.length<2&&(t=$(this));return La.insert.call(this,e,t)};ia.select=function(e){var n;if("string"==typeof e){n=[Ia(e,aa)];n.parentNode=aa.documentElement}else{n=[e];n.parentNode=t(e)}return R([n])};ia.selectAll=function(e){var t;if("string"==typeof e){t=sa(Aa(e,aa));t.parentNode=aa.documentElement}else{t=e;t.parentNode=null}return R([t])};La.on=function(e,t,n){var r=arguments.length;if(3>r){if("string"!=typeof e){2>r&&(t=!1);for(n in e)this.each(K(n,e[n],t));return this}if(2>r)return(r=this.node()["__on"+e])&&r._;n=!1}return this.each(K(e,t,n))};var Ca=ia.map({mouseenter:"mouseover",mouseleave:"mouseout"});aa&&Ca.forEach(function(e){"on"+e in aa&&Ca.remove(e)});var Ra,wa=0;ia.mouse=function(e){return Z(e,b())};var Oa=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;ia.touch=function(e,t,n){arguments.length<3&&(n=t,t=b().changedTouches);if(t)for(var r,i=0,o=t.length;o>i;++i)if((r=t[i]).identifier===n)return Z(e,r)};ia.behavior.drag=function(){function e(){this.on("mousedown.drag",o).on("touchstart.drag",s)}function t(e,t,r,o,s){return function(){function a(){var e,n,r=t(d,g);if(r){e=r[0]-x[0];n=r[1]-x[1];f|=e|n;x=r;h({type:"drag",x:r[0]+u[0],y:r[1]+u[1],dx:e,dy:n})}}function l(){if(t(d,g)){E.on(o+m,null).on(s+m,null);v(f&&ia.event.target===c);h({type:"dragend"})}}var u,p=this,c=ia.event.target,d=p.parentNode,h=n.of(p,arguments),f=0,g=e(),m=".drag"+(null==g?"":"-"+g),E=ia.select(r(c)).on(o+m,a).on(s+m,l),v=X(c),x=t(d,g);if(i){u=i.apply(p,arguments);u=[u.x-x[0],u.y-x[1]]}else u=[0,0];h({type:"dragstart"})}}var n=C(e,"drag","dragstart","dragend"),i=null,o=t(A,ia.mouse,r,"mousemove","mouseup"),s=t(J,ia.touch,y,"touchmove","touchend");e.origin=function(t){if(!arguments.length)return i;i=t;return e};return ia.rebind(e,n,"on")};ia.touches=function(e,t){arguments.length<2&&(t=b().touches);return t?sa(t).map(function(t){var n=Z(e,t);n.identifier=t.identifier;return n}):[]};var _a=1e-6,Fa=_a*_a,Pa=Math.PI,ka=2*Pa,Ma=ka-_a,Da=Pa/2,Ga=Pa/180,ja=180/Pa,Ua=Math.SQRT2,qa=2,Ba=4;ia.interpolateZoom=function(e,t){function n(e){var t=e*v;if(E){var n=ot(g),s=o/(qa*d)*(n*st(Ua*t+g)-it(g));return[r+s*u,i+s*p,o*n/ot(Ua*t+g)]}return[r+e*u,i+e*p,o*Math.exp(Ua*t)]}var r=e[0],i=e[1],o=e[2],s=t[0],a=t[1],l=t[2],u=s-r,p=a-i,c=u*u+p*p,d=Math.sqrt(c),h=(l*l-o*o+Ba*c)/(2*o*qa*d),f=(l*l-o*o-Ba*c)/(2*l*qa*d),g=Math.log(Math.sqrt(h*h+1)-h),m=Math.log(Math.sqrt(f*f+1)-f),E=m-g,v=(E||Math.log(l/o))/Ua;n.duration=1e3*v;return n};ia.behavior.zoom=function(){function e(e){e.on(O,c).on(Ha+".zoom",h).on("dblclick.zoom",f).on(P,d)}function t(e){return[(e[0]-T.x)/T.k,(e[1]-T.y)/T.k]}function n(e){return[e[0]*T.k+T.x,e[1]*T.k+T.y]}function i(e){T.k=Math.max(b[0],Math.min(b[1],e))}function o(e,t){t=n(t);T.x+=e[0]-t[0];T.y+=e[1]-t[1]}function s(t,n,r,s){t.__chart__={x:T.x,y:T.y,k:T.k};i(Math.pow(2,s));o(m=n,r);t=ia.select(t);R>0&&(t=t.transition().duration(R));t.call(e.event)}function a(){N&&N.domain(y.range().map(function(e){return(e-T.x)/T.k}).map(y.invert));A&&A.domain(I.range().map(function(e){return(e-T.y)/T.k}).map(I.invert))}function l(e){w++||e({type:"zoomstart"})}function u(e){a();e({type:"zoom",scale:T.k,translate:[T.x,T.y]})}function p(e){--w||e({type:"zoomend"});m=null}function c(){function e(){c=1;o(ia.mouse(i),h);u(a)}function n(){d.on(_,null).on(F,null);f(c&&ia.event.target===s);p(a)}var i=this,s=ia.event.target,a=k.of(i,arguments),c=0,d=ia.select(r(i)).on(_,e).on(F,n),h=t(ia.mouse(i)),f=X(i);Gu.call(i);l(a)}function d(){function e(){var e=ia.touches(f);h=T.k;e.forEach(function(e){e.identifier in m&&(m[e.identifier]=t(e))});return e}function n(){var t=ia.event.target;ia.select(t).on(y,r).on(N,a);I.push(t);for(var n=ia.event.changedTouches,i=0,o=n.length;o>i;++i)m[n[i].identifier]=null;var l=e(),u=Date.now();if(1===l.length){if(500>u-x){var p=l[0];s(f,p,m[p.identifier],Math.floor(Math.log(T.k)/Math.LN2)+1);S()}x=u}else if(l.length>1){var p=l[0],c=l[1],d=p[0]-c[0],h=p[1]-c[1];E=d*d+h*h}}function r(){var e,t,n,r,s=ia.touches(f);Gu.call(f);for(var a=0,l=s.length;l>a;++a,r=null){n=s[a];if(r=m[n.identifier]){if(t)break;e=n,t=r}}if(r){var p=(p=n[0]-e[0])*p+(p=n[1]-e[1])*p,c=E&&Math.sqrt(p/E);e=[(e[0]+n[0])/2,(e[1]+n[1])/2];t=[(t[0]+r[0])/2,(t[1]+r[1])/2];i(c*h)}x=null;o(e,t);u(g)}function a(){if(ia.event.touches.length){for(var t=ia.event.changedTouches,n=0,r=t.length;r>n;++n)delete m[t[n].identifier];for(var i in m)return void e()}ia.selectAll(I).on(v,null);A.on(O,c).on(P,d);L();p(g)}var h,f=this,g=k.of(f,arguments),m={},E=0,v=".zoom-"+ia.event.changedTouches[0].identifier,y="touchmove"+v,N="touchend"+v,I=[],A=ia.select(f),L=X(f);n();l(g);A.on(O,null).on(P,n)}function h(){var e=k.of(this,arguments);v?clearTimeout(v):(g=t(m=E||ia.mouse(this)),Gu.call(this),l(e));v=setTimeout(function(){v=null;p(e)},50);S();i(Math.pow(2,.002*Va())*T.k);o(m,g);u(e)}function f(){var e=ia.mouse(this),n=Math.log(T.k)/Math.LN2;s(this,e,t(e),ia.event.shiftKey?Math.ceil(n)-1:Math.floor(n)+1)}var g,m,E,v,x,y,N,I,A,T={x:0,y:0,k:1},L=[960,500],b=za,R=250,w=0,O="mousedown.zoom",_="mousemove.zoom",F="mouseup.zoom",P="touchstart.zoom",k=C(e,"zoomstart","zoom","zoomend");Ha||(Ha="onwheel"in aa?(Va=function(){return-ia.event.deltaY*(ia.event.deltaMode?120:1)},"wheel"):"onmousewheel"in aa?(Va=function(){return ia.event.wheelDelta},"mousewheel"):(Va=function(){return-ia.event.detail},"MozMousePixelScroll"));e.event=function(e){e.each(function(){var e=k.of(this,arguments),t=T;if(Mu)ia.select(this).transition().each("start.zoom",function(){T=this.__chart__||{x:0,y:0,k:1};l(e)}).tween("zoom:zoom",function(){var n=L[0],r=L[1],i=m?m[0]:n/2,o=m?m[1]:r/2,s=ia.interpolateZoom([(i-T.x)/T.k,(o-T.y)/T.k,n/T.k],[(i-t.x)/t.k,(o-t.y)/t.k,n/t.k]);return function(t){var r=s(t),a=n/r[2];this.__chart__=T={x:i-r[0]*a,y:o-r[1]*a,k:a};u(e)}}).each("interrupt.zoom",function(){p(e)}).each("end.zoom",function(){p(e)});else{this.__chart__=T;l(e);u(e);p(e)}})};e.translate=function(t){if(!arguments.length)return[T.x,T.y];T={x:+t[0],y:+t[1],k:T.k};a();return e};e.scale=function(t){if(!arguments.length)return T.k;T={x:T.x,y:T.y,k:+t};a();return e};e.scaleExtent=function(t){if(!arguments.length)return b;b=null==t?za:[+t[0],+t[1]];return e};e.center=function(t){if(!arguments.length)return E;E=t&&[+t[0],+t[1]];return e};e.size=function(t){if(!arguments.length)return L;L=t&&[+t[0],+t[1]];return e};e.duration=function(t){if(!arguments.length)return R;R=+t;return e};e.x=function(t){if(!arguments.length)return N;N=t;y=t.copy();T={x:0,y:0,k:1};return e};e.y=function(t){if(!arguments.length)return A;A=t;I=t.copy();T={x:0,y:0,k:1};return e};return ia.rebind(e,k,"on")};var Va,Ha,za=[0,1/0];ia.color=lt;lt.prototype.toString=function(){return this.rgb()+""};ia.hsl=ut;var Wa=ut.prototype=new lt;Wa.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);return new ut(this.h,this.s,this.l/e)};Wa.darker=function(e){e=Math.pow(.7,arguments.length?e:1);return new ut(this.h,this.s,e*this.l)};Wa.rgb=function(){return pt(this.h,this.s,this.l)};ia.hcl=ct;var $a=ct.prototype=new lt;$a.brighter=function(e){return new ct(this.h,this.c,Math.min(100,this.l+Ka*(arguments.length?e:1)))};$a.darker=function(e){return new ct(this.h,this.c,Math.max(0,this.l-Ka*(arguments.length?e:1)))};$a.rgb=function(){return dt(this.h,this.c,this.l).rgb()};ia.lab=ht;var Ka=18,Ya=.95047,Qa=1,Xa=1.08883,Za=ht.prototype=new lt;Za.brighter=function(e){return new ht(Math.min(100,this.l+Ka*(arguments.length?e:1)),this.a,this.b)};Za.darker=function(e){return new ht(Math.max(0,this.l-Ka*(arguments.length?e:1)),this.a,this.b)};Za.rgb=function(){return ft(this.l,this.a,this.b)};ia.rgb=xt;var Ja=xt.prototype=new lt;Ja.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,i=30;if(!t&&!n&&!r)return new xt(i,i,i);t&&i>t&&(t=i);n&&i>n&&(n=i);r&&i>r&&(r=i);return new xt(Math.min(255,t/e),Math.min(255,n/e),Math.min(255,r/e))};Ja.darker=function(e){e=Math.pow(.7,arguments.length?e:1);return new xt(e*this.r,e*this.g,e*this.b)};Ja.hsl=function(){return Tt(this.r,this.g,this.b)};Ja.toString=function(){return"#"+It(this.r)+It(this.g)+It(this.b)};var el=ia.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});el.forEach(function(e,t){el.set(e,yt(t))});ia.functor=Ct;ia.xhr=Rt(y);ia.dsv=function(e,t){function n(e,n,o){arguments.length<3&&(o=n,n=null);var s=wt(e,t,null==n?r:i(n),o);s.row=function(e){return arguments.length?s.response(null==(n=e)?r:i(e)):n};return s}function r(e){return n.parse(e.responseText)}function i(e){return function(t){return n.parse(t.responseText,e)}}function o(t){return t.map(s).join(e)}function s(e){return a.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}var a=new RegExp('["'+e+"\n]"),l=e.charCodeAt(0);
n.parse=function(e,t){var r;return n.parseRows(e,function(e,n){if(r)return r(e,n-1);var i=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");r=t?function(e,n){return t(i(e),n)}:i})};n.parseRows=function(e,t){function n(){if(p>=u)return s;if(i)return i=!1,o;var t=p;if(34===e.charCodeAt(t)){for(var n=t;n++<u;)if(34===e.charCodeAt(n)){if(34!==e.charCodeAt(n+1))break;++n}p=n+2;var r=e.charCodeAt(n+1);if(13===r){i=!0;10===e.charCodeAt(n+2)&&++p}else 10===r&&(i=!0);return e.slice(t+1,n).replace(/""/g,'"')}for(;u>p;){var r=e.charCodeAt(p++),a=1;if(10===r)i=!0;else if(13===r){i=!0;10===e.charCodeAt(p)&&(++p,++a)}else if(r!==l)continue;return e.slice(t,p-a)}return e.slice(t)}for(var r,i,o={},s={},a=[],u=e.length,p=0,c=0;(r=n())!==s;){for(var d=[];r!==o&&r!==s;){d.push(r);r=n()}t&&null==(d=t(d,c++))||a.push(d)}return a};n.format=function(t){if(Array.isArray(t[0]))return n.formatRows(t);var r=new x,i=[];t.forEach(function(e){for(var t in e)r.has(t)||i.push(r.add(t))});return[i.map(s).join(e)].concat(t.map(function(t){return i.map(function(e){return s(t[e])}).join(e)})).join("\n")};n.formatRows=function(e){return e.map(o).join("\n")};return n};ia.csv=ia.dsv(",","text/csv");ia.tsv=ia.dsv(" ","text/tab-separated-values");var tl,nl,rl,il,ol,sl=this[I(this,"requestAnimationFrame")]||function(e){setTimeout(e,17)};ia.timer=function(e,t,n){var r=arguments.length;2>r&&(t=0);3>r&&(n=Date.now());var i=n+t,o={c:e,t:i,f:!1,n:null};nl?nl.n=o:tl=o;nl=o;if(!rl){il=clearTimeout(il);rl=1;sl(Ft)}};ia.timer.flush=function(){Pt();kt()};ia.round=function(e,t){return t?Math.round(e*(t=Math.pow(10,t)))/t:Math.round(e)};var al=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"].map(Dt);ia.formatPrefix=function(e,t){var n=0;if(e){0>e&&(e*=-1);t&&(e=ia.round(e,Mt(e,t)));n=1+Math.floor(1e-12+Math.log(e)/Math.LN10);n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))}return al[8+n/3]};var ll=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,ul=ia.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,t){return(e=ia.round(e,Mt(e,t))).toFixed(Math.max(0,Math.min(20,Mt(e*(1+1e-15),t))))}}),pl=ia.time={},cl=Date;Ut.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){dl.setUTCDate.apply(this._,arguments)},setDay:function(){dl.setUTCDay.apply(this._,arguments)},setFullYear:function(){dl.setUTCFullYear.apply(this._,arguments)},setHours:function(){dl.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){dl.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){dl.setUTCMinutes.apply(this._,arguments)},setMonth:function(){dl.setUTCMonth.apply(this._,arguments)},setSeconds:function(){dl.setUTCSeconds.apply(this._,arguments)},setTime:function(){dl.setTime.apply(this._,arguments)}};var dl=Date.prototype;pl.year=qt(function(e){e=pl.day(e);e.setMonth(0,1);return e},function(e,t){e.setFullYear(e.getFullYear()+t)},function(e){return e.getFullYear()});pl.years=pl.year.range;pl.years.utc=pl.year.utc.range;pl.day=qt(function(e){var t=new cl(2e3,0);t.setFullYear(e.getFullYear(),e.getMonth(),e.getDate());return t},function(e,t){e.setDate(e.getDate()+t)},function(e){return e.getDate()-1});pl.days=pl.day.range;pl.days.utc=pl.day.utc.range;pl.dayOfYear=function(e){var t=pl.year(e);return Math.floor((e-t-6e4*(e.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)};["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(e,t){t=7-t;var n=pl[e]=qt(function(e){(e=pl.day(e)).setDate(e.getDate()-(e.getDay()+t)%7);return e},function(e,t){e.setDate(e.getDate()+7*Math.floor(t))},function(e){var n=pl.year(e).getDay();return Math.floor((pl.dayOfYear(e)+(n+t)%7)/7)-(n!==t)});pl[e+"s"]=n.range;pl[e+"s"].utc=n.utc.range;pl[e+"OfYear"]=function(e){var n=pl.year(e).getDay();return Math.floor((pl.dayOfYear(e)+(n+t)%7)/7)}});pl.week=pl.sunday;pl.weeks=pl.sunday.range;pl.weeks.utc=pl.sunday.utc.range;pl.weekOfYear=pl.sundayOfYear;var hl={"-":"",_:" ",0:"0"},fl=/^\s*\d+/,gl=/^%/;ia.locale=function(e){return{numberFormat:Gt(e),timeFormat:Vt(e)}};var ml=ia.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});ia.format=ml.numberFormat;ia.geo={};cn.prototype={s:0,t:0,add:function(e){dn(e,this.t,El);dn(El.s,this.s,this);this.s?this.t+=El.t:this.s=El.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var El=new cn;ia.geo.stream=function(e,t){e&&vl.hasOwnProperty(e.type)?vl[e.type](e,t):hn(e,t)};var vl={Feature:function(e,t){hn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,i=n.length;++r<i;)hn(n[r].geometry,t)}},xl={Sphere:function(e,t){t.sphere()},Point:function(e,t){e=e.coordinates;t.point(e[0],e[1],e[2])},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)e=n[r],t.point(e[0],e[1],e[2])},LineString:function(e,t){fn(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)fn(n[r],t,0)},Polygon:function(e,t){gn(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)gn(n[r],t)},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,i=n.length;++r<i;)hn(n[r],t)}};ia.geo.area=function(e){yl=0;ia.geo.stream(e,Il);return yl};var yl,Nl=new cn,Il={sphere:function(){yl+=4*Pa},point:A,lineStart:A,lineEnd:A,polygonStart:function(){Nl.reset();Il.lineStart=mn},polygonEnd:function(){var e=2*Nl;yl+=0>e?4*Pa+e:e;Il.lineStart=Il.lineEnd=Il.point=A}};ia.geo.bounds=function(){function e(e,t){x.push(y=[p=e,d=e]);c>t&&(c=t);t>h&&(h=t)}function t(t,n){var r=En([t*Ga,n*Ga]);if(E){var i=xn(E,r),o=[i[1],-i[0],0],s=xn(o,i);In(s);s=An(s);var l=t-f,u=l>0?1:-1,g=s[0]*ja*u,m=ma(l)>180;if(m^(g>u*f&&u*t>g)){var v=s[1]*ja;v>h&&(h=v)}else if(g=(g+360)%360-180,m^(g>u*f&&u*t>g)){var v=-s[1]*ja;c>v&&(c=v)}else{c>n&&(c=n);n>h&&(h=n)}if(m)f>t?a(p,t)>a(p,d)&&(d=t):a(t,d)>a(p,d)&&(p=t);else if(d>=p){p>t&&(p=t);t>d&&(d=t)}else t>f?a(p,t)>a(p,d)&&(d=t):a(t,d)>a(p,d)&&(p=t)}else e(t,n);E=r,f=t}function n(){N.point=t}function r(){y[0]=p,y[1]=d;N.point=e;E=null}function i(e,n){if(E){var r=e-f;v+=ma(r)>180?r+(r>0?360:-360):r}else g=e,m=n;Il.point(e,n);t(e,n)}function o(){Il.lineStart()}function s(){i(g,m);Il.lineEnd();ma(v)>_a&&(p=-(d=180));y[0]=p,y[1]=d;E=null}function a(e,t){return(t-=e)<0?t+360:t}function l(e,t){return e[0]-t[0]}function u(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e<t[0]||t[1]<e}var p,c,d,h,f,g,m,E,v,x,y,N={point:e,lineStart:n,lineEnd:r,polygonStart:function(){N.point=i;N.lineStart=o;N.lineEnd=s;v=0;Il.polygonStart()},polygonEnd:function(){Il.polygonEnd();N.point=e;N.lineStart=n;N.lineEnd=r;0>Nl?(p=-(d=180),c=-(h=90)):v>_a?h=90:-_a>v&&(c=-90);y[0]=p,y[1]=d}};return function(e){h=d=-(p=c=1/0);x=[];ia.geo.stream(e,N);var t=x.length;if(t){x.sort(l);for(var n,r=1,i=x[0],o=[i];t>r;++r){n=x[r];if(u(n[0],i)||u(n[1],i)){a(i[0],n[1])>a(i[0],i[1])&&(i[1]=n[1]);a(n[0],i[1])>a(i[0],i[1])&&(i[0]=n[0])}else o.push(i=n)}for(var s,n,f=-1/0,t=o.length-1,r=0,i=o[t];t>=r;i=n,++r){n=o[r];(s=a(i[1],n[0]))>f&&(f=s,p=n[0],d=i[1])}}x=y=null;return 1/0===p||1/0===c?[[0/0,0/0],[0/0,0/0]]:[[p,c],[d,h]]}}();ia.geo.centroid=function(e){Al=Tl=Ll=Sl=bl=Cl=Rl=wl=Ol=_l=Fl=0;ia.geo.stream(e,Pl);var t=Ol,n=_l,r=Fl,i=t*t+n*n+r*r;if(Fa>i){t=Cl,n=Rl,r=wl;_a>Tl&&(t=Ll,n=Sl,r=bl);i=t*t+n*n+r*r;if(Fa>i)return[0/0,0/0]}return[Math.atan2(n,t)*ja,rt(r/Math.sqrt(i))*ja]};var Al,Tl,Ll,Sl,bl,Cl,Rl,wl,Ol,_l,Fl,Pl={sphere:A,point:Ln,lineStart:bn,lineEnd:Cn,polygonStart:function(){Pl.lineStart=Rn},polygonEnd:function(){Pl.lineStart=bn}},kl=kn(On,jn,qn,[-Pa,-Pa/2]),Ml=1e9;ia.geo.clipExtent=function(){var e,t,n,r,i,o,s={stream:function(e){i&&(i.valid=!1);i=o(e);i.valid=!0;return i},extent:function(a){if(!arguments.length)return[[e,t],[n,r]];o=zn(e=+a[0][0],t=+a[0][1],n=+a[1][0],r=+a[1][1]);i&&(i.valid=!1,i=null);return s}};return s.extent([[0,0],[960,500]])};(ia.geo.conicEqualArea=function(){return Wn($n)}).raw=$n;ia.geo.albers=function(){return ia.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)};ia.geo.albersUsa=function(){function e(e){var o=e[0],s=e[1];t=null;(n(o,s),t)||(r(o,s),t)||i(o,s);return t}var t,n,r,i,o=ia.geo.albers(),s=ia.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=ia.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(e,n){t=[e,n]}};e.invert=function(e){var t=o.scale(),n=o.translate(),r=(e[0]-n[0])/t,i=(e[1]-n[1])/t;return(i>=.12&&.234>i&&r>=-.425&&-.214>r?s:i>=.166&&.234>i&&r>=-.214&&-.115>r?a:o).invert(e)};e.stream=function(e){var t=o.stream(e),n=s.stream(e),r=a.stream(e);return{point:function(e,i){t.point(e,i);n.point(e,i);r.point(e,i)},sphere:function(){t.sphere();n.sphere();r.sphere()},lineStart:function(){t.lineStart();n.lineStart();r.lineStart()},lineEnd:function(){t.lineEnd();n.lineEnd();r.lineEnd()},polygonStart:function(){t.polygonStart();n.polygonStart();r.polygonStart()},polygonEnd:function(){t.polygonEnd();n.polygonEnd();r.polygonEnd()}}};e.precision=function(t){if(!arguments.length)return o.precision();o.precision(t);s.precision(t);a.precision(t);return e};e.scale=function(t){if(!arguments.length)return o.scale();o.scale(t);s.scale(.35*t);a.scale(t);return e.translate(o.translate())};e.translate=function(t){if(!arguments.length)return o.translate();var u=o.scale(),p=+t[0],c=+t[1];n=o.translate(t).clipExtent([[p-.455*u,c-.238*u],[p+.455*u,c+.238*u]]).stream(l).point;r=s.translate([p-.307*u,c+.201*u]).clipExtent([[p-.425*u+_a,c+.12*u+_a],[p-.214*u-_a,c+.234*u-_a]]).stream(l).point;i=a.translate([p-.205*u,c+.212*u]).clipExtent([[p-.214*u+_a,c+.166*u+_a],[p-.115*u-_a,c+.234*u-_a]]).stream(l).point;return e};return e.scale(1070)};var Dl,Gl,jl,Ul,ql,Bl,Vl={point:A,lineStart:A,lineEnd:A,polygonStart:function(){Gl=0;Vl.lineStart=Kn},polygonEnd:function(){Vl.lineStart=Vl.lineEnd=Vl.point=A;Dl+=ma(Gl/2)}},Hl={point:Yn,lineStart:A,lineEnd:A,polygonStart:A,polygonEnd:A},zl={point:Zn,lineStart:Jn,lineEnd:er,polygonStart:function(){zl.lineStart=tr},polygonEnd:function(){zl.point=Zn;zl.lineStart=Jn;zl.lineEnd=er}};ia.geo.path=function(){function e(e){if(e){"function"==typeof a&&o.pointRadius(+a.apply(this,arguments));s&&s.valid||(s=i(o));ia.geo.stream(e,s)}return o.result()}function t(){s=null;return e}var n,r,i,o,s,a=4.5;e.area=function(e){Dl=0;ia.geo.stream(e,i(Vl));return Dl};e.centroid=function(e){Ll=Sl=bl=Cl=Rl=wl=Ol=_l=Fl=0;ia.geo.stream(e,i(zl));return Fl?[Ol/Fl,_l/Fl]:wl?[Cl/wl,Rl/wl]:bl?[Ll/bl,Sl/bl]:[0/0,0/0]};e.bounds=function(e){ql=Bl=-(jl=Ul=1/0);ia.geo.stream(e,i(Hl));return[[jl,Ul],[ql,Bl]]};e.projection=function(e){if(!arguments.length)return n;i=(n=e)?e.stream||ir(e):y;return t()};e.context=function(e){if(!arguments.length)return r;o=null==(r=e)?new Qn:new nr(e);"function"!=typeof a&&o.pointRadius(a);return t()};e.pointRadius=function(t){if(!arguments.length)return a;a="function"==typeof t?t:(o.pointRadius(+t),+t);return e};return e.projection(ia.geo.albersUsa()).context(null)};ia.geo.transform=function(e){return{stream:function(t){var n=new or(t);for(var r in e)n[r]=e[r];return n}}};or.prototype={point:function(e,t){this.stream.point(e,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};ia.geo.projection=ar;ia.geo.projectionMutator=lr;(ia.geo.equirectangular=function(){return ar(pr)}).raw=pr.invert=pr;ia.geo.rotation=function(e){function t(t){t=e(t[0]*Ga,t[1]*Ga);return t[0]*=ja,t[1]*=ja,t}e=dr(e[0]%360*Ga,e[1]*Ga,e.length>2?e[2]*Ga:0);t.invert=function(t){t=e.invert(t[0]*Ga,t[1]*Ga);return t[0]*=ja,t[1]*=ja,t};return t};cr.invert=pr;ia.geo.circle=function(){function e(){var e="function"==typeof r?r.apply(this,arguments):r,t=dr(-e[0]*Ga,-e[1]*Ga,0).invert,i=[];n(null,null,1,{point:function(e,n){i.push(e=t(e,n));e[0]*=ja,e[1]*=ja}});return{type:"Polygon",coordinates:[i]}}var t,n,r=[0,0],i=6;e.origin=function(t){if(!arguments.length)return r;r=t;return e};e.angle=function(r){if(!arguments.length)return t;n=mr((t=+r)*Ga,i*Ga);return e};e.precision=function(r){if(!arguments.length)return i;n=mr(t*Ga,(i=+r)*Ga);return e};return e.angle(90)};ia.geo.distance=function(e,t){var n,r=(t[0]-e[0])*Ga,i=e[1]*Ga,o=t[1]*Ga,s=Math.sin(r),a=Math.cos(r),l=Math.sin(i),u=Math.cos(i),p=Math.sin(o),c=Math.cos(o);return Math.atan2(Math.sqrt((n=c*s)*n+(n=u*p-l*c*a)*n),l*p+u*c*a)};ia.geo.graticule=function(){function e(){return{type:"MultiLineString",coordinates:t()}}function t(){return ia.range(Math.ceil(o/m)*m,i,m).map(d).concat(ia.range(Math.ceil(u/E)*E,l,E).map(h)).concat(ia.range(Math.ceil(r/f)*f,n,f).filter(function(e){return ma(e%m)>_a}).map(p)).concat(ia.range(Math.ceil(a/g)*g,s,g).filter(function(e){return ma(e%E)>_a}).map(c))}var n,r,i,o,s,a,l,u,p,c,d,h,f=10,g=f,m=90,E=360,v=2.5;e.lines=function(){return t().map(function(e){return{type:"LineString",coordinates:e}})};e.outline=function(){return{type:"Polygon",coordinates:[d(o).concat(h(l).slice(1),d(i).reverse().slice(1),h(u).reverse().slice(1))]}};e.extent=function(t){return arguments.length?e.majorExtent(t).minorExtent(t):e.minorExtent()};e.majorExtent=function(t){if(!arguments.length)return[[o,u],[i,l]];o=+t[0][0],i=+t[1][0];u=+t[0][1],l=+t[1][1];o>i&&(t=o,o=i,i=t);u>l&&(t=u,u=l,l=t);return e.precision(v)};e.minorExtent=function(t){if(!arguments.length)return[[r,a],[n,s]];r=+t[0][0],n=+t[1][0];a=+t[0][1],s=+t[1][1];r>n&&(t=r,r=n,n=t);a>s&&(t=a,a=s,s=t);return e.precision(v)};e.step=function(t){return arguments.length?e.majorStep(t).minorStep(t):e.minorStep()};e.majorStep=function(t){if(!arguments.length)return[m,E];m=+t[0],E=+t[1];return e};e.minorStep=function(t){if(!arguments.length)return[f,g];f=+t[0],g=+t[1];return e};e.precision=function(t){if(!arguments.length)return v;v=+t;p=vr(a,s,90);c=xr(r,n,v);d=vr(u,l,90);h=xr(o,i,v);return e};return e.majorExtent([[-180,-90+_a],[180,90-_a]]).minorExtent([[-180,-80-_a],[180,80+_a]])};ia.geo.greatArc=function(){function e(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),n||i.apply(this,arguments)]}}var t,n,r=yr,i=Nr;e.distance=function(){return ia.geo.distance(t||r.apply(this,arguments),n||i.apply(this,arguments))};e.source=function(n){if(!arguments.length)return r;r=n,t="function"==typeof n?null:n;return e};e.target=function(t){if(!arguments.length)return i;i=t,n="function"==typeof t?null:t;return e};e.precision=function(){return arguments.length?e:0};return e};ia.geo.interpolate=function(e,t){return Ir(e[0]*Ga,e[1]*Ga,t[0]*Ga,t[1]*Ga)};ia.geo.length=function(e){Wl=0;ia.geo.stream(e,$l);return Wl};var Wl,$l={sphere:A,point:A,lineStart:Ar,lineEnd:A,polygonStart:A,polygonEnd:A},Kl=Tr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(ia.geo.azimuthalEqualArea=function(){return ar(Kl)}).raw=Kl;var Yl=Tr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},y);(ia.geo.azimuthalEquidistant=function(){return ar(Yl)}).raw=Yl;(ia.geo.conicConformal=function(){return Wn(Lr)}).raw=Lr;(ia.geo.conicEquidistant=function(){return Wn(Sr)}).raw=Sr;var Ql=Tr(function(e){return 1/e},Math.atan);(ia.geo.gnomonic=function(){return ar(Ql)}).raw=Ql;br.invert=function(e,t){return[e,2*Math.atan(Math.exp(t))-Da]};(ia.geo.mercator=function(){return Cr(br)}).raw=br;var Xl=Tr(function(){return 1},Math.asin);(ia.geo.orthographic=function(){return ar(Xl)}).raw=Xl;var Zl=Tr(function(e){return 1/(1+e)},function(e){return 2*Math.atan(e)});(ia.geo.stereographic=function(){return ar(Zl)}).raw=Zl;Rr.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Da]};(ia.geo.transverseMercator=function(){var e=Cr(Rr),t=e.center,n=e.rotate;e.center=function(e){return e?t([-e[1],e[0]]):(e=t(),[e[1],-e[0]])};e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):(e=n(),[e[0],e[1],e[2]-90])};return n([0,0,90])}).raw=Rr;ia.geom={};ia.geom.hull=function(e){function t(e){if(e.length<3)return[];var t,i=Ct(n),o=Ct(r),s=e.length,a=[],l=[];for(t=0;s>t;t++)a.push([+i.call(this,e[t],t),+o.call(this,e[t],t),t]);a.sort(Fr);for(t=0;s>t;t++)l.push([a[t][0],-a[t][1]]);var u=_r(a),p=_r(l),c=p[0]===u[0],d=p[p.length-1]===u[u.length-1],h=[];for(t=u.length-1;t>=0;--t)h.push(e[a[u[t]][2]]);for(t=+c;t<p.length-d;++t)h.push(e[a[p[t]][2]]);return h}var n=wr,r=Or;if(arguments.length)return t(e);t.x=function(e){return arguments.length?(n=e,t):n};t.y=function(e){return arguments.length?(r=e,t):r};return t};ia.geom.polygon=function(e){Na(e,Jl);return e};var Jl=ia.geom.polygon.prototype=[];Jl.area=function(){for(var e,t=-1,n=this.length,r=this[n-1],i=0;++t<n;){e=r;r=this[t];i+=e[1]*r[0]-e[0]*r[1]}return.5*i};Jl.centroid=function(e){var t,n,r=-1,i=this.length,o=0,s=0,a=this[i-1];arguments.length||(e=-1/(6*this.area()));for(;++r<i;){t=a;a=this[r];n=t[0]*a[1]-a[0]*t[1];o+=(t[0]+a[0])*n;s+=(t[1]+a[1])*n}return[o*e,s*e]};Jl.clip=function(e){for(var t,n,r,i,o,s,a=Mr(e),l=-1,u=this.length-Mr(this),p=this[u-1];++l<u;){t=e.slice();e.length=0;i=this[l];o=t[(r=t.length-a)-1];n=-1;for(;++n<r;){s=t[n];if(Pr(s,p,i)){Pr(o,p,i)||e.push(kr(o,s,p,i));e.push(s)}else Pr(o,p,i)&&e.push(kr(o,s,p,i));o=s}a&&e.push(e[0]);p=i}return e};var eu,tu,nu,ru,iu,ou=[],su=[];Hr.prototype.prepare=function(){for(var e,t=this.edges,n=t.length;n--;){e=t[n].edge;e.b&&e.a||t.splice(n,1)}t.sort(Wr);return t.length};ni.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}};ri.prototype={insert:function(e,t){var n,r,i;if(e){t.P=e;t.N=e.N;e.N&&(e.N.P=t);e.N=t;if(e.R){e=e.R;for(;e.L;)e=e.L;e.L=t}else e.R=t;n=e}else if(this._){e=ai(this._);t.P=null;t.N=e;e.P=e.L=t;n=e}else{t.P=t.N=null;this._=t;n=null}t.L=t.R=null;t.U=n;t.C=!0;e=t;for(;n&&n.C;){r=n.U;if(n===r.L){i=r.R;if(i&&i.C){n.C=i.C=!1;r.C=!0;e=r}else{if(e===n.R){oi(this,n);e=n;n=e.U}n.C=!1;r.C=!0;si(this,r)}}else{i=r.L;if(i&&i.C){n.C=i.C=!1;r.C=!0;e=r}else{if(e===n.L){si(this,n);e=n;n=e.U}n.C=!1;r.C=!0;oi(this,r)}}n=e.U}this._.C=!1},remove:function(e){e.N&&(e.N.P=e.P);e.P&&(e.P.N=e.N);e.N=e.P=null;var t,n,r,i=e.U,o=e.L,s=e.R;n=o?s?ai(s):o:s;i?i.L===e?i.L=n:i.R=n:this._=n;if(o&&s){r=n.C;n.C=e.C;n.L=o;o.U=n;if(n!==s){i=n.U;n.U=e.U;e=n.R;i.L=e;n.R=s;s.U=n}else{n.U=i;i=n;e=n.R}}else{r=e.C;e=n}e&&(e.U=i);if(!r)if(e&&e.C)e.C=!1;else{do{if(e===this._)break;if(e===i.L){t=i.R;if(t.C){t.C=!1;i.C=!0;oi(this,i);t=i.R}if(t.L&&t.L.C||t.R&&t.R.C){if(!t.R||!t.R.C){t.L.C=!1;t.C=!0;si(this,t);t=i.R}t.C=i.C;i.C=t.R.C=!1;oi(this,i);e=this._;break}}else{t=i.L;if(t.C){t.C=!1;i.C=!0;si(this,i);t=i.L}if(t.L&&t.L.C||t.R&&t.R.C){if(!t.L||!t.L.C){t.R.C=!1;t.C=!0;oi(this,t);t=i.L}t.C=i.C;i.C=t.L.C=!1;si(this,i);e=this._;break}}t.C=!0;e=i;i=i.U}while(!e.C);e&&(e.C=!1)}}};ia.geom.voronoi=function(e){function t(e){var t=new Array(e.length),r=a[0][0],i=a[0][1],o=a[1][0],s=a[1][1];li(n(e),a).cells.forEach(function(n,a){var l=n.edges,u=n.site,p=t[a]=l.length?l.map(function(e){var t=e.start();return[t.x,t.y]}):u.x>=r&&u.x<=o&&u.y>=i&&u.y<=s?[[r,s],[o,s],[o,i],[r,i]]:[];p.point=e[a]});return t}function n(e){return e.map(function(e,t){return{x:Math.round(o(e,t)/_a)*_a,y:Math.round(s(e,t)/_a)*_a,i:t}})}var r=wr,i=Or,o=r,s=i,a=au;if(e)return t(e);t.links=function(e){return li(n(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})};t.triangles=function(e){var t=[];li(n(e)).cells.forEach(function(n,r){for(var i,o,s=n.site,a=n.edges.sort(Wr),l=-1,u=a.length,p=a[u-1].edge,c=p.l===s?p.r:p.l;++l<u;){i=p;o=c;p=a[l].edge;c=p.l===s?p.r:p.l;r<o.i&&r<c.i&&pi(s,o,c)<0&&t.push([e[r],e[o.i],e[c.i]])}});return t};t.x=function(e){return arguments.length?(o=Ct(r=e),t):r};t.y=function(e){return arguments.length?(s=Ct(i=e),t):i};t.clipExtent=function(e){if(!arguments.length)return a===au?null:a;a=null==e?au:e;return t};t.size=function(e){return arguments.length?t.clipExtent(e&&[[0,0],e]):a===au?null:a&&a[1]};return t};var au=[[-1e6,-1e6],[1e6,1e6]];ia.geom.delaunay=function(e){return ia.geom.voronoi().triangles(e)};ia.geom.quadtree=function(e,t,n,r,i){function o(e){function o(e,t,n,r,i,o,s,a){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var l=e.x,p=e.y;if(null!=l)if(ma(l-n)+ma(p-r)<.01)u(e,t,n,r,i,o,s,a);else{var c=e.point;e.x=e.y=e.point=null;u(e,c,l,p,i,o,s,a);u(e,t,n,r,i,o,s,a)}else e.x=n,e.y=r,e.point=t}else u(e,t,n,r,i,o,s,a)}function u(e,t,n,r,i,s,a,l){var u=.5*(i+a),p=.5*(s+l),c=n>=u,d=r>=p,h=d<<1|c;e.leaf=!1;e=e.nodes[h]||(e.nodes[h]=hi());c?i=u:a=u;d?s=p:l=p;o(e,t,n,r,i,s,a,l)}var p,c,d,h,f,g,m,E,v,x=Ct(a),y=Ct(l);if(null!=t)g=t,m=n,E=r,v=i;else{E=v=-(g=m=1/0);c=[],d=[];f=e.length;if(s)for(h=0;f>h;++h){p=e[h];p.x<g&&(g=p.x);p.y<m&&(m=p.y);p.x>E&&(E=p.x);p.y>v&&(v=p.y);c.push(p.x);d.push(p.y)}else for(h=0;f>h;++h){var N=+x(p=e[h],h),I=+y(p,h);g>N&&(g=N);m>I&&(m=I);N>E&&(E=N);I>v&&(v=I);c.push(N);d.push(I)}}var A=E-g,T=v-m;A>T?v=m+A:E=g+T;var L=hi();L.add=function(e){o(L,e,+x(e,++h),+y(e,h),g,m,E,v)};L.visit=function(e){fi(e,L,g,m,E,v)};L.find=function(e){return gi(L,e[0],e[1],g,m,E,v)};h=-1;if(null==t){for(;++h<f;)o(L,e[h],c[h],d[h],g,m,E,v);--h}else e.forEach(L.add);c=d=e=p=null;return L}var s,a=wr,l=Or;if(s=arguments.length){a=ci;l=di;if(3===s){i=n;r=t;n=t=0}return o(e)}o.x=function(e){return arguments.length?(a=e,o):a};o.y=function(e){return arguments.length?(l=e,o):l};o.extent=function(e){if(!arguments.length)return null==t?null:[[t,n],[r,i]];null==e?t=n=r=i=null:(t=+e[0][0],n=+e[0][1],r=+e[1][0],i=+e[1][1]);return o};o.size=function(e){if(!arguments.length)return null==t?null:[r-t,i-n];null==e?t=n=r=i=null:(t=n=0,r=+e[0],i=+e[1]);return o};return o};ia.interpolateRgb=mi;ia.interpolateObject=Ei;ia.interpolateNumber=vi;ia.interpolateString=xi;var lu=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,uu=new RegExp(lu.source,"g");ia.interpolate=yi;ia.interpolators=[function(e,t){var n=typeof t;return("string"===n?el.has(t)||/^(#|rgb\(|hsl\()/.test(t)?mi:xi:t instanceof lt?mi:Array.isArray(t)?Ni:"object"===n&&isNaN(t)?Ei:vi)(e,t)}];ia.interpolateArray=Ni;var pu=function(){return y},cu=ia.map({linear:pu,poly:Ci,quad:function(){return Li},cubic:function(){return Si},sin:function(){return Ri},exp:function(){return wi},circle:function(){return Oi},elastic:_i,back:Fi,bounce:function(){return Pi}}),du=ia.map({"in":y,out:Ai,"in-out":Ti,"out-in":function(e){return Ti(Ai(e))}});ia.ease=function(e){var t=e.indexOf("-"),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):"in";n=cu.get(n)||pu;r=du.get(r)||y;return Ii(r(n.apply(null,oa.call(arguments,1))))};ia.interpolateHcl=ki;ia.interpolateHsl=Mi;ia.interpolateLab=Di;ia.interpolateRound=Gi;ia.transform=function(e){var t=aa.createElementNS(ia.ns.prefix.svg,"g");return(ia.transform=function(e){if(null!=e){t.setAttribute("transform",e);var n=t.transform.baseVal.consolidate()}return new ji(n?n.matrix:hu)})(e)};ji.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var hu={a:1,b:0,c:0,d:1,e:0,f:0};ia.interpolateTransform=Vi;ia.layout={};ia.layout.bundle=function(){return function(e){for(var t=[],n=-1,r=e.length;++n<r;)t.push(Wi(e[n]));return t}};ia.layout.chord=function(){function e(){var e,u,c,d,h,f={},g=[],m=ia.range(o),E=[];n=[];r=[];e=0,d=-1;for(;++d<o;){u=0,h=-1;for(;++h<o;)u+=i[d][h];g.push(u);E.push(ia.range(o));e+=u}s&&m.sort(function(e,t){return s(g[e],g[t])});a&&E.forEach(function(e,t){e.sort(function(e,n){return a(i[t][e],i[t][n])})});e=(ka-p*o)/e;u=0,d=-1;for(;++d<o;){c=u,h=-1;for(;++h<o;){var v=m[d],x=E[v][h],y=i[v][x],N=u,I=u+=y*e;f[v+"-"+x]={index:v,subindex:x,startAngle:N,endAngle:I,value:y}}r[v]={index:v,startAngle:c,endAngle:u,value:(u-c)/e};u+=p}d=-1;for(;++d<o;){h=d-1;for(;++h<o;){var A=f[d+"-"+h],T=f[h+"-"+d];(A.value||T.value)&&n.push(A.value<T.value?{source:T,target:A}:{source:A,target:T})}}l&&t()}function t(){n.sort(function(e,t){return l((e.source.value+e.target.value)/2,(t.source.value+t.target.value)/2)})}var n,r,i,o,s,a,l,u={},p=0;u.matrix=function(e){if(!arguments.length)return i;o=(i=e)&&i.length;n=r=null;return u};u.padding=function(e){if(!arguments.length)return p;p=e;n=r=null;return u};u.sortGroups=function(e){if(!arguments.length)return s;s=e;n=r=null;return u};u.sortSubgroups=function(e){if(!arguments.length)return a;a=e;n=null;return u};u.sortChords=function(e){if(!arguments.length)return l;l=e;n&&t();return u};u.chords=function(){n||e();return n};u.groups=function(){r||e();return r};return u};ia.layout.force=function(){function e(e){return function(t,n,r,i){if(t.point!==e){var o=t.cx-e.x,s=t.cy-e.y,a=i-n,l=o*o+s*s;if(l>a*a/m){if(f>l){var u=t.charge/l;e.px-=o*u;e.py-=s*u}return!0}if(t.point&&l&&f>l){var u=t.pointCharge/l;e.px-=o*u;e.py-=s*u}}return!t.charge}}function t(e){e.px=ia.event.x,e.py=ia.event.y;a.resume()}var n,r,i,o,s,a={},l=ia.dispatch("start","tick","end"),u=[1,1],p=.9,c=fu,d=gu,h=-30,f=mu,g=.1,m=.64,E=[],v=[];a.tick=function(){if((r*=.99)<.005){l.end({type:"end",alpha:r=0});return!0}var t,n,a,c,d,f,m,x,y,N=E.length,I=v.length;for(n=0;I>n;++n){a=v[n];c=a.source;d=a.target;x=d.x-c.x;y=d.y-c.y;if(f=x*x+y*y){f=r*o[n]*((f=Math.sqrt(f))-i[n])/f;x*=f;y*=f;d.x-=x*(m=c.weight/(d.weight+c.weight));d.y-=y*m;c.x+=x*(m=1-m);c.y+=y*m}}if(m=r*g){x=u[0]/2;y=u[1]/2;n=-1;if(m)for(;++n<N;){a=E[n];a.x+=(x-a.x)*m;a.y+=(y-a.y)*m}}if(h){Ji(t=ia.geom.quadtree(E),r,s);n=-1;for(;++n<N;)(a=E[n]).fixed||t.visit(e(a))}n=-1;for(;++n<N;){a=E[n];if(a.fixed){a.x=a.px;a.y=a.py}else{a.x-=(a.px-(a.px=a.x))*p;a.y-=(a.py-(a.py=a.y))*p}}l.tick({type:"tick",alpha:r})};a.nodes=function(e){if(!arguments.length)return E;E=e;return a};a.links=function(e){if(!arguments.length)return v;v=e;return a};a.size=function(e){if(!arguments.length)return u;u=e;return a};a.linkDistance=function(e){if(!arguments.length)return c;c="function"==typeof e?e:+e;return a};a.distance=a.linkDistance;a.linkStrength=function(e){if(!arguments.length)return d;d="function"==typeof e?e:+e;return a};a.friction=function(e){if(!arguments.length)return p;p=+e;return a};a.charge=function(e){if(!arguments.length)return h;h="function"==typeof e?e:+e;return a};a.chargeDistance=function(e){if(!arguments.length)return Math.sqrt(f);f=e*e;return a};a.gravity=function(e){if(!arguments.length)return g;g=+e;return a};a.theta=function(e){if(!arguments.length)return Math.sqrt(m);m=e*e;return a};a.alpha=function(e){if(!arguments.length)return r;e=+e;if(r)r=e>0?e:0;else if(e>0){l.start({type:"start",alpha:r=e});ia.timer(a.tick)}return a};a.start=function(){function e(e,r){if(!n){n=new Array(l);for(a=0;l>a;++a)n[a]=[];for(a=0;p>a;++a){var i=v[a];n[i.source.index].push(i.target);n[i.target.index].push(i.source)}}for(var o,s=n[t],a=-1,u=s.length;++a<u;)if(!isNaN(o=s[a][e]))return o;return Math.random()*r}var t,n,r,l=E.length,p=v.length,f=u[0],g=u[1];for(t=0;l>t;++t){(r=E[t]).index=t;r.weight=0}for(t=0;p>t;++t){r=v[t];"number"==typeof r.source&&(r.source=E[r.source]);"number"==typeof r.target&&(r.target=E[r.target]);++r.source.weight;++r.target.weight}for(t=0;l>t;++t){r=E[t];isNaN(r.x)&&(r.x=e("x",f));isNaN(r.y)&&(r.y=e("y",g));isNaN(r.px)&&(r.px=r.x);isNaN(r.py)&&(r.py=r.y)}i=[];if("function"==typeof c)for(t=0;p>t;++t)i[t]=+c.call(this,v[t],t);else for(t=0;p>t;++t)i[t]=c;o=[];if("function"==typeof d)for(t=0;p>t;++t)o[t]=+d.call(this,v[t],t);else for(t=0;p>t;++t)o[t]=d;s=[];if("function"==typeof h)for(t=0;l>t;++t)s[t]=+h.call(this,E[t],t);else for(t=0;l>t;++t)s[t]=h;return a.resume()};a.resume=function(){return a.alpha(.1)};a.stop=function(){return a.alpha(0)};a.drag=function(){n||(n=ia.behavior.drag().origin(y).on("dragstart.force",Yi).on("drag.force",t).on("dragend.force",Qi));if(!arguments.length)return n;this.on("mouseover.force",Xi).on("mouseout.force",Zi).call(n);return void 0};return ia.rebind(a,l,"on")};var fu=20,gu=1,mu=1/0;ia.layout.hierarchy=function(){function e(i){var o,s=[i],a=[];i.depth=0;for(;null!=(o=s.pop());){a.push(o);if((u=n.call(e,o,o.depth))&&(l=u.length)){for(var l,u,p;--l>=0;){s.push(p=u[l]);p.parent=o;p.depth=o.depth+1}r&&(o.value=0);o.children=u}else{r&&(o.value=+r.call(e,o,o.depth)||0);delete o.children}}no(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t);r&&(i=e.parent)&&(i.value+=e.value)});return a}var t=oo,n=ro,r=io;e.sort=function(n){if(!arguments.length)return t;t=n;return e};e.children=function(t){if(!arguments.length)return n;n=t;return e};e.value=function(t){if(!arguments.length)return r;r=t;return e};e.revalue=function(t){if(r){to(t,function(e){e.children&&(e.value=0)});no(t,function(t){var n;t.children||(t.value=+r.call(e,t,t.depth)||0);(n=t.parent)&&(n.value+=t.value)})}return t};return e};ia.layout.partition=function(){function e(t,n,r,i){var o=t.children;t.x=n;t.y=t.depth*i;t.dx=r;t.dy=i;if(o&&(s=o.length)){var s,a,l,u=-1;r=t.value?r/t.value:0;for(;++u<s;){e(a=o[u],n,l=a.value*r,i);n+=l}}}function t(e){var n=e.children,r=0;if(n&&(i=n.length))for(var i,o=-1;++o<i;)r=Math.max(r,t(n[o]));return 1+r}function n(n,o){var s=r.call(this,n,o);e(s[0],0,i[0],i[1]/t(s[0]));return s}var r=ia.layout.hierarchy(),i=[1,1];n.size=function(e){if(!arguments.length)return i;i=e;return n};return eo(n,r)};ia.layout.pie=function(){function e(s){var a,l=s.length,u=s.map(function(n,r){return+t.call(e,n,r)}),p=+("function"==typeof r?r.apply(this,arguments):r),c=("function"==typeof i?i.apply(this,arguments):i)-p,d=Math.min(Math.abs(c)/l,+("function"==typeof o?o.apply(this,arguments):o)),h=d*(0>c?-1:1),f=(c-l*h)/ia.sum(u),g=ia.range(l),m=[];null!=n&&g.sort(n===Eu?function(e,t){return u[t]-u[e]}:function(e,t){return n(s[e],s[t])});g.forEach(function(e){m[e]={data:s[e],value:a=u[e],startAngle:p,endAngle:p+=a*f+h,padAngle:d}});return m}var t=Number,n=Eu,r=0,i=ka,o=0;e.value=function(n){if(!arguments.length)return t;t=n;return e};e.sort=function(t){if(!arguments.length)return n;n=t;return e};e.startAngle=function(t){if(!arguments.length)return r;r=t;return e};e.endAngle=function(t){if(!arguments.length)return i;i=t;return e};e.padAngle=function(t){if(!arguments.length)return o;o=t;return e};return e};var Eu={};ia.layout.stack=function(){function e(a,l){if(!(d=a.length))return a;var u=a.map(function(n,r){return t.call(e,n,r)}),p=u.map(function(t){return t.map(function(t,n){return[o.call(e,t,n),s.call(e,t,n)]})}),c=n.call(e,p,l);u=ia.permute(u,c);p=ia.permute(p,c);var d,h,f,g,m=r.call(e,p,l),E=u[0].length;for(f=0;E>f;++f){i.call(e,u[0][f],g=m[f],p[0][f][1]);for(h=1;d>h;++h)i.call(e,u[h][f],g+=p[h-1][f][1],p[h][f][1])}return a}var t=y,n=po,r=co,i=uo,o=ao,s=lo;e.values=function(n){if(!arguments.length)return t;t=n;return e};e.order=function(t){if(!arguments.length)return n;n="function"==typeof t?t:vu.get(t)||po;return e};e.offset=function(t){if(!arguments.length)return r;r="function"==typeof t?t:xu.get(t)||co;return e};e.x=function(t){if(!arguments.length)return o;o=t;return e};e.y=function(t){if(!arguments.length)return s;
s=t;return e};e.out=function(t){if(!arguments.length)return i;i=t;return e};return e};var vu=ia.map({"inside-out":function(e){var t,n,r=e.length,i=e.map(ho),o=e.map(fo),s=ia.range(r).sort(function(e,t){return i[e]-i[t]}),a=0,l=0,u=[],p=[];for(t=0;r>t;++t){n=s[t];if(l>a){a+=o[n];u.push(n)}else{l+=o[n];p.push(n)}}return p.reverse().concat(u)},reverse:function(e){return ia.range(e.length).reverse()},"default":po}),xu=ia.map({silhouette:function(e){var t,n,r,i=e.length,o=e[0].length,s=[],a=0,l=[];for(n=0;o>n;++n){for(t=0,r=0;i>t;t++)r+=e[t][n][1];r>a&&(a=r);s.push(r)}for(n=0;o>n;++n)l[n]=(a-s[n])/2;return l},wiggle:function(e){var t,n,r,i,o,s,a,l,u,p=e.length,c=e[0],d=c.length,h=[];h[0]=l=u=0;for(n=1;d>n;++n){for(t=0,i=0;p>t;++t)i+=e[t][n][1];for(t=0,o=0,a=c[n][0]-c[n-1][0];p>t;++t){for(r=0,s=(e[t][n][1]-e[t][n-1][1])/(2*a);t>r;++r)s+=(e[r][n][1]-e[r][n-1][1])/a;o+=s*e[t][n][1]}h[n]=l-=i?o/i*a:0;u>l&&(u=l)}for(n=0;d>n;++n)h[n]-=u;return h},expand:function(e){var t,n,r,i=e.length,o=e[0].length,s=1/i,a=[];for(n=0;o>n;++n){for(t=0,r=0;i>t;t++)r+=e[t][n][1];if(r)for(t=0;i>t;t++)e[t][n][1]/=r;else for(t=0;i>t;t++)e[t][n][1]=s}for(n=0;o>n;++n)a[n]=0;return a},zero:co});ia.layout.histogram=function(){function e(e,o){for(var s,a,l=[],u=e.map(n,this),p=r.call(this,u,o),c=i.call(this,p,u,o),o=-1,d=u.length,h=c.length-1,f=t?1:1/d;++o<h;){s=l[o]=[];s.dx=c[o+1]-(s.x=c[o]);s.y=0}if(h>0){o=-1;for(;++o<d;){a=u[o];if(a>=p[0]&&a<=p[1]){s=l[ia.bisect(c,a,1,h)-1];s.y+=f;s.push(e[o])}}}return l}var t=!0,n=Number,r=vo,i=mo;e.value=function(t){if(!arguments.length)return n;n=t;return e};e.range=function(t){if(!arguments.length)return r;r=Ct(t);return e};e.bins=function(t){if(!arguments.length)return i;i="number"==typeof t?function(e){return Eo(e,t)}:Ct(t);return e};e.frequency=function(n){if(!arguments.length)return t;t=!!n;return e};return e};ia.layout.pack=function(){function e(e,o){var s=n.call(this,e,o),a=s[0],l=i[0],u=i[1],p=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};a.x=a.y=0;no(a,function(e){e.r=+p(e.value)});no(a,Ao);if(r){var c=r*(t?1:Math.max(2*a.r/l,2*a.r/u))/2;no(a,function(e){e.r+=c});no(a,Ao);no(a,function(e){e.r-=c})}So(a,l/2,u/2,t?1:1/Math.max(2*a.r/l,2*a.r/u));return s}var t,n=ia.layout.hierarchy().sort(xo),r=0,i=[1,1];e.size=function(t){if(!arguments.length)return i;i=t;return e};e.radius=function(n){if(!arguments.length)return t;t=null==n||"function"==typeof n?n:+n;return e};e.padding=function(t){if(!arguments.length)return r;r=+t;return e};return eo(e,n)};ia.layout.tree=function(){function e(e,i){var p=s.call(this,e,i),c=p[0],d=t(c);no(d,n),d.parent.m=-d.z;to(d,r);if(u)to(c,o);else{var h=c,f=c,g=c;to(c,function(e){e.x<h.x&&(h=e);e.x>f.x&&(f=e);e.depth>g.depth&&(g=e)});var m=a(h,f)/2-h.x,E=l[0]/(f.x+a(f,h)/2+m),v=l[1]/(g.depth||1);to(c,function(e){e.x=(e.x+m)*E;e.y=e.depth*v})}return p}function t(e){for(var t,n={A:null,children:[e]},r=[n];null!=(t=r.pop());)for(var i,o=t.children,s=0,a=o.length;a>s;++s)r.push((o[s]=i={_:o[s],parent:t,children:(i=o[s].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:s}).a=i);return n.children[0]}function n(e){var t=e.children,n=e.parent.children,r=e.i?n[e.i-1]:null;if(t.length){_o(e);var o=(t[0].z+t[t.length-1].z)/2;if(r){e.z=r.z+a(e._,r._);e.m=e.z-o}else e.z=o}else r&&(e.z=r.z+a(e._,r._));e.parent.A=i(e,r,e.parent.A||n[0])}function r(e){e._.x=e.z+e.parent.m;e.m+=e.parent.m}function i(e,t,n){if(t){for(var r,i=e,o=e,s=t,l=i.parent.children[0],u=i.m,p=o.m,c=s.m,d=l.m;s=wo(s),i=Ro(i),s&&i;){l=Ro(l);o=wo(o);o.a=e;r=s.z+c-i.z-u+a(s._,i._);if(r>0){Oo(Fo(s,e,n),e,r);u+=r;p+=r}c+=s.m;u+=i.m;d+=l.m;p+=o.m}if(s&&!wo(o)){o.t=s;o.m+=c-p}if(i&&!Ro(l)){l.t=i;l.m+=u-d;n=e}}return n}function o(e){e.x*=l[0];e.y=e.depth*l[1]}var s=ia.layout.hierarchy().sort(null).value(null),a=Co,l=[1,1],u=null;e.separation=function(t){if(!arguments.length)return a;a=t;return e};e.size=function(t){if(!arguments.length)return u?null:l;u=null==(l=t)?o:null;return e};e.nodeSize=function(t){if(!arguments.length)return u?l:null;u=null==(l=t)?null:o;return e};return eo(e,s)};ia.layout.cluster=function(){function e(e,o){var s,a=t.call(this,e,o),l=a[0],u=0;no(l,function(e){var t=e.children;if(t&&t.length){e.x=ko(t);e.y=Po(t)}else{e.x=s?u+=n(e,s):0;e.y=0;s=e}});var p=Mo(l),c=Do(l),d=p.x-n(p,c)/2,h=c.x+n(c,p)/2;no(l,i?function(e){e.x=(e.x-l.x)*r[0];e.y=(l.y-e.y)*r[1]}:function(e){e.x=(e.x-d)/(h-d)*r[0];e.y=(1-(l.y?e.y/l.y:1))*r[1]});return a}var t=ia.layout.hierarchy().sort(null).value(null),n=Co,r=[1,1],i=!1;e.separation=function(t){if(!arguments.length)return n;n=t;return e};e.size=function(t){if(!arguments.length)return i?null:r;i=null==(r=t);return e};e.nodeSize=function(t){if(!arguments.length)return i?r:null;i=null!=(r=t);return e};return eo(e,t)};ia.layout.treemap=function(){function e(e,t){for(var n,r,i=-1,o=e.length;++i<o;){r=(n=e[i]).value*(0>t?0:t);n.area=isNaN(r)||0>=r?0:r}}function t(n){var o=n.children;if(o&&o.length){var s,a,l,u=c(n),p=[],d=o.slice(),f=1/0,g="slice"===h?u.dx:"dice"===h?u.dy:"slice-dice"===h?1&n.depth?u.dy:u.dx:Math.min(u.dx,u.dy);e(d,u.dx*u.dy/n.value);p.area=0;for(;(l=d.length)>0;){p.push(s=d[l-1]);p.area+=s.area;if("squarify"!==h||(a=r(p,g))<=f){d.pop();f=a}else{p.area-=p.pop().area;i(p,g,u,!1);g=Math.min(u.dx,u.dy);p.length=p.area=0;f=1/0}}if(p.length){i(p,g,u,!0);p.length=p.area=0}o.forEach(t)}}function n(t){var r=t.children;if(r&&r.length){var o,s=c(t),a=r.slice(),l=[];e(a,s.dx*s.dy/t.value);l.area=0;for(;o=a.pop();){l.push(o);l.area+=o.area;if(null!=o.z){i(l,o.z?s.dx:s.dy,s,!a.length);l.length=l.area=0}}r.forEach(n)}}function r(e,t){for(var n,r=e.area,i=0,o=1/0,s=-1,a=e.length;++s<a;)if(n=e[s].area){o>n&&(o=n);n>i&&(i=n)}r*=r;t*=t;return r?Math.max(t*i*f/r,r/(t*o*f)):1/0}function i(e,t,n,r){var i,o=-1,s=e.length,a=n.x,u=n.y,p=t?l(e.area/t):0;if(t==n.dx){(r||p>n.dy)&&(p=n.dy);for(;++o<s;){i=e[o];i.x=a;i.y=u;i.dy=p;a+=i.dx=Math.min(n.x+n.dx-a,p?l(i.area/p):0)}i.z=!0;i.dx+=n.x+n.dx-a;n.y+=p;n.dy-=p}else{(r||p>n.dx)&&(p=n.dx);for(;++o<s;){i=e[o];i.x=a;i.y=u;i.dx=p;u+=i.dy=Math.min(n.y+n.dy-u,p?l(i.area/p):0)}i.z=!1;i.dy+=n.y+n.dy-u;n.x+=p;n.dx-=p}}function o(r){var i=s||a(r),o=i[0];o.x=0;o.y=0;o.dx=u[0];o.dy=u[1];s&&a.revalue(o);e([o],o.dx*o.dy/o.value);(s?n:t)(o);d&&(s=i);return i}var s,a=ia.layout.hierarchy(),l=Math.round,u=[1,1],p=null,c=Go,d=!1,h="squarify",f=.5*(1+Math.sqrt(5));o.size=function(e){if(!arguments.length)return u;u=e;return o};o.padding=function(e){function t(t){var n=e.call(o,t,t.depth);return null==n?Go(t):jo(t,"number"==typeof n?[n,n,n,n]:n)}function n(t){return jo(t,e)}if(!arguments.length)return p;var r;c=null==(p=e)?Go:"function"==(r=typeof e)?t:"number"===r?(e=[e,e,e,e],n):n;return o};o.round=function(e){if(!arguments.length)return l!=Number;l=e?Math.round:Number;return o};o.sticky=function(e){if(!arguments.length)return d;d=e;s=null;return o};o.ratio=function(e){if(!arguments.length)return f;f=e;return o};o.mode=function(e){if(!arguments.length)return h;h=e+"";return o};return eo(o,a)};ia.random={normal:function(e,t){var n=arguments.length;2>n&&(t=1);1>n&&(e=0);return function(){var n,r,i;do{n=2*Math.random()-1;r=2*Math.random()-1;i=n*n+r*r}while(!i||i>1);return e+t*n*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var e=ia.random.normal.apply(ia,arguments);return function(){return Math.exp(e())}},bates:function(e){var t=ia.random.irwinHall(e);return function(){return t()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;e>n;n++)t+=Math.random();return t}}};ia.scale={};var yu={floor:y,ceil:y};ia.scale.linear=function(){return Wo([0,1],[0,1],yi,!1)};var Nu={s:1,g:1,p:1,r:1,e:1};ia.scale.log=function(){return es(ia.scale.linear().domain([0,1]),10,!0,[1,10])};var Iu=ia.format(".0e"),Au={floor:function(e){return-Math.ceil(-e)},ceil:function(e){return-Math.floor(-e)}};ia.scale.pow=function(){return ts(ia.scale.linear(),1,[0,1])};ia.scale.sqrt=function(){return ia.scale.pow().exponent(.5)};ia.scale.ordinal=function(){return rs([],{t:"range",a:[[]]})};ia.scale.category10=function(){return ia.scale.ordinal().range(Tu)};ia.scale.category20=function(){return ia.scale.ordinal().range(Lu)};ia.scale.category20b=function(){return ia.scale.ordinal().range(Su)};ia.scale.category20c=function(){return ia.scale.ordinal().range(bu)};var Tu=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(Nt),Lu=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(Nt),Su=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(Nt),bu=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(Nt);ia.scale.quantile=function(){return is([],[])};ia.scale.quantize=function(){return os(0,1,[0,1])};ia.scale.threshold=function(){return ss([.5],[0,1])};ia.scale.identity=function(){return as([0,1])};ia.svg={};ia.svg.arc=function(){function e(){var e=Math.max(0,+n.apply(this,arguments)),u=Math.max(0,+r.apply(this,arguments)),p=s.apply(this,arguments)-Da,c=a.apply(this,arguments)-Da,d=Math.abs(c-p),h=p>c?0:1;e>u&&(f=u,u=e,e=f);if(d>=Ma)return t(u,h)+(e?t(e,1-h):"")+"Z";var f,g,m,E,v,x,y,N,I,A,T,L,S=0,b=0,C=[];if(E=(+l.apply(this,arguments)||0)/2){m=o===Cu?Math.sqrt(e*e+u*u):+o.apply(this,arguments);h||(b*=-1);u&&(b=rt(m/u*Math.sin(E)));e&&(S=rt(m/e*Math.sin(E)))}if(u){v=u*Math.cos(p+b);x=u*Math.sin(p+b);y=u*Math.cos(c-b);N=u*Math.sin(c-b);var R=Math.abs(c-p-2*b)<=Pa?0:1;if(b&&fs(v,x,y,N)===h^R){var w=(p+c)/2;v=u*Math.cos(w);x=u*Math.sin(w);y=N=null}}else v=x=0;if(e){I=e*Math.cos(c-S);A=e*Math.sin(c-S);T=e*Math.cos(p+S);L=e*Math.sin(p+S);var O=Math.abs(p-c+2*S)<=Pa?0:1;if(S&&fs(I,A,T,L)===1-h^O){var _=(p+c)/2;I=e*Math.cos(_);A=e*Math.sin(_);T=L=null}}else I=A=0;if((f=Math.min(Math.abs(u-e)/2,+i.apply(this,arguments)))>.001){g=u>e^h?0:1;var F=null==T?[I,A]:null==y?[v,x]:kr([v,x],[T,L],[y,N],[I,A]),P=v-F[0],k=x-F[1],M=y-F[0],D=N-F[1],G=1/Math.sin(Math.acos((P*M+k*D)/(Math.sqrt(P*P+k*k)*Math.sqrt(M*M+D*D)))/2),j=Math.sqrt(F[0]*F[0]+F[1]*F[1]);if(null!=y){var U=Math.min(f,(u-j)/(G+1)),q=gs(null==T?[I,A]:[T,L],[v,x],u,U,h),B=gs([y,N],[I,A],u,U,h);f===U?C.push("M",q[0],"A",U,",",U," 0 0,",g," ",q[1],"A",u,",",u," 0 ",1-h^fs(q[1][0],q[1][1],B[1][0],B[1][1]),",",h," ",B[1],"A",U,",",U," 0 0,",g," ",B[0]):C.push("M",q[0],"A",U,",",U," 0 1,",g," ",B[0])}else C.push("M",v,",",x);if(null!=T){var V=Math.min(f,(e-j)/(G-1)),H=gs([v,x],[T,L],e,-V,h),z=gs([I,A],null==y?[v,x]:[y,N],e,-V,h);f===V?C.push("L",z[0],"A",V,",",V," 0 0,",g," ",z[1],"A",e,",",e," 0 ",h^fs(z[1][0],z[1][1],H[1][0],H[1][1]),",",1-h," ",H[1],"A",V,",",V," 0 0,",g," ",H[0]):C.push("L",z[0],"A",V,",",V," 0 0,",g," ",H[0])}else C.push("L",I,",",A)}else{C.push("M",v,",",x);null!=y&&C.push("A",u,",",u," 0 ",R,",",h," ",y,",",N);C.push("L",I,",",A);null!=T&&C.push("A",e,",",e," 0 ",O,",",1-h," ",T,",",L)}C.push("Z");return C.join("")}function t(e,t){return"M0,"+e+"A"+e+","+e+" 0 1,"+t+" 0,"+-e+"A"+e+","+e+" 0 1,"+t+" 0,"+e}var n=us,r=ps,i=ls,o=Cu,s=cs,a=ds,l=hs;e.innerRadius=function(t){if(!arguments.length)return n;n=Ct(t);return e};e.outerRadius=function(t){if(!arguments.length)return r;r=Ct(t);return e};e.cornerRadius=function(t){if(!arguments.length)return i;i=Ct(t);return e};e.padRadius=function(t){if(!arguments.length)return o;o=t==Cu?Cu:Ct(t);return e};e.startAngle=function(t){if(!arguments.length)return s;s=Ct(t);return e};e.endAngle=function(t){if(!arguments.length)return a;a=Ct(t);return e};e.padAngle=function(t){if(!arguments.length)return l;l=Ct(t);return e};e.centroid=function(){var e=(+n.apply(this,arguments)+ +r.apply(this,arguments))/2,t=(+s.apply(this,arguments)+ +a.apply(this,arguments))/2-Da;return[Math.cos(t)*e,Math.sin(t)*e]};return e};var Cu="auto";ia.svg.line=function(){return ms(y)};var Ru=ia.map({linear:Es,"linear-closed":vs,step:xs,"step-before":ys,"step-after":Ns,basis:bs,"basis-open":Cs,"basis-closed":Rs,bundle:ws,cardinal:Ts,"cardinal-open":Is,"cardinal-closed":As,monotone:Ms});Ru.forEach(function(e,t){t.key=e;t.closed=/-closed$/.test(e)});var wu=[0,2/3,1/3,0],Ou=[0,1/3,2/3,0],_u=[0,1/6,2/3,1/6];ia.svg.line.radial=function(){var e=ms(Ds);e.radius=e.x,delete e.x;e.angle=e.y,delete e.y;return e};ys.reverse=Ns;Ns.reverse=ys;ia.svg.area=function(){return Gs(y)};ia.svg.area.radial=function(){var e=Gs(Ds);e.radius=e.x,delete e.x;e.innerRadius=e.x0,delete e.x0;e.outerRadius=e.x1,delete e.x1;e.angle=e.y,delete e.y;e.startAngle=e.y0,delete e.y0;e.endAngle=e.y1,delete e.y1;return e};ia.svg.chord=function(){function e(e,a){var l=t(this,o,e,a),u=t(this,s,e,a);return"M"+l.p0+r(l.r,l.p1,l.a1-l.a0)+(n(l,u)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,u.r,u.p0)+r(u.r,u.p1,u.a1-u.a0)+i(u.r,u.p1,l.r,l.p0))+"Z"}function t(e,t,n,r){var i=t.call(e,n,r),o=a.call(e,i,r),s=l.call(e,i,r)-Da,p=u.call(e,i,r)-Da;return{r:o,a0:s,a1:p,p0:[o*Math.cos(s),o*Math.sin(s)],p1:[o*Math.cos(p),o*Math.sin(p)]}}function n(e,t){return e.a0==t.a0&&e.a1==t.a1}function r(e,t,n){return"A"+e+","+e+" 0 "+ +(n>Pa)+",1 "+t}function i(e,t,n,r){return"Q 0,0 "+r}var o=yr,s=Nr,a=js,l=cs,u=ds;e.radius=function(t){if(!arguments.length)return a;a=Ct(t);return e};e.source=function(t){if(!arguments.length)return o;o=Ct(t);return e};e.target=function(t){if(!arguments.length)return s;s=Ct(t);return e};e.startAngle=function(t){if(!arguments.length)return l;l=Ct(t);return e};e.endAngle=function(t){if(!arguments.length)return u;u=Ct(t);return e};return e};ia.svg.diagonal=function(){function e(e,i){var o=t.call(this,e,i),s=n.call(this,e,i),a=(o.y+s.y)/2,l=[o,{x:o.x,y:a},{x:s.x,y:a},s];l=l.map(r);return"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var t=yr,n=Nr,r=Us;e.source=function(n){if(!arguments.length)return t;t=Ct(n);return e};e.target=function(t){if(!arguments.length)return n;n=Ct(t);return e};e.projection=function(t){if(!arguments.length)return r;r=t;return e};return e};ia.svg.diagonal.radial=function(){var e=ia.svg.diagonal(),t=Us,n=e.projection;e.projection=function(e){return arguments.length?n(qs(t=e)):t};return e};ia.svg.symbol=function(){function e(e,r){return(Fu.get(t.call(this,e,r))||Hs)(n.call(this,e,r))}var t=Vs,n=Bs;e.type=function(n){if(!arguments.length)return t;t=Ct(n);return e};e.size=function(t){if(!arguments.length)return n;n=Ct(t);return e};return e};var Fu=ia.map({circle:Hs,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ku)),n=t*ku;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/Pu),n=t*Pu/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/Pu),n=t*Pu/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});ia.svg.symbolTypes=Fu.keys();var Pu=Math.sqrt(3),ku=Math.tan(30*Ga);La.transition=function(e){for(var t,n,r=Mu||++Uu,i=Ys(e),o=[],s=Du||{time:Date.now(),ease:bi,delay:0,duration:250},a=-1,l=this.length;++a<l;){o.push(t=[]);for(var u=this[a],p=-1,c=u.length;++p<c;){(n=u[p])&&Qs(n,p,i,r,s);t.push(n)}}return Ws(o,i,r)};La.interrupt=function(e){return this.each(null==e?Gu:zs(Ys(e)))};var Mu,Du,Gu=zs(Ys()),ju=[],Uu=0;ju.call=La.call;ju.empty=La.empty;ju.node=La.node;ju.size=La.size;ia.transition=function(e,t){return e&&e.transition?Mu?e.transition(t):e:ia.selection().transition(e)};ia.transition.prototype=ju;ju.select=function(e){var t,n,r,i=this.id,o=this.namespace,s=[];e=w(e);for(var a=-1,l=this.length;++a<l;){s.push(t=[]);for(var u=this[a],p=-1,c=u.length;++p<c;)if((r=u[p])&&(n=e.call(r,r.__data__,p,a))){"__data__"in r&&(n.__data__=r.__data__);Qs(n,p,o,i,r[o][i]);t.push(n)}else t.push(null)}return Ws(s,o,i)};ju.selectAll=function(e){var t,n,r,i,o,s=this.id,a=this.namespace,l=[];e=O(e);for(var u=-1,p=this.length;++u<p;)for(var c=this[u],d=-1,h=c.length;++d<h;)if(r=c[d]){o=r[a][s];n=e.call(r,r.__data__,d,u);l.push(t=[]);for(var f=-1,g=n.length;++f<g;){(i=n[f])&&Qs(i,f,a,s,o);t.push(i)}}return Ws(l,a,s)};ju.filter=function(e){var t,n,r,i=[];"function"!=typeof e&&(e=V(e));for(var o=0,s=this.length;s>o;o++){i.push(t=[]);for(var n=this[o],a=0,l=n.length;l>a;a++)(r=n[a])&&e.call(r,r.__data__,a,o)&&t.push(r)}return Ws(i,this.namespace,this.id)};ju.tween=function(e,t){var n=this.id,r=this.namespace;return arguments.length<2?this.node()[r][n].tween.get(e):z(this,null==t?function(t){t[r][n].tween.remove(e)}:function(i){i[r][n].tween.set(e,t)})};ju.attr=function(e,t){function n(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function i(e){return null==e?n:(e+="",function(){var t,n=this.getAttribute(a);return n!==e&&(t=s(n,e),function(e){this.setAttribute(a,t(e))})})}function o(e){return null==e?r:(e+="",function(){var t,n=this.getAttributeNS(a.space,a.local);return n!==e&&(t=s(n,e),function(e){this.setAttributeNS(a.space,a.local,t(e))})})}if(arguments.length<2){for(t in e)this.attr(t,e[t]);return this}var s="transform"==e?Vi:yi,a=ia.ns.qualify(e);return $s(this,"attr."+e,t,a.local?o:i)};ju.attrTween=function(e,t){function n(e,n){var r=t.call(this,e,n,this.getAttribute(i));return r&&function(e){this.setAttribute(i,r(e))}}function r(e,n){var r=t.call(this,e,n,this.getAttributeNS(i.space,i.local));return r&&function(e){this.setAttributeNS(i.space,i.local,r(e))}}var i=ia.ns.qualify(e);return this.tween("attr."+e,i.local?r:n)};ju.style=function(e,t,n){function i(){this.style.removeProperty(e)}function o(t){return null==t?i:(t+="",function(){var i,o=r(this).getComputedStyle(this,null).getPropertyValue(e);return o!==t&&(i=yi(o,t),function(t){this.style.setProperty(e,i(t),n)})})}var s=arguments.length;if(3>s){if("string"!=typeof e){2>s&&(t="");for(n in e)this.style(n,e[n],t);return this}n=""}return $s(this,"style."+e,t,o)};ju.styleTween=function(e,t,n){function i(i,o){var s=t.call(this,i,o,r(this).getComputedStyle(this,null).getPropertyValue(e));return s&&function(t){this.style.setProperty(e,s(t),n)}}arguments.length<3&&(n="");return this.tween("style."+e,i)};ju.text=function(e){return $s(this,"text",e,Ks)};ju.remove=function(){var e=this.namespace;return this.each("end.transition",function(){var t;this[e].count<2&&(t=this.parentNode)&&t.removeChild(this)})};ju.ease=function(e){var t=this.id,n=this.namespace;if(arguments.length<1)return this.node()[n][t].ease;"function"!=typeof e&&(e=ia.ease.apply(ia,arguments));return z(this,function(r){r[n][t].ease=e})};ju.delay=function(e){var t=this.id,n=this.namespace;return arguments.length<1?this.node()[n][t].delay:z(this,"function"==typeof e?function(r,i,o){r[n][t].delay=+e.call(r,r.__data__,i,o)}:(e=+e,function(r){r[n][t].delay=e}))};ju.duration=function(e){var t=this.id,n=this.namespace;return arguments.length<1?this.node()[n][t].duration:z(this,"function"==typeof e?function(r,i,o){r[n][t].duration=Math.max(1,e.call(r,r.__data__,i,o))}:(e=Math.max(1,e),function(r){r[n][t].duration=e}))};ju.each=function(e,t){var n=this.id,r=this.namespace;if(arguments.length<2){var i=Du,o=Mu;try{Mu=n;z(this,function(t,i,o){Du=t[r][n];e.call(t,t.__data__,i,o)})}finally{Du=i;Mu=o}}else z(this,function(i){var o=i[r][n];(o.event||(o.event=ia.dispatch("start","end","interrupt"))).on(e,t)});return this};ju.transition=function(){for(var e,t,n,r,i=this.id,o=++Uu,s=this.namespace,a=[],l=0,u=this.length;u>l;l++){a.push(e=[]);for(var t=this[l],p=0,c=t.length;c>p;p++){if(n=t[p]){r=n[s][i];Qs(n,p,s,o,{time:r.time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration})}e.push(n)}}return Ws(a,s,o)};ia.svg.axis=function(){function e(e){e.each(function(){var e,u=ia.select(this),p=this.__chart__||n,c=this.__chart__=n.copy(),d=null==l?c.ticks?c.ticks.apply(c,a):c.domain():l,h=null==t?c.tickFormat?c.tickFormat.apply(c,a):y:t,f=u.selectAll(".tick").data(d,c),g=f.enter().insert("g",".domain").attr("class","tick").style("opacity",_a),m=ia.transition(f.exit()).style("opacity",_a).remove(),E=ia.transition(f.order()).style("opacity",1),v=Math.max(i,0)+s,x=qo(c),N=u.selectAll(".domain").data([0]),I=(N.enter().append("path").attr("class","domain"),ia.transition(N));g.append("line");g.append("text");var A,T,L,S,b=g.select("line"),C=E.select("line"),R=f.select("text").text(h),w=g.select("text"),O=E.select("text"),_="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r){e=Xs,A="x",L="y",T="x2",S="y2";R.attr("dy",0>_?"0em":".71em").style("text-anchor","middle");I.attr("d","M"+x[0]+","+_*o+"V0H"+x[1]+"V"+_*o)}else{e=Zs,A="y",L="x",T="y2",S="x2";R.attr("dy",".32em").style("text-anchor",0>_?"end":"start");I.attr("d","M"+_*o+","+x[0]+"H0V"+x[1]+"H"+_*o)}b.attr(S,_*i);w.attr(L,_*v);C.attr(T,0).attr(S,_*i);O.attr(A,0).attr(L,_*v);if(c.rangeBand){var F=c,P=F.rangeBand()/2;p=c=function(e){return F(e)+P}}else p.rangeBand?p=c:m.call(e,c,p);g.call(e,p,c);E.call(e,c,c)})}var t,n=ia.scale.linear(),r=qu,i=6,o=6,s=3,a=[10],l=null;e.scale=function(t){if(!arguments.length)return n;n=t;return e};e.orient=function(t){if(!arguments.length)return r;r=t in Bu?t+"":qu;return e};e.ticks=function(){if(!arguments.length)return a;a=arguments;return e};e.tickValues=function(t){if(!arguments.length)return l;l=t;return e};e.tickFormat=function(n){if(!arguments.length)return t;t=n;return e};e.tickSize=function(t){var n=arguments.length;if(!n)return i;i=+t;o=+arguments[n-1];return e};e.innerTickSize=function(t){if(!arguments.length)return i;i=+t;return e};e.outerTickSize=function(t){if(!arguments.length)return o;o=+t;return e};e.tickPadding=function(t){if(!arguments.length)return s;s=+t;return e};e.tickSubdivide=function(){return arguments.length&&e};return e};var qu="bottom",Bu={top:1,right:1,bottom:1,left:1};ia.svg.brush=function(){function e(r){r.each(function(){var r=ia.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",o).on("touchstart.brush",o),s=r.selectAll(".background").data([0]);s.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair");r.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=r.selectAll(".resize").data(g,y);a.exit().remove();a.enter().append("g").attr("class",function(e){return"resize "+e}).style("cursor",function(e){return Vu[e]}).append("rect").attr("x",function(e){return/[ew]$/.test(e)?-3:null}).attr("y",function(e){return/^[ns]/.test(e)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden");a.style("display",e.empty()?"none":null);var l,c=ia.transition(r),d=ia.transition(s);if(u){l=qo(u);d.attr("x",l[0]).attr("width",l[1]-l[0]);n(c)}if(p){l=qo(p);d.attr("y",l[0]).attr("height",l[1]-l[0]);i(c)}t(c)})}function t(e){e.selectAll(".resize").attr("transform",function(e){return"translate("+c[+/e$/.test(e)]+","+d[+/^s/.test(e)]+")"})}function n(e){e.select(".extent").attr("x",c[0]);e.selectAll(".extent,.n>rect,.s>rect").attr("width",c[1]-c[0])}function i(e){e.select(".extent").attr("y",d[0]);e.selectAll(".extent,.e>rect,.w>rect").attr("height",d[1]-d[0])}function o(){function o(){if(32==ia.event.keyCode){if(!R){x=null;O[0]-=c[1];O[1]-=d[1];R=2}S()}}function g(){if(32==ia.event.keyCode&&2==R){O[0]+=c[1];O[1]+=d[1];R=0;S()}}function m(){var e=ia.mouse(N),r=!1;if(y){e[0]+=y[0];e[1]+=y[1]}if(!R)if(ia.event.altKey){x||(x=[(c[0]+c[1])/2,(d[0]+d[1])/2]);O[0]=c[+(e[0]<x[0])];O[1]=d[+(e[1]<x[1])]}else x=null;if(b&&E(e,u,0)){n(T);r=!0}if(C&&E(e,p,1)){i(T);r=!0}if(r){t(T);A({type:"brush",mode:R?"move":"resize"})}}function E(e,t,n){var r,i,o=qo(t),l=o[0],u=o[1],p=O[n],g=n?d:c,m=g[1]-g[0];if(R){l-=p;u-=m+p}r=(n?f:h)?Math.max(l,Math.min(u,e[n])):e[n];if(R)i=(r+=p)+m;else{x&&(p=Math.max(l,Math.min(u,2*x[n]-r)));if(r>p){i=r;r=p}else i=p}if(g[0]!=r||g[1]!=i){n?a=null:s=null;g[0]=r;g[1]=i;return!0}}function v(){m();T.style("pointer-events","all").selectAll(".resize").style("display",e.empty()?"none":null);ia.select("body").style("cursor",null);_.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null);w();A({type:"brushend"})}var x,y,N=this,I=ia.select(ia.event.target),A=l.of(N,arguments),T=ia.select(N),L=I.datum(),b=!/^(n|s)$/.test(L)&&u,C=!/^(e|w)$/.test(L)&&p,R=I.classed("extent"),w=X(N),O=ia.mouse(N),_=ia.select(r(N)).on("keydown.brush",o).on("keyup.brush",g);ia.event.changedTouches?_.on("touchmove.brush",m).on("touchend.brush",v):_.on("mousemove.brush",m).on("mouseup.brush",v);T.interrupt().selectAll("*").interrupt();if(R){O[0]=c[0]-O[0];O[1]=d[0]-O[1]}else if(L){var F=+/w$/.test(L),P=+/^n/.test(L);y=[c[1-F]-O[0],d[1-P]-O[1]];O[0]=c[F];O[1]=d[P]}else ia.event.altKey&&(x=O.slice());T.style("pointer-events","none").selectAll(".resize").style("display",null);ia.select("body").style("cursor",I.style("cursor"));A({type:"brushstart"});m()}var s,a,l=C(e,"brushstart","brush","brushend"),u=null,p=null,c=[0,0],d=[0,0],h=!0,f=!0,g=Hu[0];e.event=function(e){e.each(function(){var e=l.of(this,arguments),t={x:c,y:d,i:s,j:a},n=this.__chart__||t;this.__chart__=t;if(Mu)ia.select(this).transition().each("start.brush",function(){s=n.i;a=n.j;c=n.x;d=n.y;e({type:"brushstart"})}).tween("brush:brush",function(){var n=Ni(c,t.x),r=Ni(d,t.y);s=a=null;return function(i){c=t.x=n(i);d=t.y=r(i);e({type:"brush",mode:"resize"})}}).each("end.brush",function(){s=t.i;a=t.j;e({type:"brush",mode:"resize"});e({type:"brushend"})});else{e({type:"brushstart"});e({type:"brush",mode:"resize"});e({type:"brushend"})}})};e.x=function(t){if(!arguments.length)return u;u=t;g=Hu[!u<<1|!p];return e};e.y=function(t){if(!arguments.length)return p;p=t;g=Hu[!u<<1|!p];return e};e.clamp=function(t){if(!arguments.length)return u&&p?[h,f]:u?h:p?f:null;u&&p?(h=!!t[0],f=!!t[1]):u?h=!!t:p&&(f=!!t);return e};e.extent=function(t){var n,r,i,o,l;if(!arguments.length){if(u)if(s)n=s[0],r=s[1];else{n=c[0],r=c[1];u.invert&&(n=u.invert(n),r=u.invert(r));n>r&&(l=n,n=r,r=l)}if(p)if(a)i=a[0],o=a[1];else{i=d[0],o=d[1];p.invert&&(i=p.invert(i),o=p.invert(o));i>o&&(l=i,i=o,o=l)}return u&&p?[[n,i],[r,o]]:u?[n,r]:p&&[i,o]}if(u){n=t[0],r=t[1];p&&(n=n[0],r=r[0]);s=[n,r];u.invert&&(n=u(n),r=u(r));n>r&&(l=n,n=r,r=l);(n!=c[0]||r!=c[1])&&(c=[n,r])}if(p){i=t[0],o=t[1];u&&(i=i[1],o=o[1]);a=[i,o];p.invert&&(i=p(i),o=p(o));i>o&&(l=i,i=o,o=l);(i!=d[0]||o!=d[1])&&(d=[i,o])}return e};e.clear=function(){if(!e.empty()){c=[0,0],d=[0,0];s=a=null}return e};e.empty=function(){return!!u&&c[0]==c[1]||!!p&&d[0]==d[1]};return ia.rebind(e,l,"on")};var Vu={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Hu=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],zu=pl.format=ml.timeFormat,Wu=zu.utc,$u=Wu("%Y-%m-%dT%H:%M:%S.%LZ");zu.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Js:$u;Js.parse=function(e){var t=new Date(e);return isNaN(t)?null:t};Js.toString=$u.toString;pl.second=qt(function(e){return new cl(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()});pl.seconds=pl.second.range;pl.seconds.utc=pl.second.utc.range;pl.minute=qt(function(e){return new cl(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()});pl.minutes=pl.minute.range;pl.minutes.utc=pl.minute.utc.range;pl.hour=qt(function(e){var t=e.getTimezoneOffset()/60;return new cl(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()});pl.hours=pl.hour.range;pl.hours.utc=pl.hour.utc.range;pl.month=qt(function(e){e=pl.day(e);e.setDate(1);return e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()});pl.months=pl.month.range;pl.months.utc=pl.month.utc.range;var Ku=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Yu=[[pl.second,1],[pl.second,5],[pl.second,15],[pl.second,30],[pl.minute,1],[pl.minute,5],[pl.minute,15],[pl.minute,30],[pl.hour,1],[pl.hour,3],[pl.hour,6],[pl.hour,12],[pl.day,1],[pl.day,2],[pl.week,1],[pl.month,1],[pl.month,3],[pl.year,1]],Qu=zu.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",On]]),Xu={range:function(e,t,n){return ia.range(Math.ceil(e/n)*n,+t,n).map(ta)},floor:y,ceil:y};Yu.year=pl.year;pl.scale=function(){return ea(ia.scale.linear(),Yu,Qu)};var Zu=Yu.map(function(e){return[e[0].utc,e[1]]}),Ju=Wu.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",On]]);Zu.year=pl.year.utc;pl.scale.utc=function(){return ea(ia.scale.linear(),Zu,Ju)};ia.text=Rt(function(e){return e.responseText});ia.json=function(e,t){return wt(e,"application/json",na,t)};ia.html=function(e,t){return wt(e,"text/html",ra,t)};ia.xml=Rt(function(e){return e.responseXML});"function"==typeof e&&e.amd?e(ia):"object"==typeof n&&n.exports&&(n.exports=ia);this.d3=ia}()},{}],59:[function(e,t){t.exports=e(3)},{"/home/lrd900/yasgui/yasgui/node_modules/jquery-ui/core.js":3,jquery:void 0}],60:[function(e,t){t.exports=e(4)},{"./widget":62,"/home/lrd900/yasgui/yasgui/node_modules/jquery-ui/mouse.js":4,jquery:void 0}],61:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("./core");e("./mouse");e("./widget");(function(e){function t(e,t,n){return e>t&&t+n>e}function n(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))}e.widget("ui.sortable",e.ui.mouse,{version:"1.10.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var e=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?"x"===e.axis||n(this.items[0].item):!1;this.offset=this.element.offset();this._mouseInit();this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){if("disabled"===t){this.options[t]=n;this.widget().toggleClass("ui-sortable-disabled",!!n)}else e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=null,i=!1,o=this;if(this.reverting)return!1;if(this.options.disabled||"static"===this.options.type)return!1;this._refreshItems(t);e(t.target).parents().each(function(){if(e.data(this,o.widgetName+"-item")===o){r=e(this);return!1}});e.data(t.target,o.widgetName+"-item")===o&&(r=e(t.target));if(!r)return!1;if(this.options.handle&&!n){e(this.options.handle,r).find("*").addBack().each(function(){this===t.target&&(i=!0)});if(!i)return!1}this.currentItem=r;this._removeCurrentsFromItems();return!0},_mouseStart:function(t,n,r){var i,o,s=this.options;this.currentContainer=this;this.refreshPositions();
this.helper=this._createHelper(t);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(t);this.originalPageX=t.pageX;this.originalPageY=t.pageY;s.cursorAt&&this._adjustOffsetFromHelper(s.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!==this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();s.containment&&this._setContainment();if(s.cursor&&"auto"!==s.cursor){o=this.document.find("body");this.storedCursor=o.css("cursor");o.css("cursor",s.cursor);this.storedStylesheet=e("<style>*{ cursor: "+s.cursor+" !important; }</style>").appendTo(o)}if(s.opacity){this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity"));this.helper.css("opacity",s.opacity)}if(s.zIndex){this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex"));this.helper.css("zIndex",s.zIndex)}this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset());this._trigger("start",t,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",t,this._uiHash(this));e.ui.ddmanager&&(e.ui.ddmanager.current=this);e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t);this.dragging=!0;this.helper.addClass("ui-sortable-helper");this._mouseDrag(t);return!0},_mouseDrag:function(t){var n,r,i,o,s=this.options,a=!1;this.position=this._generatePosition(t);this.positionAbs=this._convertPositionTo("absolute");this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){if(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName){this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<s.scrollSensitivity?this.scrollParent[0].scrollTop=a=this.scrollParent[0].scrollTop+s.scrollSpeed:t.pageY-this.overflowOffset.top<s.scrollSensitivity&&(this.scrollParent[0].scrollTop=a=this.scrollParent[0].scrollTop-s.scrollSpeed);this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<s.scrollSensitivity?this.scrollParent[0].scrollLeft=a=this.scrollParent[0].scrollLeft+s.scrollSpeed:t.pageX-this.overflowOffset.left<s.scrollSensitivity&&(this.scrollParent[0].scrollLeft=a=this.scrollParent[0].scrollLeft-s.scrollSpeed)}else{t.pageY-e(document).scrollTop()<s.scrollSensitivity?a=e(document).scrollTop(e(document).scrollTop()-s.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<s.scrollSensitivity&&(a=e(document).scrollTop(e(document).scrollTop()+s.scrollSpeed));t.pageX-e(document).scrollLeft()<s.scrollSensitivity?a=e(document).scrollLeft(e(document).scrollLeft()-s.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<s.scrollSensitivity&&(a=e(document).scrollLeft(e(document).scrollLeft()+s.scrollSpeed))}a!==!1&&e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)}this.positionAbs=this._convertPositionTo("absolute");this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px");this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px");for(n=this.items.length-1;n>=0;n--){r=this.items[n];i=r.item[0];o=this._intersectsWithPointer(r);if(o&&r.instance===this.currentContainer&&i!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==i&&!e.contains(this.placeholder[0],i)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],i):!0)){this.direction=1===o?"down":"up";if("pointer"!==this.options.tolerance&&!this._intersectsWithSides(r))break;this._rearrange(t,r);this._trigger("change",t,this._uiHash());break}}this._contactContainers(t);e.ui.ddmanager&&e.ui.ddmanager.drag(this,t);this._trigger("sort",t,this._uiHash());this.lastPositionAbs=this.positionAbs;return!1},_mouseStop:function(t,n){if(t){e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t);if(this.options.revert){var r=this,i=this.placeholder.offset(),o=this.options.axis,s={};o&&"x"!==o||(s.left=i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft));o&&"y"!==o||(s.top=i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop));this.reverting=!0;e(this.helper).animate(s,parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null});"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--){this.containers[t]._trigger("deactivate",null,this._uiHash(this));if(this.containers[t].containerCache.over){this.containers[t]._trigger("out",null,this._uiHash(this));this.containers[t].containerCache.over=0}}}if(this.placeholder){this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove();e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null});this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)}return this},serialize:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];t=t||{};e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);n&&r.push((t.key||n[1]+"[]")+"="+(t.key&&t.expression?n[1]:n[2]))});!r.length&&t.key&&r.push(t.key+"=");return r.join("&")},toArray:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];t=t||{};n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")});return r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,o=e.left,s=o+e.width,a=e.top,l=a+e.height,u=this.offset.click.top,p=this.offset.click.left,c="x"===this.options.axis||r+u>a&&l>r+u,d="y"===this.options.axis||t+p>o&&s>t+p,h=c&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?h:o<t+this.helperProportions.width/2&&n-this.helperProportions.width/2<s&&a<r+this.helperProportions.height/2&&i-this.helperProportions.height/2<l},_intersectsWithPointer:function(e){var n="x"===this.options.axis||t(this.positionAbs.top+this.offset.click.top,e.top,e.height),r="y"===this.options.axis||t(this.positionAbs.left+this.offset.click.left,e.left,e.width),i=n&&r,o=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return i?this.floating?s&&"right"===s||"down"===o?2:1:o&&("down"===o?2:1):!1},_intersectsWithSides:function(e){var n=t(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),r=t(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),i=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return this.floating&&o?"right"===o&&r||"left"===o&&!r:i&&("down"===i&&n||"up"===i&&!n)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){this._refreshItems(e);this.refreshPositions();return this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){function n(){a.push(this)}var r,i,o,s,a=[],l=[],u=this._connectWith();if(u&&t)for(r=u.length-1;r>=0;r--){o=e(u[r]);for(i=o.length-1;i>=0;i--){s=e.data(o[i],this.widgetFullName);s&&s!==this&&!s.options.disabled&&l.push([e.isFunction(s.options.items)?s.options.items.call(s.element):e(s.options.items,s.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),s])}}l.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(r=l.length-1;r>=0;r--)l[r][0].each(n);return e(a)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var n=0;n<t.length;n++)if(t[n]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[];this.containers=[this];var n,r,i,o,s,a,l,u,p=this.items,c=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(n=d.length-1;n>=0;n--){i=e(d[n]);for(r=i.length-1;r>=0;r--){o=e.data(i[r],this.widgetFullName);if(o&&o!==this&&!o.options.disabled){c.push([e.isFunction(o.options.items)?o.options.items.call(o.element[0],t,{item:this.currentItem}):e(o.options.items,o.element),o]);this.containers.push(o)}}}for(n=c.length-1;n>=0;n--){s=c[n][1];a=c[n][0];for(r=0,u=a.length;u>r;r++){l=e(a[r]);l.data(this.widgetName+"-item",s);p.push({item:l,instance:s,width:0,height:0,left:0,top:0})}}},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var n,r,i,o;for(n=this.items.length-1;n>=0;n--){r=this.items[n];if(r.instance===this.currentContainer||!this.currentContainer||r.item[0]===this.currentItem[0]){i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item;if(!t){r.width=i.outerWidth();r.height=i.outerHeight()}o=i.offset();r.left=o.left;r.top=o.top}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(n=this.containers.length-1;n>=0;n--){o=this.containers[n].element.offset();this.containers[n].containerCache.left=o.left;this.containers[n].containerCache.top=o.top;this.containers[n].containerCache.width=this.containers[n].element.outerWidth();this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(t){t=t||this;var n,r=t.options;if(!r.placeholder||r.placeholder.constructor===String){n=r.placeholder;r.placeholder={element:function(){var r=t.currentItem[0].nodeName.toLowerCase(),i=e("<"+r+">",t.document[0]).addClass(n||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");"tr"===r?t.currentItem.children().each(function(){e("<td> </td>",t.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(i)}):"img"===r&&i.attr("src",t.currentItem.attr("src"));n||i.css("visibility","hidden");return i},update:function(e,i){if(!n||r.forcePlaceholderSize){i.height()||i.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10));i.width()||i.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10))}}}}t.placeholder=e(r.placeholder.element.call(t.element,t.currentItem));t.currentItem.after(t.placeholder);r.placeholder.update(t,t.placeholder)},_contactContainers:function(r){var i,o,s,a,l,u,p,c,d,h,f=null,g=null;for(i=this.containers.length-1;i>=0;i--)if(!e.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(f&&e.contains(this.containers[i].element[0],f.element[0]))continue;f=this.containers[i];g=i}else if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",r,this._uiHash(this));this.containers[i].containerCache.over=0}if(f)if(1===this.containers.length){if(!this.containers[g].containerCache.over){this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}}else{s=1e4;a=null;h=f.floating||n(this.currentItem);l=h?"left":"top";u=h?"width":"height";p=this.positionAbs[l]+this.offset.click[l];for(o=this.items.length-1;o>=0;o--)if(e.contains(this.containers[g].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!h||t(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))){c=this.items[o].item.offset()[l];d=!1;if(Math.abs(c-p)>Math.abs(c+this.items[o][u]-p)){d=!0;c+=this.items[o][u]}if(Math.abs(c-p)<s){s=Math.abs(c-p);a=this.items[o];this.direction=d?"up":"down"}}if(!a&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[g])return;a?this._rearrange(r,a,null,!0):this._rearrange(r,null,this.containers[g].element,!0);this._trigger("change",r,this._uiHash());this.containers[g]._trigger("change",r,this._uiHash(this));this.currentContainer=this.containers[g];this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t,this.currentItem])):"clone"===n.helper?this.currentItem.clone():this.currentItem;r.parents("body").length||e("parent"!==n.appendTo?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]);r[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")});(!r[0].style.width||n.forceHelperSize)&&r.width(this.currentItem.width());(!r[0].style.height||n.forceHelperSize)&&r.height(this.currentItem.height());return r},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" "));e.isArray(t)&&(t={left:+t[0],top:+t[1]||0});"left"in t&&(this.offset.click.left=t.left+this.margins.left);"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left);"top"in t&&(this.offset.click.top=t.top+this.margins.top);"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();if("absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])){t.left+=this.scrollParent.scrollLeft();t.top+=this.scrollParent.scrollTop()}(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0});return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,n,r,i=this.options;"parent"===i.containment&&(i.containment=this.helper[0].parentNode);("document"===i.containment||"window"===i.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e("document"===i.containment?document:window).width()-this.helperProportions.width-this.margins.left,(e("document"===i.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]);if(!/^(document|window|parent)$/.test(i.containment)){t=e(i.containment)[0];n=e(i.containment).offset();r="hidden"!==e(t).css("overflow");this.containment=[n.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(t,n){n||(n=this.position);var r="absolute"===t?1:-1,i="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i=this.options,o=t.pageX,s=t.pageY,a="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=/(html|body)/i.test(a[0].tagName);"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset());if(this.originalPosition){if(this.containment){t.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left);t.pageY-this.offset.click.top<this.containment[1]&&(s=this.containment[1]+this.offset.click.top);t.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left);t.pageY-this.offset.click.top>this.containment[3]&&(s=this.containment[3]+this.offset.click.top)}if(i.grid){n=this.originalPageY+Math.round((s-this.originalPageY)/i.grid[1])*i.grid[1];s=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n;r=this.originalPageX+Math.round((o-this.originalPageX)/i.grid[0])*i.grid[0];o=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r}}return{top:s-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():l?0:a.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():l?0:a.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i===this.counter&&this.refreshPositions(!r)})},_clear:function(e,t){function n(e,t,n){return function(r){n._trigger(e,r,t._uiHash(t))}}this.reverting=!1;var r,i=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(r in this._storedCSS)("auto"===this._storedCSS[r]||"static"===this._storedCSS[r])&&(this._storedCSS[r]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!t&&i.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))});!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||t||i.push(function(e){this._trigger("update",e,this._uiHash())});if(this!==this.currentContainer&&!t){i.push(function(e){this._trigger("remove",e,this._uiHash())});i.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer));i.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))}for(r=this.containers.length-1;r>=0;r--){t||i.push(n("deactivate",this,this.containers[r]));if(this.containers[r].containerCache.over){i.push(n("out",this,this.containers[r]));this.containers[r].containerCache.over=0}}if(this.storedCursor){this.document.find("body").css("cursor",this.storedCursor);this.storedStylesheet.remove()}this._storedOpacity&&this.helper.css("opacity",this._storedOpacity);this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex);this.dragging=!1;if(this.cancelHelperRemoval){if(!t){this._trigger("beforeStop",e,this._uiHash());for(r=0;r<i.length;r++)i[r].call(this,e);this._trigger("stop",e,this._uiHash())}this.fromOutside=!1;return!1}t||this._trigger("beforeStop",e,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!==this.currentItem[0]&&this.helper.remove();this.helper=null;if(!t){for(r=0;r<i.length;r++)i[r].call(this,e);this._trigger("stop",e,this._uiHash())}this.fromOutside=!1;return!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var n=t||this;return{helper:n.helper,placeholder:n.placeholder||e([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:t?t.element:null}}})})(t)},{"./core":59,"./mouse":60,"./widget":62,jquery:void 0}],62:[function(e,t){t.exports=e(7)},{"/home/lrd900/yasgui/yasgui/node_modules/jquery-ui/widget.js":7,jquery:void 0}],63:[function(t,n,r){(function(){var i;i=function(i){return"object"==typeof r&&"object"==typeof n?i(function(){try{return t("jquery")}catch(e){return window.jQuery}}()):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){return e.pivotUtilities.d3_renderers={Treemap:function(t,n){var r,i,o,s,a,l,u,p,c,d,h,f,g,m;o={localeStrings:{}};n=e.extend(o,n);l=e("<div style='width: 100%; height: 100%;'>");p={name:"All",children:[]};r=function(e,t,n){var i,o,s,a,l,u;if(0!==t.length){null==e.children&&(e.children=[]);s=t.shift();u=e.children;for(a=0,l=u.length;l>a;a++){i=u[a];if(i.name===s){r(i,t,n);return}}o={name:s};r(o,t,n);return e.children.push(o)}e.value=n};m=t.getRowKeys();for(f=0,g=m.length;g>f;f++){u=m[f];d=t.getAggregator(u,[]).value();null!=d&&r(p,u,d)}i=d3.scale.category10();h=e(window).width()/1.4;s=e(window).height()/1.4;a=10;c=d3.layout.treemap().size([h,s]).sticky(!0).value(function(e){return e.size});d3.select(l[0]).append("div").style("position","relative").style("width",h+2*a+"px").style("height",s+2*a+"px").style("left",a+"px").style("top",a+"px").datum(p).selectAll(".node").data(c.padding([15,0,0,0]).value(function(e){return e.value}).nodes).enter().append("div").attr("class","node").style("background",function(e){return null!=e.children?"lightgrey":i(e.name)}).text(function(e){return e.name}).call(function(){this.style("left",function(e){return e.x+"px"}).style("top",function(e){return e.y+"px"}).style("width",function(e){return Math.max(0,e.dx-1)+"px"}).style("height",function(e){return Math.max(0,e.dy-1)+"px"})});return l}}})}).call(this)},{jquery:void 0}],64:[function(t,n,r){(function(){var i;i=function(i){return"object"==typeof r&&"object"==typeof n?i(function(){try{return t("jquery")}catch(e){return window.jQuery}}()):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){var t;t=function(t,n){return function(r,i){var o,s,a,l,u,p,c,d,h,f,g,m,E,v,x,y,N,I,A,T,L,S,b,C,R;p={localeStrings:{vs:"vs",by:"by"}};i=e.extend(p,i);N=r.getRowKeys();0===N.length&&N.push([]);a=r.getColKeys();0===a.length&&a.push([]);f=function(){var e,t,n;n=[];for(e=0,t=N.length;t>e;e++){d=N[e];n.push(d.join("-"))}return n}();f.unshift("");m=0;l=[f];for(S=0,C=a.length;C>S;S++){s=a[S];x=[s.join("-")];m+=x[0].length;for(b=0,R=N.length;R>b;b++){y=N[b];o=r.getAggregator(y,s);x.push(null!=o.value()?o.value():null)}l.push(x)}I=T=r.aggregatorName+(r.valAttrs.length?"("+r.valAttrs.join(", ")+")":"");h=r.colAttrs.join("-");""!==h&&(I+=" "+i.localeStrings.vs+" "+h);c=r.rowAttrs.join("-");""!==c&&(I+=" "+i.localeStrings.by+" "+c);E={width:e(window).width()/1.4,height:e(window).height()/1.4,title:I,hAxis:{title:h,slantedText:m>50},vAxis:{title:T}};2===l[0].length&&""===l[0][1]&&(E.legend={position:"none"});for(g in n){A=n[g];E[g]=A}u=google.visualization.arrayToDataTable(l);v=e("<div style='width: 100%; height: 100%;'>");L=new google.visualization.ChartWrapper({dataTable:u,chartType:t,options:E});L.draw(v[0]);v.bind("dblclick",function(){var e;e=new google.visualization.ChartEditor;google.visualization.events.addListener(e,"ok",function(){return e.getChartWrapper().draw(v[0])});return e.openDialog(L)});return v}};return e.pivotUtilities.gchart_renderers={"Line Chart":t("LineChart"),"Bar Chart":t("ColumnChart"),"Stacked Bar Chart":t("ColumnChart",{isStacked:!0}),"Area Chart":t("AreaChart",{isStacked:!0})}})}).call(this)},{jquery:void 0}],65:[function(t,n,r){(function(){var i,o=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1},s=[].slice,a=function(e,t){return function(){return e.apply(t,arguments)}},l={}.hasOwnProperty;i=function(i){return"object"==typeof r&&"object"==typeof n?i(function(){try{return t("jquery")}catch(e){return window.jQuery}}()):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){var t,n,r,i,u,p,c,d,h,f,g,m,E,v,x,y;n=function(e,t,n){var r,i,o,s;e+="";i=e.split(".");o=i[0];s=i.length>1?n+i[1]:"";r=/(\d+)(\d{3})/;for(;r.test(o);)o=o.replace(r,"$1"+t+"$2");return o+s};f=function(t){var r;r={digitsAfterDecimal:2,scaler:1,thousandsSep:",",decimalSep:".",prefix:"",suffix:"",showZero:!1};t=e.extend(r,t);return function(e){var r;if(isNaN(e)||!isFinite(e))return"";if(0===e&&!t.showZero)return"";r=n((t.scaler*e).toFixed(t.digitsAfterDecimal),t.thousandsSep,t.decimalSep);return""+t.prefix+r+t.suffix}};E=f();v=f({digitsAfterDecimal:0});x=f({digitsAfterDecimal:1,scaler:100,suffix:"%"});r={count:function(e){null==e&&(e=v);return function(){return function(){return{count:0,push:function(){return this.count++},value:function(){return this.count},format:e}}}},countUnique:function(e){null==e&&(e=v);return function(t){var n;n=t[0];return function(){return{uniq:[],push:function(e){var t;return t=e[n],o.call(this.uniq,t)<0?this.uniq.push(e[n]):void 0},value:function(){return this.uniq.length},format:e,numInputs:null!=n?0:1}}}},listUnique:function(e){return function(t){var n;n=t[0];return function(){return{uniq:[],push:function(e){var t;return t=e[n],o.call(this.uniq,t)<0?this.uniq.push(e[n]):void 0},value:function(){return this.uniq.join(e)},format:function(e){return e},numInputs:null!=n?0:1}}}},sum:function(e){null==e&&(e=E);return function(t){var n;n=t[0];return function(){return{sum:0,push:function(e){return isNaN(parseFloat(e[n]))?void 0:this.sum+=parseFloat(e[n])},value:function(){return this.sum},format:e,numInputs:null!=n?0:1}}}},average:function(e){null==e&&(e=E);return function(t){var n;n=t[0];return function(){return{sum:0,len:0,push:function(e){if(!isNaN(parseFloat(e[n]))){this.sum+=parseFloat(e[n]);return this.len++}},value:function(){return this.sum/this.len},format:e,numInputs:null!=n?0:1}}}},sumOverSum:function(e){null==e&&(e=E);return function(t){var n,r;r=t[0],n=t[1];return function(){return{sumNum:0,sumDenom:0,push:function(e){isNaN(parseFloat(e[r]))||(this.sumNum+=parseFloat(e[r]));return isNaN(parseFloat(e[n]))?void 0:this.sumDenom+=parseFloat(e[n])},value:function(){return this.sumNum/this.sumDenom},format:e,numInputs:null!=r&&null!=n?0:2}}}},sumOverSumBound80:function(e,t){null==e&&(e=!0);null==t&&(t=E);return function(n){var r,i;i=n[0],r=n[1];return function(){return{sumNum:0,sumDenom:0,push:function(e){isNaN(parseFloat(e[i]))||(this.sumNum+=parseFloat(e[i]));return isNaN(parseFloat(e[r]))?void 0:this.sumDenom+=parseFloat(e[r])},value:function(){var t;t=e?1:-1;return(.821187207574908/this.sumDenom+this.sumNum/this.sumDenom+1.2815515655446004*t*Math.sqrt(.410593603787454/(this.sumDenom*this.sumDenom)+this.sumNum*(1-this.sumNum/this.sumDenom)/(this.sumDenom*this.sumDenom)))/(1+1.642374415149816/this.sumDenom)},format:t,numInputs:null!=i&&null!=r?0:2}}}},fractionOf:function(e,t,n){null==t&&(t="total");null==n&&(n=x);return function(){var r;r=1<=arguments.length?s.call(arguments,0):[];return function(i,o,s){return{selector:{total:[[],[]],row:[o,[]],col:[[],s]}[t],inner:e.apply(null,r)(i,o,s),push:function(e){return this.inner.push(e)},format:n,value:function(){return this.inner.value()/i.getAggregator.apply(i,this.selector).inner.value()},numInputs:e.apply(null,r)().numInputs}}}}};i=function(e){return{Count:e.count(v),"Count Unique Values":e.countUnique(v),"List Unique Values":e.listUnique(", "),Sum:e.sum(E),"Integer Sum":e.sum(v),Average:e.average(E),"Sum over Sum":e.sumOverSum(E),"80% Upper Bound":e.sumOverSumBound80(!0,E),"80% Lower Bound":e.sumOverSumBound80(!1,E),"Sum as Fraction of Total":e.fractionOf(e.sum(),"total",x),"Sum as Fraction of Rows":e.fractionOf(e.sum(),"row",x),"Sum as Fraction of Columns":e.fractionOf(e.sum(),"col",x),"Count as Fraction of Total":e.fractionOf(e.count(),"total",x),"Count as Fraction of Rows":e.fractionOf(e.count(),"row",x),"Count as Fraction of Columns":e.fractionOf(e.count(),"col",x)}}(r);m={Table:function(e,t){return g(e,t)},"Table Barchart":function(t,n){return e(g(t,n)).barchart()},Heatmap:function(t,n){return e(g(t,n)).heatmap()},"Row Heatmap":function(t,n){return e(g(t,n)).heatmap("rowheatmap")},"Col Heatmap":function(t,n){return e(g(t,n)).heatmap("colheatmap")}};c={en:{aggregators:i,renderers:m,localeStrings:{renderError:"An error occurred rendering the PivotTable results.",computeError:"An error occurred computing the PivotTable results.",uiRenderError:"An error occurred rendering the PivotTable UI.",selectAll:"Select All",selectNone:"Select None",tooMany:"(too many to list)",filterResults:"Filter results",totals:"Totals",vs:"vs",by:"by"}}};d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];y=function(e){return("0"+e).substr(-2,2)};p={bin:function(e,t){return function(n){return n[e]-n[e]%t}},dateFormat:function(e,t,n,r){null==n&&(n=d);null==r&&(r=u);return function(i){var o;o=new Date(Date.parse(i[e]));return isNaN(o)?"":t.replace(/%(.)/g,function(e,t){switch(t){case"y":return o.getFullYear();case"m":return y(o.getMonth()+1);case"n":return n[o.getMonth()];case"d":return y(o.getDate());case"w":return r[o.getDay()];case"x":return o.getDay();case"H":return y(o.getHours());case"M":return y(o.getMinutes());case"S":return y(o.getSeconds());default:return"%"+t}})}}};h=function(){return function(e,t){var n,r,i,o,s,a,l;a=/(\d+)|(\D+)/g;s=/\d/;l=/^0/;if("number"==typeof e||"number"==typeof t)return isNaN(e)?1:isNaN(t)?-1:e-t;n=String(e).toLowerCase();i=String(t).toLowerCase();if(n===i)return 0;if(!s.test(n)||!s.test(i))return n>i?1:-1;n=n.match(a);i=i.match(a);for(;n.length&&i.length;){r=n.shift();o=i.shift();if(r!==o)return s.test(r)&&s.test(o)?r.replace(l,".0")-o.replace(l,".0"):r>o?1:-1}return n.length-i.length}}(this);e.pivotUtilities={aggregatorTemplates:r,aggregators:i,renderers:m,derivers:p,locales:c,naturalSort:h,numberFormat:f};t=function(){function t(e,n){this.getAggregator=a(this.getAggregator,this);
this.getRowKeys=a(this.getRowKeys,this);this.getColKeys=a(this.getColKeys,this);this.sortKeys=a(this.sortKeys,this);this.arrSort=a(this.arrSort,this);this.natSort=a(this.natSort,this);this.aggregator=n.aggregator;this.aggregatorName=n.aggregatorName;this.colAttrs=n.cols;this.rowAttrs=n.rows;this.valAttrs=n.vals;this.tree={};this.rowKeys=[];this.colKeys=[];this.rowTotals={};this.colTotals={};this.allTotal=this.aggregator(this,[],[]);this.sorted=!1;t.forEachRecord(e,n.derivedAttributes,function(e){return function(t){return n.filter(t)?e.processRecord(t):void 0}}(this))}t.forEachRecord=function(t,n,r){var i,o,s,a,u,p,c,d,h,f,g,m;i=e.isEmptyObject(n)?r:function(e){var t,i,o;for(t in n){i=n[t];e[t]=null!=(o=i(e))?o:e[t]}return r(e)};if(e.isFunction(t))return t(i);if(e.isArray(t)){if(e.isArray(t[0])){g=[];for(s in t)if(l.call(t,s)){o=t[s];if(s>0){p={};f=t[0];for(a in f)if(l.call(f,a)){u=f[a];p[u]=o[a]}g.push(i(p))}}return g}m=[];for(d=0,h=t.length;h>d;d++){p=t[d];m.push(i(p))}return m}if(t instanceof jQuery){c=[];e("thead > tr > th",t).each(function(){return c.push(e(this).text())});return e("tbody > tr",t).each(function(){p={};e("td",this).each(function(t){return p[c[t]]=e(this).text()});return i(p)})}throw new Error("unknown input format")};t.convertToArray=function(e){var n;n=[];t.forEachRecord(e,{},function(e){return n.push(e)});return n};t.prototype.natSort=function(e,t){return h(e,t)};t.prototype.arrSort=function(e,t){return this.natSort(e.join(),t.join())};t.prototype.sortKeys=function(){if(!this.sorted){this.rowKeys.sort(this.arrSort);this.colKeys.sort(this.arrSort)}return this.sorted=!0};t.prototype.getColKeys=function(){this.sortKeys();return this.colKeys};t.prototype.getRowKeys=function(){this.sortKeys();return this.rowKeys};t.prototype.processRecord=function(e){var t,n,r,i,o,s,a,l,u,p,c,d,h;t=[];i=[];p=this.colAttrs;for(s=0,l=p.length;l>s;s++){o=p[s];t.push(null!=(c=e[o])?c:"null")}d=this.rowAttrs;for(a=0,u=d.length;u>a;a++){o=d[a];i.push(null!=(h=e[o])?h:"null")}r=i.join(String.fromCharCode(0));n=t.join(String.fromCharCode(0));this.allTotal.push(e);if(0!==i.length){if(!this.rowTotals[r]){this.rowKeys.push(i);this.rowTotals[r]=this.aggregator(this,i,[])}this.rowTotals[r].push(e)}if(0!==t.length){if(!this.colTotals[n]){this.colKeys.push(t);this.colTotals[n]=this.aggregator(this,[],t)}this.colTotals[n].push(e)}if(0!==t.length&&0!==i.length){this.tree[r]||(this.tree[r]={});this.tree[r][n]||(this.tree[r][n]=this.aggregator(this,i,t));return this.tree[r][n].push(e)}};t.prototype.getAggregator=function(e,t){var n,r,i;i=e.join(String.fromCharCode(0));r=t.join(String.fromCharCode(0));n=0===e.length&&0===t.length?this.allTotal:0===e.length?this.colTotals[r]:0===t.length?this.rowTotals[i]:this.tree[i][r];return null!=n?n:{value:function(){return null},format:function(){return""}}};return t}();g=function(t,n){var r,i,o,s,a,u,p,c,d,h,f,g,m,E,v,x,y,N,I,A,T;u={localeStrings:{totals:"Totals"}};n=e.extend(u,n);o=t.colAttrs;f=t.rowAttrs;m=t.getRowKeys();a=t.getColKeys();h=document.createElement("table");h.className="pvtTable";E=function(e,t,n){var r,i,o,s,a,l;if(0!==t){i=!0;for(s=a=0;n>=0?n>=a:a>=n;s=n>=0?++a:--a)e[t-1][s]!==e[t][s]&&(i=!1);if(i)return-1}r=0;for(;t+r<e.length;){o=!1;for(s=l=0;n>=0?n>=l:l>=n;s=n>=0?++l:--l)e[t][s]!==e[t+r][s]&&(o=!0);if(o)break;r++}return r};for(c in o)if(l.call(o,c)){i=o[c];N=document.createElement("tr");if(0===parseInt(c)&&0!==f.length){x=document.createElement("th");x.setAttribute("colspan",f.length);x.setAttribute("rowspan",o.length);N.appendChild(x)}x=document.createElement("th");x.className="pvtAxisLabel";x.textContent=i;N.appendChild(x);for(p in a)if(l.call(a,p)){s=a[p];T=E(a,parseInt(p),parseInt(c));if(-1!==T){x=document.createElement("th");x.className="pvtColLabel";x.textContent=s[c];x.setAttribute("colspan",T);parseInt(c)===o.length-1&&0!==f.length&&x.setAttribute("rowspan",2);N.appendChild(x)}}if(0===parseInt(c)){x=document.createElement("th");x.className="pvtTotalLabel";x.innerHTML=n.localeStrings.totals;x.setAttribute("rowspan",o.length+(0===f.length?0:1));N.appendChild(x)}h.appendChild(N)}if(0!==f.length){N=document.createElement("tr");for(p in f)if(l.call(f,p)){d=f[p];x=document.createElement("th");x.className="pvtAxisLabel";x.textContent=d;N.appendChild(x)}x=document.createElement("th");if(0===o.length){x.className="pvtTotalLabel";x.innerHTML=n.localeStrings.totals}N.appendChild(x);h.appendChild(N)}for(p in m)if(l.call(m,p)){g=m[p];N=document.createElement("tr");for(c in g)if(l.call(g,c)){I=g[c];T=E(m,parseInt(p),parseInt(c));if(-1!==T){x=document.createElement("th");x.className="pvtRowLabel";x.textContent=I;x.setAttribute("rowspan",T);parseInt(c)===f.length-1&&0!==o.length&&x.setAttribute("colspan",2);N.appendChild(x)}}for(c in a)if(l.call(a,c)){s=a[c];r=t.getAggregator(g,s);A=r.value();v=document.createElement("td");v.className="pvtVal row"+p+" col"+c;v.innerHTML=r.format(A);v.setAttribute("data-value",A);N.appendChild(v)}y=t.getAggregator(g,[]);A=y.value();v=document.createElement("td");v.className="pvtTotal rowTotal";v.innerHTML=y.format(A);v.setAttribute("data-value",A);v.setAttribute("data-for","row"+p);N.appendChild(v);h.appendChild(N)}N=document.createElement("tr");x=document.createElement("th");x.className="pvtTotalLabel";x.innerHTML=n.localeStrings.totals;x.setAttribute("colspan",f.length+(0===o.length?0:1));N.appendChild(x);for(c in a)if(l.call(a,c)){s=a[c];y=t.getAggregator([],s);A=y.value();v=document.createElement("td");v.className="pvtTotal colTotal";v.innerHTML=y.format(A);v.setAttribute("data-value",A);v.setAttribute("data-for","col"+c);N.appendChild(v)}y=t.getAggregator([],[]);A=y.value();v=document.createElement("td");v.className="pvtGrandTotal";v.innerHTML=y.format(A);v.setAttribute("data-value",A);N.appendChild(v);h.appendChild(N);h.setAttribute("data-numrows",m.length);h.setAttribute("data-numcols",a.length);return h};e.fn.pivot=function(n,i){var o,s,a,l,u;o={cols:[],rows:[],filter:function(){return!0},aggregator:r.count()(),aggregatorName:"Count",derivedAttributes:{},renderer:g,rendererOptions:null,localeStrings:c.en.localeStrings};i=e.extend(o,i);l=null;try{a=new t(n,i);try{l=i.renderer(a,i.rendererOptions)}catch(p){s=p;"undefined"!=typeof console&&null!==console&&console.error(s.stack);l=e("<span>").html(i.localeStrings.renderError)}}catch(p){s=p;"undefined"!=typeof console&&null!==console&&console.error(s.stack);l=e("<span>").html(i.localeStrings.computeError)}u=this[0];for(;u.hasChildNodes();)u.removeChild(u.lastChild);return this.append(l)};e.fn.pivotUI=function(n,r,i,s){var a,u,p,d,f,g,m,E,v,x,y,N,I,A,T,L,S,b,C,R,w,O,_,F,P,k,M,D,G,j,U,q,B,V,H,z,W,$,K;null==i&&(i=!1);null==s&&(s="en");m={derivedAttributes:{},aggregators:c[s].aggregators,renderers:c[s].renderers,hiddenAttributes:[],menuLimit:200,cols:[],rows:[],vals:[],exclusions:{},unusedAttrsVertical:"auto",autoSortUnusedAttrs:!1,rendererOptions:{localeStrings:c[s].localeStrings},onRefresh:null,filter:function(){return!0},localeStrings:c[s].localeStrings};v=this.data("pivotUIOptions");I=null==v||i?e.extend(m,r):v;try{n=t.convertToArray(n);R=function(){var e,t;e=n[0];t=[];for(N in e)l.call(e,N)&&t.push(N);return t}();H=I.derivedAttributes;for(f in H)l.call(H,f)&&o.call(R,f)<0&&R.push(f);d={};for(M=0,U=R.length;U>M;M++){P=R[M];d[P]={}}t.forEachRecord(n,I.derivedAttributes,function(e){var t,n,r;r=[];for(N in e)if(l.call(e,N)){t=e[N];if(I.filter(e)){null==t&&(t="null");null==(n=d[N])[t]&&(n[t]=0);r.push(d[N][t]++)}}return r});_=e("<table cellpadding='5'>");b=e("<td>");S=e("<select class='pvtRenderer'>").appendTo(b).bind("change",function(){return T()});z=I.renderers;for(P in z)l.call(z,P)&&e("<option>").val(P).html(P).appendTo(S);g=e("<td class='pvtAxisContainer pvtUnused'>");C=function(){var e,t,n;n=[];for(e=0,t=R.length;t>e;e++){f=R[e];o.call(I.hiddenAttributes,f)<0&&n.push(f)}return n}();F=!1;if("auto"===I.unusedAttrsVertical){p=0;for(D=0,q=C.length;q>D;D++){a=C[D];p+=a.length}F=p>120}g.addClass(I.unusedAttrsVertical===!0||F?"pvtVertList":"pvtHorizList");k=function(t){var n,r,i,s,a,l,u,p,c,f,m,E,v,y,A;u=function(){var e;e=[];for(N in d[t])e.push(N);return e}();l=!1;E=e("<div>").addClass("pvtFilterBox").hide();E.append(e("<h4>").text(""+t+" ("+u.length+")"));if(u.length>I.menuLimit)E.append(e("<p>").html(I.localeStrings.tooMany));else{r=e("<p>").appendTo(E);r.append(e("<button>").html(I.localeStrings.selectAll).bind("click",function(){return E.find("input:visible").prop("checked",!0)}));r.append(e("<button>").html(I.localeStrings.selectNone).bind("click",function(){return E.find("input:visible").prop("checked",!1)}));r.append(e("<input>").addClass("pvtSearch").attr("placeholder",I.localeStrings.filterResults).bind("keyup",function(){var t;t=e(this).val().toLowerCase();return e(this).parents(".pvtFilterBox").find("label span").each(function(){var n;n=e(this).text().toLowerCase().indexOf(t);return-1!==n?e(this).parent().show():e(this).parent().hide()})}));i=e("<div>").addClass("pvtCheckContainer").appendTo(E);A=u.sort(h);for(v=0,y=A.length;y>v;v++){N=A[v];m=d[t][N];s=e("<label>");a=I.exclusions[t]?o.call(I.exclusions[t],N)>=0:!1;l||(l=a);e("<input type='checkbox' class='pvtFilter'>").attr("checked",!a).data("filter",[t,N]).appendTo(s);s.append(e("<span>").text(""+N+" ("+m+")"));i.append(e("<p>").append(s))}}f=function(){var t;t=e(E).find("[type='checkbox']").length-e(E).find("[type='checkbox']:checked").length;t>0?n.addClass("pvtFilteredAttribute"):n.removeClass("pvtFilteredAttribute");return u.length>I.menuLimit?E.toggle():E.toggle(0,T)};e("<p>").appendTo(E).append(e("<button>").text("OK").bind("click",f));p=function(t){E.css({left:t.pageX,top:t.pageY}).toggle();e(".pvtSearch").val("");return e("label").show()};c=e("<span class='pvtTriangle'>").html(" ▾").bind("click",p);n=e("<li class='axis_"+x+"'>").append(e("<span class='pvtAttr'>").text(t).data("attrName",t).append(c));l&&n.addClass("pvtFilteredAttribute");g.append(n).append(E);return n.bind("dblclick",p)};for(x in C){f=C[x];k(f)}w=e("<tr>").appendTo(_);u=e("<select class='pvtAggregator'>").bind("change",function(){return T()});W=I.aggregators;for(P in W)l.call(W,P)&&u.append(e("<option>").val(P).html(P));e("<td class='pvtVals'>").appendTo(w).append(u).append(e("<br>"));e("<td class='pvtAxisContainer pvtHorizList pvtCols'>").appendTo(w);O=e("<tr>").appendTo(_);O.append(e("<td valign='top' class='pvtAxisContainer pvtRows'>"));A=e("<td valign='top' class='pvtRendererArea'>").appendTo(O);if(I.unusedAttrsVertical===!0||F){_.find("tr:nth-child(1)").prepend(b);_.find("tr:nth-child(2)").prepend(g)}else _.prepend(e("<tr>").append(b).append(g));this.html(_);$=I.cols;for(G=0,B=$.length;B>G;G++){P=$[G];this.find(".pvtCols").append(this.find(".axis_"+C.indexOf(P)))}K=I.rows;for(j=0,V=K.length;V>j;j++){P=K[j];this.find(".pvtRows").append(this.find(".axis_"+C.indexOf(P)))}null!=I.aggregatorName&&this.find(".pvtAggregator").val(I.aggregatorName);null!=I.rendererName&&this.find(".pvtRenderer").val(I.rendererName);y=!0;L=function(t){return function(){var r,i,s,a,l,p,c,d,h,f,g,m,E,v;d={derivedAttributes:I.derivedAttributes,localeStrings:I.localeStrings,rendererOptions:I.rendererOptions,cols:[],rows:[]};l=null!=(v=I.aggregators[u.val()]([])().numInputs)?v:0;f=[];t.find(".pvtRows li span.pvtAttr").each(function(){return d.rows.push(e(this).data("attrName"))});t.find(".pvtCols li span.pvtAttr").each(function(){return d.cols.push(e(this).data("attrName"))});t.find(".pvtVals select.pvtAttrDropdown").each(function(){if(0===l)return e(this).remove();l--;return""!==e(this).val()?f.push(e(this).val()):void 0});if(0!==l){c=t.find(".pvtVals");for(P=m=0;l>=0?l>m:m>l;P=l>=0?++m:--m){a=e("<select class='pvtAttrDropdown'>").append(e("<option>")).bind("change",function(){return T()});for(E=0,g=C.length;g>E;E++){r=C[E];a.append(e("<option>").val(r).text(r))}c.append(a)}}if(y){f=I.vals;x=0;t.find(".pvtVals select.pvtAttrDropdown").each(function(){e(this).val(f[x]);return x++});y=!1}d.aggregatorName=u.val();d.vals=f;d.aggregator=I.aggregators[u.val()](f);d.renderer=I.renderers[S.val()];i={};t.find("input.pvtFilter").not(":checked").each(function(){var t;t=e(this).data("filter");return null!=i[t[0]]?i[t[0]].push(t[1]):i[t[0]]=[t[1]]});d.filter=function(e){var t,n;if(!I.filter(e))return!1;for(N in i){t=i[N];if(n=""+e[N],o.call(t,n)>=0)return!1}return!0};A.pivot(n,d);p=e.extend(I,{cols:d.cols,rows:d.rows,vals:f,exclusions:i,aggregatorName:u.val(),rendererName:S.val()});t.data("pivotUIOptions",p);if(I.autoSortUnusedAttrs){s=e.pivotUtilities.naturalSort;h=t.find("td.pvtUnused.pvtAxisContainer");e(h).children("li").sort(function(t,n){return s(e(t).text(),e(n).text())}).appendTo(h)}A.css("opacity",1);return null!=I.onRefresh?I.onRefresh(p):void 0}}(this);T=function(){return function(){A.css("opacity",.5);return setTimeout(L,10)}}(this);T();this.find(".pvtAxisContainer").sortable({update:function(e,t){return null==t.sender?T():void 0},connectWith:this.find(".pvtAxisContainer"),items:"li",placeholder:"pvtPlaceholder"})}catch(Y){E=Y;"undefined"!=typeof console&&null!==console&&console.error(E.stack);this.html(I.localeStrings.uiRenderError)}return this};e.fn.heatmap=function(t){var n,r,i,o,s,a,l,u;null==t&&(t="heatmap");a=this.data("numrows");s=this.data("numcols");n=function(e,t,n){var r;r=function(){switch(e){case"red":return function(e){return"ff"+e+e};case"green":return function(e){return""+e+"ff"+e};case"blue":return function(e){return""+e+e+"ff"}}}();return function(e){var i,o;o=255-Math.round(255*(e-t)/(n-t));i=o.toString(16).split(".")[0];1===i.length&&(i=0+i);return r(i)}};r=function(t){return function(r,i){var o,s,a;s=function(n){return t.find(r).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?n(t,e(this)):void 0})};a=[];s(function(e){return a.push(e)});o=n(i,Math.min.apply(Math,a),Math.max.apply(Math,a));return s(function(e,t){return t.css("background-color","#"+o(e))})}}(this);switch(t){case"heatmap":r(".pvtVal","red");break;case"rowheatmap":for(i=l=0;a>=0?a>l:l>a;i=a>=0?++l:--l)r(".pvtVal.row"+i,"red");break;case"colheatmap":for(o=u=0;s>=0?s>u:u>s;o=s>=0?++u:--u)r(".pvtVal.col"+o,"red")}r(".pvtTotal.rowTotal","red");r(".pvtTotal.colTotal","red");return this};return e.fn.barchart=function(){var t,n,r,i,o;i=this.data("numrows");r=this.data("numcols");t=function(t){return function(n){var r,i,o,s;r=function(r){return t.find(n).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?r(t,e(this)):void 0})};s=[];r(function(e){return s.push(e)});i=Math.max.apply(Math,s);o=function(e){return 100*e/(1.4*i)};return r(function(t,n){var r,i;r=n.text();i=e("<div>").css({position:"relative",height:"55px"});i.append(e("<div>").css({position:"absolute",bottom:0,left:0,right:0,height:o(t)+"%","background-color":"gray"}));i.append(e("<div>").text(r).css({position:"relative","padding-left":"5px","padding-right":"5px"}));return n.css({padding:0,"padding-top":"5px","text-align":"center"}).html(i)})}}(this);for(n=o=0;i>=0?i>o:o>i;n=i>=0?++o:--o)t(".pvtVal.row"+n);t(".pvtTotal.colTotal");return this}})}).call(this)},{jquery:void 0}],66:[function(e,t){t.exports=e(12)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/node_modules/store/store.js":12}],67:[function(e,t){t.exports=e(13)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/package.json":13}],68:[function(e,t){t.exports=e(14)},{"../package.json":67,"./storage.js":69,"./svg.js":70,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/main.js":14}],69:[function(e,t){t.exports=e(15)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/storage.js":15,store:66}],70:[function(e,t){t.exports=e(16)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/svg.js":16}],71:[function(e,t){t.exports={name:"yasgui-yasr",description:"Yet Another SPARQL Resultset GUI",version:"2.4.12",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasr.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasr.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1","gulp-html-replace":"^1.4.1","browserify-shim":"^3.8.1"},bugs:"https://github.com/YASGUI/YASR/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASR.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1",pivottable:"^1.2.2","jquery-ui":"^1.10.5",d3:"^3.4.13"},"browserify-shim":{google:"global:google"},browserify:{transform:["browserify-shim"]},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"},"../lib/DataTables/media/js/jquery.dataTables.js":{require:"datatables",global:"jQuery"},datatables:{require:"datatables",global:"jQuery"},d3:{require:"d3",global:"d3"},"jquery-ui/sortable":{require:"jquery-ui/sortable",global:"jQuery"},pivottable:{require:"pivottable",global:"jQuery"}}}},{}],72:[function(e,t){"use strict";t.exports=function(e){var t='"',n=",",r="\n",i=e.head.vars,o=e.results.bindings,s=function(){for(var e=0;e<i.length;e++)u(i[e]);c+=r},a=function(){for(var e=0;e<o.length;e++){l(o[e]);c+=r}},l=function(e){for(var t=0;t<i.length;t++){var n=i[t];u(e.hasOwnProperty(n)?e[n].value:"")}},u=function(e){e.replace(t,t+t);p(e)&&(e=t+e+t);c+=" "+e+" "+n},p=function(e){var r=!1;e.match("[\\w|"+n+"|"+t+"]")&&(r=!0);return r},c="";s();a();return c}},{}],73:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=t.exports=function(t){var r=n("<div class='booleanResult'></div>"),i=function(){r.empty().appendTo(t.resultsContainer);var i=t.results.getBoolean(),o=null,s=null;if(i===!0){o="check";s="True"}else if(i===!1){o="cross";s="False"}else{r.width("140");s="Could not find boolean value in response"}o&&e("yasgui-utils").svg.draw(r,e("./imgs.js")[o]);n("<span></span>").text(s).appendTo(r)},o=function(){return t.results.getBoolean&&(t.results.getBoolean()===!0||0==t.results.getBoolean())};return{name:null,draw:i,hideFromSelection:!0,getPriority:10,canHandleResults:o}};r.version={"YASR-boolean":e("../package.json").version,jquery:n.fn.jquery}},{"../package.json":71,"./imgs.js":79,jquery:void 0,"yasgui-utils":68}],74:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports={output:"table",useGoogleCharts:!0,outputPlugins:["table","error","boolean","rawResponse"],drawOutputSelector:!0,drawDownloadIcon:!0,getUsedPrefixes:null,persistency:{prefix:function(e){return"yasr_"+n(e.container).closest("[id]").attr("id")+"_"},outputSelector:function(){return"selector"},results:{id:function(e){return"results_"+n(e.container).closest("[id]").attr("id")},key:"results",maxSize:1e5}}}},{jquery:void 0}],75:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=t.exports=function(e){var t=n("<div class='errorResult'></div>"),i=n.extend(!0,{},r.defaults),o=function(){var e=null;if(i.tryQueryLink){var t=i.tryQueryLink();e=n("<button>",{"class":"yasr_btn yasr_tryQuery"}).text("Try query in new browser window").click(function(){window.open(t,"_blank");n(this).blur()})}return e},s=function(){var r=e.results.getException();t.empty().appendTo(e.resultsContainer);var s=n("<div>",{"class":"errorHeader"}).appendTo(t);if(0!==r.status){var a="Error";r.statusText&&r.statusText.length<100&&(a=r.statusText);a+=" (#"+r.status+")";s.append(n("<span>",{"class":"exception"}).text(a)).append(o());var l=null;r.responseText?l=r.responseText:"string"==typeof r&&(l=r);l&&t.append(n("<pre>").text(l))}else{s.append(o());t.append(n("<div>",{"class":"corsMessage"}).append(i.corsMessage))}},a=function(e){return e.results.getException()||!1};return{name:null,draw:s,getPriority:20,hideFromSelection:!0,canHandleResults:a}};r.defaults={corsMessage:"Unable to get response from endpoint",tryQueryLink:null}},{jquery:void 0}],76:[function(e,t){t.exports={GoogleTypeException:function(e,t){this.foundTypes=e;this.varName=t;this.toString=function(){var e="Conflicting data types found for variable "+this.varName+'. Assuming all values of this variable are "string".';e+=" To avoid this issue, cast the values in your SPARQL query to the intended xsd datatype";return e};this.toHtml=function(){var e="Conflicting data types found for variable <i>"+this.varName+'</i>. Assuming all values of this variable are "string".';e+=" As a result, several Google Charts will not render values of this particular variable.";e+=" To avoid this issue, cast the values in your SPARQL query to the intended xsd datatype";return e}}}},{}],77:[function(e,t){(function(n){var r=e("events").EventEmitter,i=(function(){try{return e("jquery")}catch(t){return window.jQuery}}(),!1),o=!1,s=function(){r.call(this);var e=this;this.init=function(){if(o||("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)||i)("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)?e.emit("initDone"):o&&e.emit("initError");else{i=!0;a("http://google.com/jsapi",function(){i=!1;e.emit("initDone")});var t=100,r=6e3,s=+new Date,l=function(){if(!("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null))if(+new Date-s>r){o=!0;i=!1;e.emit("initError")}else setTimeout(l,t)};l()}};this.googleLoad=function(){var t=function(){("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null).load("visualization","1",{packages:["corechart","charteditor"],callback:function(){e.emit("done")}})};if(i){e.once("initDone",t);e.once("initError",function(){e.emit("error","Could not load google loader")})}else if("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)t();else if(o)e.emit("error","Could not load google loader");else{e.once("initDone",t);e.once("initError",function(){e.emit("error","Could not load google loader")})}}},a=function(e,t){var n=document.createElement("script");n.type="text/javascript";n.readyState?n.onreadystatechange=function(){if("loaded"==n.readyState||"complete"==n.readyState){n.onreadystatechange=null;t()}}:n.onload=function(){t()};n.src=e;document.body.appendChild(n)};s.prototype=new r;t.exports=new s}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{events:2,jquery:void 0}],78:[function(e,t){(function(n){"use strict";function r(e,t,n){function r(e,t,o){var l,u,p,c,d,h,f,g;if(null==e||null==t)return e===t;if(e.__placeholder__||t.__placeholder__)return!0;if(e===t)return 0!==e||1/e==1/t;l=i.call(e);if(i.call(t)!=l)return!1;switch(l){case"[object String]":return e==String(t);case"[object Number]":return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object RegExp]":return e.source==t.source&&e.global==t.global&&e.multiline==t.multiline&&e.ignoreCase==t.ignoreCase}if("object"!=typeof e||"object"!=typeof t)return!1;u=o.length;for(;u--;)if(o[u]==e)return!0;o.push(e);p=0;c=!0;if("[object Array]"==l){d=e.length;h=t.length;if(a){switch(n){case"===":c=d===h;break;case"<==":c=h>=d;break;case"<<=":c=h>d}p=d;a=!1}else{c=d===h;p=d}if(c)for(;p--&&(c=p in e==p in t&&r(e[p],t[p],o)););}else{if("constructor"in e!="constructor"in t||e.constructor!=t.constructor)return!1;for(f in e)if(s(e,f)){p++;if(!(c=s(t,f)&&r(e[f],t[f],o)))break}if(c){g=0;for(f in t)s(t,f)&&++g;if(a)c="<<="===n?g>p:"<=="===n?g>=p:p===g;else{a=!1;c=p===g}}}o.pop();return c}var i={}.toString,o={}.hasOwnProperty,s=function(e,t){return o.call(e,t)},a=!0;return r(e,t,[])}var i=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),o=e("./utils.js"),s=e("yasgui-utils"),a=t.exports=function(t){var l=i.extend(!0,{},a.defaults),u=t.container.closest("[id]").attr("id");null==t.options.gchart&&(t.options.gchart={});var p=t.getPersistencyId("motionchart"),c=t.getPersistencyId("chartConfig");null==t.options.gchart.motionChartState&&(t.options.gchart.motionChartState=s.storage.get(p));null==t.options.gchart.chartConfig&&(t.options.gchart.chartConfig=s.storage.get(c));var d=null,h=function(e){var i="undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null;d=new i.visualization.ChartEditor;i.visualization.events.addListener(d,"ok",function(){var e,n;e=d.getChartWrapper();if(!r(e.getChartType,"MotionChart","===")){t.options.gchart.motionChartState=e.n;s.storage.set(p,t.options.gchart.motionChartState);e.setOption("state",t.options.gchart.motionChartState);i.visualization.events.addListener(e,"ready",function(){var n;n=e.getChart();i.visualization.events.addListener(n,"statechange",function(){t.options.gchart.motionChartState=n.getState();s.storage.set(p,t.options.gchart.motionChartState)})})}n=e.getDataTable();e.setDataTable(null);t.options.gchart.chartConfig=e.toJSON();s.storage.set(c,t.options.gchart.chartConfig);e.setDataTable(n);e.draw();t.updateHeader()});e&&e()};return{name:"Google Chart",hideFromSelection:!1,priority:7,canHandleResults:function(e){var t,n;return null!=(t=e.results)&&(n=t.getVariables())&&n.length>0},getDownloadInfo:function(){if(!t.results)return null;var e=t.resultsContainer.find("svg");if(e.length>0)return{getContent:function(){return e[0].outerHTML?e[0].outerHTML:i("<div>").append(e.clone()).html()},filename:"queryResults.svg",contentType:"image/svg+xml",buttonTitle:"Download SVG Image"};var n=t.resultsContainer.find(".google-visualization-table-table");return n.length>0?{getContent:function(){return n.tableToCsv()},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:void 0},getEmbedHtml:function(){if(!t.results)return null;var e=t.resultsContainer.find("svg").clone().removeAttr("height").removeAttr("width").css("height","").css("width","");if(0==e.length)return null;var n=e[0].outerHTML;n||(n=i("<div>").append(e.clone()).html());return'<div style="width: 800px; height: 600px;">\n'+n+"\n</div>"},draw:function(){var r=function(){t.resultsContainer.empty();var n=u+"_gchartWrapper",r=null;t.resultsContainer.append(i("<button>",{"class":"openGchartBtn yasr_btn"}).text("Chart Config").click(function(){d.openDialog(r)})).append(i("<div>",{id:n,"class":"gchartWrapper"}));var a=new google.visualization.DataTable,c=t.results.getAsJson();c.head.vars.forEach(function(n){var r="string";try{r=o.getGoogleTypeForBindings(c.results.bindings,n)}catch(i){if(!(i instanceof e("./exceptions.js").GoogleTypeException))throw i;t.warn(i.toHtml())}a.addColumn(r,n)});var h=null;t.options.getUsedPrefixes&&(h="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);c.results.bindings.forEach(function(e){var t=[];c.head.vars.forEach(function(n,r){t.push(o.castGoogleType(e[n],h,a.getColumnType(r)))});a.addRow(t)});if(t.options.gchart.chartConfig){r=new google.visualization.ChartWrapper(t.options.gchart.chartConfig);if("MotionChart"===r.getChartType()&&null!=t.options.gchart.motionChartState){r.setOption("state",t.options.gchart.motionChartState);google.visualization.events.addListener(r,"ready",function(){var e;e=r.getChart();google.visualization.events.addListener(e,"statechange",function(){t.options.gchart.motionChartState=e.getState();s.storage.set(p,t.options.gchart.motionChartState)})})}r.setDataTable(a)}else r=new google.visualization.ChartWrapper({chartType:"Table",dataTable:a,containerId:n});r.setOption("width",l.width);r.setOption("height",l.height);r.draw();t.updateHeader()};("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)&&("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null).visualization&&d?r():e("./gChartLoader.js").on("done",function(){h();r()}).on("error",function(){console.log("errorrr")}).googleLoad()}}};a.defaults={height:"600px",width:"100%",persistencyId:"gchart"}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./exceptions.js":76,"./gChartLoader.js":77,"./utils.js":92,jquery:void 0,"yasgui-utils":68}],79:[function(e,t){"use strict";t.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',move:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_11656_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="753" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="287" inkscape:window-y="249" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><polygon points="33,83 50,100 67,83 54,83 54,17 67,17 50,0 33,17 46,17 46,83 " transform="translate(-7.962963,-10)" /><polygon points="83,67 100,50 83,33 83,46 17,46 17,33 0,50 17,67 17,54 83,54 " transform="translate(-7.962963,-10)" /></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}
},{}],80:[function(e){e("./tableToCsv.js")},{"./tableToCsv.js":81}],81:[function(e){"use strict";var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.fn.tableToCsv=function(e){var n="";e=t.extend({quote:'"',delimiter:",",lineBreak:"\n"},e);var r=function(t){var n=!1;t.match("[\\w|"+e.delimiter+"|"+e.quote+"]")&&(n=!0);return n},i=function(t){t.replace(e.quote,e.quote+e.quote);r(t)&&(t=e.quote+t+e.quote);n+=" "+t+" "+e.delimiter},o=function(t){t.forEach(function(e){i(e)});n+=e.lineBreak},s=t(this),a={},l=0;s.find("tr:first *").each(function(){t(this).attr("colspan")?l+=+t(this).attr("colspan"):l++});s.find("tr").each(function(e,n){for(var r=t(n),i=[],s=0,u=0;l>u+s;u++)if(a[u]){i.push(a[u].text);a[u].rowSpan--;a[u].rowSpan||delete a[u]}else{var p=r.find(":nth-child("+(u+1)+")");console.log(p);var c=p.attr("colspan"),d=p.attr("rowspan");if(c&&!isNaN(c)){for(var h=0;c>h;h++)i.push(p.text());s+=c-1}else if(d&&!isNaN(d)){a[u+s]={rowSpan:d-1,text:p.text()};i.push(p.text());s++}else i.push(p.text())}o(i)});return n}},{jquery:void 0}],82:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("yasgui-utils");console=console||{log:function(){}};e("./jquery/extendJquery.js");var i=t.exports=function(t,o,s){var a={};a.options=n.extend(!0,{},i.defaults,o);a.container=n("<div class='yasr'></div>").appendTo(t);a.header=n("<div class='yasr_header'></div>").appendTo(a.container);a.resultsContainer=n("<div class='yasr_results'></div>").appendTo(a.container);a.storage=r.storage;var l=null;a.getPersistencyId=function(e){null===l&&(l=a.options.persistency&&a.options.persistency.prefix?"string"==typeof a.options.persistency.prefix?a.options.persistency.prefix:a.options.persistency.prefix(a):!1);return l&&e?l+("string"==typeof e?e:e(a)):null};a.options.useGoogleCharts&&e("./gChartLoader.js").once("initError",function(){a.options.useGoogleCharts=!1}).init();a.plugins={};for(var u in i.plugins)(a.options.useGoogleCharts||"gchart"!=u)&&(a.plugins[u]=new i.plugins[u](a));a.updateHeader=function(){var e=a.header.find(".yasr_downloadIcon").removeAttr("title"),t=a.header.find(".yasr_embedBtn"),n=a.plugins[a.options.output];if(n){var r=n.getDownloadInfo?n.getDownloadInfo():null;if(r){r.buttonTitle&&e.attr("title",r.buttonTitle);e.prop("disabled",!1);e.find("path").each(function(){this.style.fill="black"})}else{e.prop("disabled",!0).prop("title","Download not supported for this result representation");e.find("path").each(function(){this.style.fill="gray"})}var i=null;n.getEmbedHtml&&(i=n.getEmbedHtml());i&&i.length>0?t.show():t.hide()}};a.draw=function(e){if(!a.results)return!1;e||(e=a.options.output);var t=null,r=-1,i=[];for(var o in a.plugins)if(a.plugins[o].canHandleResults(a)){var s=a.plugins[o].getPriority;"function"==typeof s&&(s=s(a));if(null!=s&&void 0!=s&&s>r){r=s;t=o}}else i.push(o);p(i);if(e in a.plugins&&a.plugins[e].canHandleResults(a)){n(a.resultsContainer).empty();a.plugins[e].draw();return!0}if(t){n(a.resultsContainer).empty();a.plugins[t].draw();return!0}return!1};var p=function(e){a.header.find(".yasr_btnGroup .yasr_btn").removeClass("disabled");e.forEach(function(e){a.header.find(".yasr_btnGroup .select_"+e).addClass("disabled")})};a.somethingDrawn=function(){return!a.resultsContainer.is(":empty")};a.setResponse=function(t,n,i){try{a.results=e("./parsers/wrapper.js")(t,n,i)}catch(o){a.results={getException:function(){return o}}}a.draw();var s=a.getPersistencyId(a.options.persistency.results.key);s&&(a.results.getOriginalResponseAsString&&a.results.getOriginalResponseAsString().length<a.options.persistency.results.maxSize?r.storage.set(s,a.results.getAsStoreObject(),"month"):r.storage.remove(s))};var c=null,d=null,h=null;a.warn=function(e){if(!c){c=n("<div>",{"class":"toggableWarning"}).prependTo(a.container).hide();d=n("<span>",{"class":"toggleWarning"}).html("×").click(function(){c.hide(400)}).appendTo(c);h=n("<span>",{"class":"toggableMsg"}).appendTo(c)}h.empty();e instanceof n?h.append(e):h.html(e);c.show(400)};var f=null,g=function(){if(null===f){var e=window.URL||window.webkitURL||window.mozURL||window.msURL;f=e&&Blob}return f},m=null,E=function(t){var i=function(){var e=n('<div class="yasr_btnGroup"></div>');n.each(t.plugins,function(i,o){if(!o.hideFromSelection){var s=o.name||i,a=n("<button class='yasr_btn'></button>").text(s).addClass("select_"+i).click(function(){e.find("button.selected").removeClass("selected");n(this).addClass("selected");t.options.output=i;var o=t.getPersistencyId(t.options.persistency.outputSelector);o&&r.storage.set(o,t.options.output,"month");c&&c.hide(400);t.draw();t.updateHeader()}).appendTo(e);t.options.output==i&&a.addClass("selected")}});e.children().length>1&&t.header.append(e)},o=function(){var r=function(e,t){var n=null,r=window.URL||window.webkitURL||window.mozURL||window.msURL;if(r&&Blob){var i=new Blob([e],{type:t});n=r.createObjectURL(i)}return n},i=n("<button class='yasr_btn yasr_downloadIcon btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").download)).click(function(){var i=t.plugins[t.options.output];if(i&&i.getDownloadInfo){var o=i.getDownloadInfo(),s=r(o.getContent(),o.contentType?o.contentType:"text/plain"),a=n("<a></a>",{href:s,download:o.filename});e("./utils.js").fireClick(a)}});t.header.append(i)},s=function(){var r=n("<button class='yasr_btn btn_fullscreen btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").fullscreen)).click(function(){t.container.addClass("yasr_fullscreen")});t.header.append(r)},a=function(){var r=n("<button class='yasr_btn btn_smallscreen btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").smallscreen)).click(function(){t.container.removeClass("yasr_fullscreen")});t.header.append(r)},l=function(){m=n("<button>",{"class":"yasr_btn yasr_embedBtn",title:"Get HTML snippet to embed results on a web page"}).text("</>").click(function(e){var r=t.plugins[t.options.output];if(r&&r.getEmbedHtml){var i=r.getEmbedHtml();e.stopPropagation();var o=n("<div class='yasr_embedPopup'></div>").appendTo(t.header);n("html").click(function(){o&&o.remove()});o.click(function(e){e.stopPropagation()});var s=n("<textarea>").val(i);s.focus(function(){var e=n(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});o.empty().append(s);var a=m.position(),l=a.top+m.outerHeight()+"px",u=Math.max(a.left+m.outerWidth()-o.outerWidth(),0)+"px";o.css("top",l).css("left",u)}});t.header.append(m)};s();a();t.options.drawOutputSelector&&i();t.options.drawDownloadIcon&&g()&&o();l()},v=a.getPersistencyId(a.options.persistency.outputSelector);if(v){var x=r.storage.get(v);x&&(a.options.output=x)}E(a);if(!s&&a.options.persistency&&a.options.persistency.results){var y,N=a.getPersistencyId(a.options.persistency.results.key);N&&(y=r.storage.get(N));if(!y&&a.options.persistency.results.id){var I="string"==typeof a.options.persistency.results.id?a.options.persistency.results.id:a.options.persistency.results.id(a);if(I){y=r.storage.get(I);y&&r.storage.remove(I)}}y&&(n.isArray(y)?a.setResponse.apply(this,y):a.setResponse(y))}s&&a.setResponse(s);a.updateHeader();return a};i.plugins={};i.registerOutput=function(e,t){i.plugins[e]=t};i.defaults=e("./defaults.js");i.version={YASR:e("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":e("yasgui-utils").version};i.$=n;try{i.registerOutput("boolean",e("./boolean.js"))}catch(o){}try{i.registerOutput("rawResponse",e("./rawResponse.js"))}catch(o){}try{i.registerOutput("table",e("./table.js"))}catch(o){}try{i.registerOutput("error",e("./error.js"))}catch(o){}try{i.registerOutput("pivot",e("./pivot.js"))}catch(o){}try{i.registerOutput("gchart",e("./gchart.js"))}catch(o){}},{"../package.json":71,"./boolean.js":73,"./defaults.js":74,"./error.js":75,"./gChartLoader.js":77,"./gchart.js":78,"./imgs.js":79,"./jquery/extendJquery.js":80,"./parsers/wrapper.js":87,"./pivot.js":89,"./rawResponse.js":90,"./table.js":91,"./utils.js":92,jquery:void 0,"yasgui-utils":68}],83:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),t.exports=function(t){return e("./dlv.js")(t,",")}},{"./dlv.js":84,jquery:void 0}],84:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("../../lib/jquery.csv-0.71.js");t.exports=function(e,t){var r={},i=n.csv.toArrays(e,{separator:t}),o=function(e){return 0==e.indexOf("http")?"uri":null},s=function(){if(2==i.length&&1==i[0].length&&1==i[1].length&&"boolean"==i[0][0]&&("1"==i[1][0]||"0"==i[1][0])){r["boolean"]="1"==i[1][0]?!0:!1;return!0}return!1},a=function(){if(i.length>0&&i[0].length>0){r.head={vars:i[0]};return!0}return!1},l=function(){if(i.length>1){r.results={bindings:[]};for(var e=1;e<i.length;e++){for(var t={},n=0;n<i[e].length;n++){var s=r.head.vars[n];if(s){var a=i[e][n],l=o(a);t[s]={value:a};l&&(t[s].type=l)}}r.results.bindings.push(t)}r.head={vars:i[0]};return!0}return!1},u=s();if(!u){var p=a();p&&l()}return r}},{"../../lib/jquery.csv-0.71.js":50,jquery:void 0}],85:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),t.exports=function(e){if("string"==typeof e)try{return JSON.parse(e)}catch(t){return!1}return"object"==typeof e&&e.constructor==={}.constructor?e:!1}},{jquery:void 0}],86:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),t.exports=function(t){return e("./dlv.js")(t," ")}},{"./dlv.js":84,jquery:void 0}],87:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),t.exports=function(t,n,r){var i={xml:e("./xml.js"),json:e("./json.js"),tsv:e("./tsv.js"),csv:e("./csv.js")},o=null,s=null,a=null,l=null,u=null,p=function(){if("object"==typeof t){if(t.exception)u=t.exception;else if(void 0!=t.status&&(t.status>=300||0===t.status)){u={status:t.status};"string"==typeof r&&(u.errorString=r);t.responseText&&(u.responseText=t.responseText);t.statusText&&(u.statusText=t.statusText)}if(t.contentType)o=t.contentType.toLowerCase();else if(t.getResponseHeader&&t.getResponseHeader("content-type")){var e=t.getResponseHeader("content-type").trim().toLowerCase();e.length>0&&(o=e)}t.response?s=t.response:n||r||(s=t)}u||s||(s=t.responseText?t.responseText:t)},c=function(){if(a)return a;if(a===!1||u)return!1;var e=function(){if(o)if(o.indexOf("json")>-1){try{a=i.json(s)}catch(e){u=e}l="json"}else if(o.indexOf("xml")>-1){try{a=i.xml(s)}catch(e){u=e}l="xml"}else if(o.indexOf("csv")>-1){try{a=i.csv(s)}catch(e){u=e}l="csv"}else if(o.indexOf("tab-separated")>-1){try{a=i.tsv(s)}catch(e){u=e}l="tsv"}},t=function(){a=i.json(s);if(a)l="json";else try{a=i.xml(s);a&&(l="xml")}catch(e){}};e();a||t();a||(a=!1);return a},d=function(){var e=c();return e&&"head"in e?e.head.vars:null},h=function(){var e=c();return e&&"results"in e?e.results.bindings:null},f=function(){var e=c();return e&&"boolean"in e?e["boolean"]:null},g=function(){return s},m=function(){var e="";"string"==typeof s?e=s:"json"==l?e=JSON.stringify(s,void 0,2):"xml"==l&&(e=(new XMLSerializer).serializeToString(s));return e},E=function(){return u},v=function(){null==l&&c();return l},x=function(){var e={};if(t.status){e.status=t.status;e.responseText=t.responseText;e.statusText=t.statusText;e.contentType=o}else e=t;var i=n,s=void 0;"string"==typeof r&&(s=r);return[e,i,s]};p();a=c();return{getAsStoreObject:x,getAsJson:c,getOriginalResponse:g,getOriginalResponseAsString:m,getOriginalContentType:function(){return o},getVariables:d,getBindings:h,getBoolean:f,getType:v,getException:E}}},{"./csv.js":83,"./json.js":85,"./tsv.js":86,"./xml.js":88,jquery:void 0}],88:[function(e,t){"use strict";{var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports=function(e){var t=function(e){s.head={};for(var t=0;t<e.childNodes.length;t++){var n=e.childNodes[t];if("variable"==n.nodeName){s.head.vars||(s.head.vars=[]);var r=n.getAttribute("name");r&&s.head.vars.push(r)}}},r=function(e){s.results={};s.results.bindings=[];for(var t=0;t<e.childNodes.length;t++){for(var n=e.childNodes[t],r=null,i=0;i<n.childNodes.length;i++){var o=n.childNodes[i];if("binding"==o.nodeName){var a=o.getAttribute("name");if(a){r=r||{};r[a]={};for(var l=0;l<o.childNodes.length;l++){var u=o.childNodes[l],p=u.nodeName;if("#text"!=p){r[a].type=p;r[a].value=u.innerHTML;var c=u.getAttribute("datatype");c&&(r[a].datatype=c)}}}}}r&&s.results.bindings.push(r)}},i=function(e){s["boolean"]="true"==e.innerHTML?!0:!1},o=null;"string"==typeof e?o=n.parseXML(e):n.isXMLDoc(e)&&(o=e);var e=null;if(!(o.childNodes.length>0))return null;e=o.childNodes[0];for(var s={},a=0;a<e.childNodes.length;a++){var l=e.childNodes[a];"head"==l.nodeName&&t(l);"results"==l.nodeName&&r(l);"boolean"==l.nodeName&&i(l)}return s}}},{jquery:void 0}],89:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("./utils.js"),i=e("yasgui-utils"),o=e("./imgs.js");(function(){try{return e("jquery-ui/sortable")}catch(t){return window.jQuery}})();(function(){try{return e("pivottable")}catch(t){return window.jQuery}})();if(!n.fn.pivotUI)throw new Error("Pivot lib not loaded");var s=t.exports=function(t){var a=n.extend(!0,{},s.defaults);if(a.useD3Chart){try{var l=function(){try{return e("d3")}catch(t){return window.d3}}();l&&e("../node_modules/pivottable/dist/d3_renderers.js")}catch(u){}n.pivotUtilities.d3_renderers&&n.extend(!0,n.pivotUtilities.renderers,n.pivotUtilities.d3_renderers)}var p,c=null,d=function(){var e=t.results.getVariables();if(!a.mergeLabelsWithUris)return e;var n=[];c="string"==typeof a.mergeLabelsWithUris?a.mergeLabelsWithUris:"Label";e.forEach(function(t){-1!==t.indexOf(c,t.length-c.length)&&e.indexOf(t.substring(0,t.length-c.length))>=0||n.push(t)});return n},h=function(e){var n=d(),i=null;t.options.getUsedPrefixes&&(i="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);t.results.getBindings().forEach(function(t){var o={};n.forEach(function(e){if(e in t){var n=t[e].value;c&&t[e+c]?n=t[e+c].value:"uri"==t[e].type&&(n=r.uriToPrefixed(i,n));o[e]=n}else o[e]=null});e(o)})},f=t.getPersistencyId(a.persistencyId),g=function(){var e=i.storage.get(f);if(e){var r=t.results.getVariables(),o=!0;e.cols.forEach(function(e){r.indexOf(e)<0&&(o=!1)});o&&e.rows.forEach(function(e){r.indexOf(e)<0&&(o=!1)});if(!o){e.cols=[];e.rows=[]}n.pivotUtilities.renderers[e.rendererName]||delete e.rendererName}else e={};return e},m=function(){var r=function(){var e=function(e){if(f){var n={cols:e.cols,rows:e.rows,rendererName:e.rendererName,aggregatorName:e.aggregatorName,vals:e.vals};i.storage.set(f,n,"month")}e.rendererName.toLowerCase().indexOf(" chart")>=0?r.show():r.hide();t.updateHeader()},r=n("<button>",{"class":"openPivotGchart yasr_btn"}).text("Chart Config").click(function(){p.find('div[dir="ltr"]').dblclick()}).appendTo(t.resultsContainer);p=n("<div>",{"class":"pivotTable"}).appendTo(n(t.resultsContainer));var a=n.extend(!0,{},g(),s.defaults.pivotTable);a.onRefresh=function(){var t=a.onRefresh;return function(n){e(n);t&&t(n)}}();window.pivot=p.pivotUI(h,a);var l=n(i.svg.getElement(o.move));p.find(".pvtTriangle").replaceWith(l);n(".pvtCols").prepend(n("<div>",{"class":"containerHeader"}).text("Columns"));n(".pvtRows").prepend(n("<div>",{"class":"containerHeader"}).text("Rows"));n(".pvtUnused").prepend(n("<div>",{"class":"containerHeader"}).text("Available Variables"));n(".pvtVals").prepend(n("<div>",{"class":"containerHeader"}).text("Cells"));setTimeout(t.updateHeader,400)};t.options.useGoogleCharts&&a.useGoogleCharts&&!n.pivotUtilities.gchart_renderers?e("./gChartLoader.js").on("done",function(){try{e("../node_modules/pivottable/dist/gchart_renderers.js");n.extend(!0,n.pivotUtilities.renderers,n.pivotUtilities.gchart_renderers)}catch(t){a.useGoogleCharts=!1}r()}).on("error",function(){console.log("could not load gchart");a.useGoogleCharts=!1;r()}).googleLoad():r()},E=function(){return t.results&&t.results.getVariables&&t.results.getVariables()&&t.results.getVariables().length>0},v=function(){if(!t.results)return null;var e=t.resultsContainer.find(".pvtRendererArea svg");if(e.length>0)return{getContent:function(){return e[0].outerHTML?e[0].outerHTML:n("<div>").append(e.clone()).html()},filename:"queryResults.svg",contentType:"image/svg+xml",buttonTitle:"Download SVG Image"};var r=t.resultsContainer.find(".pvtRendererArea table");return r.length>0?{getContent:function(){return r.tableToCsv()},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:void 0},x=function(){if(!t.results)return null;var e=t.resultsContainer.find(".pvtRendererArea svg").clone().removeAttr("height").removeAttr("width").css("height","").css("width","");if(0==e.length)return null;var r=e[0].outerHTML;r||(r=n("<div>").append(e.clone()).html());return'<div style="width: 800px; height: 600px;">\n'+r+"\n</div>"};return{getDownloadInfo:v,getEmbedHtml:x,options:a,draw:m,name:"Pivot Table",canHandleResults:E,getPriority:4}};s.defaults={mergeLabelsWithUris:!1,useGoogleCharts:!0,useD3Chart:!0,persistencyId:"pivot",pivotTable:{}};s.version={"YASR-rawResponse":e("../package.json").version,jquery:n.fn.jquery}},{"../node_modules/pivottable/dist/d3_renderers.js":63,"../node_modules/pivottable/dist/gchart_renderers.js":64,"../package.json":71,"./gChartLoader.js":77,"./imgs.js":79,"./utils.js":92,d3:58,jquery:void 0,"jquery-ui/sortable":61,pivottable:65,"yasgui-utils":68}],90:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=function(){try{return e("codemirror")}catch(t){return window.CodeMirror}}();e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/mode/xml/xml.js");e("codemirror/mode/javascript/javascript.js");var i=t.exports=function(e){var t=n.extend(!0,{},i.defaults),o=null,s=function(){var n=t.CodeMirror;n.value=e.results.getOriginalResponseAsString();var i=e.results.getType();if(i){"json"==i&&(i={name:"javascript",json:!0});n.mode=i}o=r(e.resultsContainer.get()[0],n);o.on("fold",function(){o.refresh()});o.on("unfold",function(){o.refresh()})},a=function(){if(!e.results)return!1;if(!e.results.getOriginalResponseAsString)return!1;var t=e.results.getOriginalResponseAsString();return t&&0!=t.length||!e.results.getException()?!0:!1},l=function(){if(!e.results)return null;var t=e.results.getOriginalContentType(),n=e.results.getType();return{getContent:function(){return e.results.getOriginalResponse()},filename:"queryResults"+(n?"."+n:""),contentType:t?t:"text/plain",buttonTitle:"Download raw response"}};return{draw:s,name:"Raw Response",canHandleResults:a,getPriority:2,getDownloadInfo:l}};i.defaults={CodeMirror:{readOnly:!0,lineNumbers:!0,lineWrapping:!0,foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"]}};i.version={"YASR-rawResponse":e("../package.json").version,jquery:n.fn.jquery,CodeMirror:r.version}},{"../package.json":71,codemirror:void 0,"codemirror/addon/edit/matchbrackets.js":51,"codemirror/addon/fold/brace-fold.js":52,"codemirror/addon/fold/foldcode.js":53,"codemirror/addon/fold/foldgutter.js":54,"codemirror/addon/fold/xml-fold.js":55,"codemirror/mode/javascript/javascript.js":56,"codemirror/mode/xml/xml.js":57,jquery:void 0}],91:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("yasgui-utils"),i=e("./utils.js"),o=e("./imgs.js");(function(){try{return e("datatables")}catch(t){return window.jQuery}})();e("../lib/colResizable-1.4.js");var s=t.exports=function(t){var i=null,a={name:"Table",getPriority:10},l=a.options=n.extend(!0,{},s.defaults),p=l.persistency?t.getPersistencyId(l.persistency.tableLength):null,c=function(){var e=[],n=t.results.getBindings(),r=t.results.getVariables(),i=null;t.options.getUsedPrefixes&&(i="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);for(var o=0;o<n.length;o++){var s=[];s.push("");for(var u=n[o],p=0;p<r.length;p++){var c=r[p];s.push(c in u?l.getCellContent?l.getCellContent(t,a,u,c,{rowId:o,colId:p,usedPrefixes:i}):"":"")}e.push(s)}return e},d=t.getPersistencyId("eventId")||"yasr_"+n(t.container).closest("[id]").attr("id"),h=function(){i.on("order.dt",function(){f()});p&&i.on("length.dt",function(e,t,n){r.storage.set(p,n,"month")});n.extend(!0,l.callbacks,l.handlers);i.delegate("td","click",function(e){if(l.callbacks&&l.callbacks.onCellClick){var t=l.callbacks.onCellClick(this,e);if(t===!1)return!1}}).delegate("td","mouseenter",function(e){l.callbacks&&l.callbacks.onCellMouseEnter&&l.callbacks.onCellMouseEnter(this,e);var t=n(this);l.fetchTitlesFromPreflabel&&void 0===t.attr("title")&&0==t.text().trim().indexOf("http")&&u(t)}).delegate("td","mouseleave",function(e){l.callbacks&&l.callbacks.onCellMouseLeave&&l.callbacks.onCellMouseLeave(this,e)});n(window).off("resize."+d);n(window).on("resize."+d,g);g()};a.draw=function(){i=n('<table cellpadding="0" cellspacing="0" border="0" class="resultsTable"></table>');n(t.resultsContainer).html(i);var e=l.datatable;e.data=c();e.columns=l.getColumns(t,a);var o=r.storage.get(p);o&&(e.pageLength=o);i.DataTable(n.extend(!0,{},e));f();h();i.colResizable();i.find("thead").outerHeight();n(t.resultsContainer).find(".JCLRgrip").height(i.find("thead").outerHeight());var s=t.header.outerHeight()-5;if(s>0){t.resultsContainer.find(".dataTables_wrapper").css("position","relative").css("top","-"+s+"px").css("margin-bottom","-"+s+"px");n(t.resultsContainer).find(".JCLRgrip").css("marginTop",s+"px")}};var f=function(){var e={sorting:"unsorted",sorting_asc:"sortAsc",sorting_desc:"sortDesc"};i.find(".sortIcons").remove();for(var t in e){var s=n("<div class='sortIcons'></div>");r.svg.draw(s,o[e[t]]);i.find("th."+t).append(s)}};a.canHandleResults=function(){return t.results&&t.results.getVariables&&t.results.getVariables()&&t.results.getVariables().length>0};a.getDownloadInfo=function(){return t.results?{getContent:function(){return e("./bindingsToCsv.js")(t.results.getAsJson())},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:null};var g=function(){var e=!0,n=t.container.find(".yasr_downloadIcon"),r=t.container.find(".dataTables_filter"),i=n.offset().left;if(i>0){var o=i+n.outerWidth(),s=r.offset().left;s>0&&o>s&&(e=!1)}e?r.css("visibility","visible"):r.css("visibility","hidden")};return a},a=function(e,t,n){var r=i.escapeHtmlEntities(n.value);if(n["xml:lang"])r='"'+r+'"<sup>@'+n["xml:lang"]+"</sup>";else if(n.datatype){var o="http://www.w3.org/2001/XMLSchema#",s=n.datatype;s=0===s.indexOf(o)?"xsd:"+s.substring(o.length):"<"+s+">";r='"'+r+'"<sup>^^'+s+"</sup>"}return r},l=function(e,t,n,r,i){var o=n[r],s=null;if("uri"==o.type){var l=null,u=o.value,p=u;if(i.usedPrefixes)for(var c in i.usedPrefixes)if(0==p.indexOf(i.usedPrefixes[c])){p=c+":"+u.substring(i.usedPrefixes[c].length);break}if(t.options.mergeLabelsWithUris){var d="string"==typeof t.options.mergeLabelsWithUris?t.options.mergeLabelsWithUris:"Label";if(n[r+d]){p=a(e,t,n[r+d]);l=u}}s="<a "+(l?"title='"+u+"' ":"")+"class='uri' target='_blank' href='"+u+"'>"+p+"</a>"}else s="<span class='nonUri'>"+a(e,t,o)+"</span>";return"<div>"+s+"</div>"},u=function(e){var t=function(){e.attr("title","")};n.get("http://preflabel.org/api/v1/label/"+encodeURIComponent(e.text())+"?silent=true").success(function(n){"object"==typeof n&&n.label?e.attr("title",n.label):"string"==typeof n&&n.length>0?e.attr("title",n):t()}).fail(t)};s.defaults={getCellContent:l,persistency:{tableLength:"tableLength"},getColumns:function(e,t){var n=function(n){if(!t.options.mergeLabelsWithUris)return!0;var r="string"==typeof t.options.mergeLabelsWithUris?t.options.mergeLabelsWithUris:"Label";return-1!==n.indexOf(r,n.length-r.length)&&e.results.getVariables().indexOf(n.substring(0,n.length-r.length))>=0?!1:!0},r=[];r.push({title:""});e.results.getVariables().forEach(function(e){r.push({title:"<span>"+e+"</span>",visible:n(e)})});return r},fetchTitlesFromPreflabel:!0,mergeLabelsWithUris:!1,callbacks:{onCellMouseEnter:null,onCellMouseLeave:null,onCellClick:null},datatable:{autoWidth:!1,order:[],pageLength:50,lengthMenu:[[10,50,100,1e3,-1],[10,50,100,1e3,"All"]],lengthChange:!0,pagingType:"full_numbers",drawCallback:function(e){for(var t=0;t<e.aiDisplay.length;t++)n("td:eq(0)",e.aoData[e.aiDisplay[t]].nTr).html(t+1);var r=!1;n(e.nTableWrapper).find(".paginate_button").each(function(){-1==n(this).attr("class").indexOf("current")&&-1==n(this).attr("class").indexOf("disabled")&&(r=!0)});r?n(e.nTableWrapper).find(".dataTables_paginate").show():n(e.nTableWrapper).find(".dataTables_paginate").hide()},columnDefs:[{width:"32px",orderable:!1,targets:0}]}};s.version={"YASR-table":e("../package.json").version,jquery:n.fn.jquery,"jquery-datatables":n.fn.DataTable.version}},{"../lib/colResizable-1.4.js":49,"../package.json":71,"./bindingsToCsv.js":72,"./imgs.js":79,"./utils.js":92,datatables:void 0,jquery:void 0,"yasgui-utils":68}],92:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("./exceptions.js").GoogleTypeException;t.exports={escapeHtmlEntities:function(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")},uriToPrefixed:function(e,t){if(e)for(var n in e)if(0==t.indexOf(e[n])){t=n+":"+t.substring(e[n].length);break}return t},getGoogleTypeForBinding:function(e){if(null==e)return null;if(null==e.type||"typed-literal"!==e.type&&"literal"!==e.type)return"string";switch(e.datatype){case"http://www.w3.org/2001/XMLSchema#float":case"http://www.w3.org/2001/XMLSchema#decimal":case"http://www.w3.org/2001/XMLSchema#int":case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#long":case"http://www.w3.org/2001/XMLSchema#gYearMonth":case"http://www.w3.org/2001/XMLSchema#gYear":case"http://www.w3.org/2001/XMLSchema#gMonthDay":case"http://www.w3.org/2001/XMLSchema#gDay":case"http://www.w3.org/2001/XMLSchema#gMonth":return"number";case"http://www.w3.org/2001/XMLSchema#date":return"date";case"http://www.w3.org/2001/XMLSchema#dateTime":return"datetime";case"http://www.w3.org/2001/XMLSchema#time":return"timeofday";default:return"string"}},getGoogleTypeForBindings:function(e,n){var i={},o=0;e.forEach(function(e){var r=t.exports.getGoogleTypeForBinding(e[n]);if(null!=r){if(!(r in i)){i[r]=0;o++}i[r]++}});if(0==o)return"string";if(1!=o)throw new r(i,n);for(var s in i)return s},castGoogleType:function(e,n,r){if(null==e)return null;if("string"==r||null==e.type||"typed-literal"!==e.type&&"literal"!==e.type)return(e.type="uri")?t.exports.uriToPrefixed(n,e.value):e.value;switch(e.datatype){case"http://www.w3.org/2001/XMLSchema#float":case"http://www.w3.org/2001/XMLSchema#decimal":case"http://www.w3.org/2001/XMLSchema#int":case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#long":case"http://www.w3.org/2001/XMLSchema#gYearMonth":case"http://www.w3.org/2001/XMLSchema#gYear":case"http://www.w3.org/2001/XMLSchema#gMonthDay":case"http://www.w3.org/2001/XMLSchema#gDay":case"http://www.w3.org/2001/XMLSchema#gMonth":return Number(e.value);case"http://www.w3.org/2001/XMLSchema#date":var o=i(e.value);if(o)return o;case"http://www.w3.org/2001/XMLSchema#dateTime":case"http://www.w3.org/2001/XMLSchema#time":return new Date(e.value);default:return e.value}},fireClick:function(e){e&&e.each(function(e,t){var r=n(t);if(document.dispatchEvent){var i=document.createEvent("MouseEvents");i.initMouseEvent("click",!0,!0,window,1,1,1,1,1,!1,!1,!1,!1,0,r[0]);r[0].dispatchEvent(i)}else document.fireEvent&&r[0].click()})}};var i=function(e){var t=new Date(e.replace(/(\d)([\+-]\d{2}:\d{2})/,"$1Z$2"));return isNaN(t)?null:t}},{"./exceptions.js":76,jquery:void 0}],93:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports={persistencyPrefix:function(e){return"yasgui_"+n(e.wrapperElement).closest("[id]").attr("id")+"_"},api:{corsProxy:null,collections:null},tracker:{googleAnalyticsId:null,askConsent:!0}}},{jquery:void 0}],94:[function(e,t){"use strict";t.exports={yasgui:'<svg xmlns:osb="http://www.openswatchbook.org/uri/2009/osb" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" viewBox="0 0 603.99 522.51" width="100%" height="100%" version="1.1" inkscape:version="0.48.4 r9939" sodipodi:docname="test.svg"> <defs > <linearGradient osb:paint="solid"> <stop style="stop-color:#3b3b3b;stop-opacity:1;" offset="0" /> </linearGradient> <inkscape:path-effect effect="skeletal" is_visible="true" pattern="M 0,5 C 0,2.24 2.24,0 5,0 7.76,0 10,2.24 10,5 10,7.76 7.76,10 5,10 2.24,10 0,7.76 0,5 z" copytype="single_stretched" prop_scale="1" scale_y_rel="false" spacing="0" normal_offset="0" tang_offset="0" prop_units="false" vertical_pattern="false" fuse_tolerance="0" /> <inkscape:path-effect effect="spiro" is_visible="true" /> <inkscape:path-effect effect="skeletal" is_visible="true" pattern="M 0,5 C 0,2.24 2.24,0 5,0 7.76,0 10,2.24 10,5 10,7.76 7.76,10 5,10 2.24,10 0,7.76 0,5 z" copytype="single_stretched" prop_scale="1" scale_y_rel="false" spacing="0" normal_offset="0" tang_offset="0" prop_units="false" vertical_pattern="false" fuse_tolerance="0" /> <inkscape:path-effect effect="spiro" is_visible="true" /> </defs> <sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.35" inkscape:cx="-469.55507" inkscape:cy="840.5292" inkscape:document-units="px" inkscape:current-layer="layer1" showgrid="false" inkscape:window-width="1855" inkscape:window-height="1056" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" /> <metadata > <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title /> </cc:Work> </rdf:RDF> </metadata> <g inkscape:label="Layer 1" inkscape:groupmode="layer" transform="translate(-50.966817,-280.33262)"> <rect style="fill:#3b3b3b;fill-opacity:1;stroke:none" width="40.000004" height="478.57324" x="-374.48849" y="103.99496" transform="matrix(-2.679181e-4,-0.99999996,0.99999993,-3.6684387e-4,0,0)" /> <rect style="fill:#3b3b3b;fill-opacity:1;stroke:none" width="40.000004" height="560" x="651.37634" y="-132.06581" transform="matrix(0.74639582,0.66550228,-0.66550228,0.74639582,0,0)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,92.132758,620.67568)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,457.84706,214.96137)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,-30.152972,219.81853)" /> <g transform="matrix(0.68747304,-0.7262099,0.7262099,0.68747304,0,0)" inkscape:transform-center-x="239.86342" inkscape:transform-center-y="-26.958107" style="font-size:40px;font-style:normal;font-weight:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#3b3b3b;fill-opacity:1;stroke:none;font-family:Sans" > <path d="m -320.16655,490.61871 33.2,0 -32.4,75.4 0,64.6 -32.2,0 0,-64.6 -32.4,-75.4 33.2,0 15.2,43 15.4,-43 0,0" style="font-size:200px;font-variant:normal;font-stretch:normal;letter-spacing:20px;fill:#3b3b3b;font-family:RR Beaver;-inkscape-font-specification:RR Beaver" /> <path d="m -177.4603,630.61871 -32.2,0 -21.6,-80.4 -21.6,80.4 -32.2,0 37.4,-140 0.4,0 32,0 0.4,0 37.4,140 0,0" style="font-size:200px;font-variant:normal;font-stretch:normal;letter-spacing:20px;fill:#3b3b3b;font-family:RR Beaver;-inkscape-font-specification:RR Beaver" /> <path d="m -84.835303,544.41871 c 5.999926,9e-5 11.59992,1.13342 16.8,3.4 5.19991,2.26675 9.733238,5.40008 13.6,9.4 3.866564,3.86674 6.933228,8.40007 9.2,13.6 2.266556,5.20006 3.399889,10.80005 3.4,16.8 -1.11e-4,6.00004 -1.133444,11.60003 -3.4,16.8 -2.266772,5.20002 -5.333436,9.73335 -9.2,13.6 -3.866762,3.86668 -8.40009,6.93334 -13.6,9.2 -5.20008,2.26667 -10.800074,3.4 -16.8,3.4 l -64.599997,0 0,-32.2 64.599997,0 c 3.066595,-0.1333 5.599926,-1.19996 7.6,-3.2 2.133255,-2.13329 3.199921,-4.66662 3.2,-7.6 -7.9e-5,-3.06662 -1.066745,-5.59995 -3.2,-7.6 -2.000074,-2.13328 -4.533405,-3.19994 -7.6,-3.2 l -21.599997,0 c -6.00004,6e-5 -11.60004,-1.13328 -16.8,-3.4 -5.20003,-2.2666 -9.73336,-5.33327 -13.6,-9.2 -3.86668,-3.99993 -6.93335,-8.59992 -9.2,-13.8 -2.26667,-5.19991 -3.40001,-10.79991 -3.4,-16.8 -10e-6,-5.99989 1.13333,-11.59989 3.4,-16.8 2.26665,-5.19988 5.33332,-9.73321 9.2,-13.6 3.86664,-3.86653 8.39997,-6.9332 13.6,-9.2 5.19996,-2.26652 10.79996,-3.39986 16.8,-3.4 l 42.999997,0 0,32.4 -42.999997,0 c -3.06671,1.1e-4 -5.66671,1.06678 -7.8,3.2 -2.00004,2.00011 -3.00004,4.46677 -3,7.4 -4e-5,3.06676 0.99996,5.66676 3,7.8 2.13329,2.00009 4.73329,3.00009 7.8,3 l 21.599997,0 0,0" style="font-size:200px;font-variant:normal;font-stretch:normal;letter-spacing:20px;fill:#3b3b3b;font-family:RR Beaver;-inkscape-font-specification:RR Beaver" /> </g> <g style="font-size:40px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Theorem NBP;-inkscape-font-specification:Theorem NBP" > <path d="m 422.17683,677.02126 36.55,0 -5.44,27.54 -1.87,9.18 c -1.0201,5.10003 -2.94677,9.86003 -5.78,14.28 -2.83343,4.42002 -6.23343,8.27335 -10.2,11.56 -3.85342,3.28667 -8.21675,5.89334 -13.09,7.82 -4.76007,1.92667 -9.69007,2.89 -14.79,2.89 l -18.36,0 c -5.10004,0 -9.69003,-0.96333 -13.77,-2.89 -3.96669,-1.92666 -7.31002,-4.53333 -10.03,-7.82 -2.60668,-3.28665 -4.42002,-7.13998 -5.44,-11.56 -1.02001,-4.41997 -1.02001,-9.17997 0,-14.28 l 9.18,-45.9 c 1.01998,-5.09991 2.94664,-9.85991 5.78,-14.28 2.8333,-4.4199 6.17663,-8.27323 10.03,-11.56 3.96662,-3.28656 8.32995,-5.89322 13.09,-7.82 4.87328,-1.92655 9.85994,-2.88988 14.96,-2.89 l 18.36,0 c 5.09991,1.2e-4 9.63324,0.96345 13.6,2.89 4.0799,1.92678 7.42323,4.53344 10.03,7.82 2.71989,3.28677 4.58989,7.1401 5.61,11.56 1.01988,4.42009 1.01988,9.18009 0,14.28 l -27.37,0 c 0.45325,-2.49325 -9e-5,-4.58991 -1.36,-6.29 -1.36009,-1.81324 -3.34342,-2.71991 -5.95,-2.72 l -18.36,0 c -2.60673,9e-5 -4.98672,0.90676 -7.14,2.72 -2.15339,1.70009 -3.45672,3.79675 -3.91,6.29 l -9.18,45.9 c -0.45337,2.49337 -4e-5,4.6467 1.36,6.46 1.35996,1.81336 3.34329,2.72003 5.95,2.72 l 18.36,0 c 2.6066,3e-5 4.98659,-0.90664 7.14,-2.72 2.15326,-1.8133 3.45659,-3.96663 3.91,-6.46 l 1.87,-9.18 -9.18,0 5.44,-27.54" style="font-size:170px;font-style:italic;font-weight:bold;letter-spacing:20px;fill:#c80000;font-family:RR Beaver;-inkscape-font-specification:RR Beaver Bold Italic" /> <path d="m 569.69808,713.74126 c -1.0201,5.10003 -2.94677,9.86003 -5.78,14.28 -2.83343,4.42002 -6.23343,8.27335 -10.2,11.56 -3.85342,3.28667 -8.21675,5.89334 -13.09,7.82 -4.76007,1.92667 -9.69007,2.89 -14.79,2.89 l -18.36,0 c -5.10004,0 -9.69003,-0.96333 -13.77,-2.89 -3.96669,-1.92666 -7.31002,-4.53333 -10.03,-7.82 -2.60668,-3.28665 -4.42002,-7.13998 -5.44,-11.56 -1.02001,-4.41997 -1.02001,-9.17997 0,-14.28 l 16.49,-82.45 27.37,0 -16.49,82.45 c -0.45337,2.49337 -4e-5,4.6467 1.36,6.46 1.35996,1.81336 3.34329,2.72003 5.95,2.72 l 18.36,0 c 2.6066,3e-5 4.98659,-0.90664 7.14,-2.72 2.15326,-1.8133 3.45659,-3.96663 3.91,-6.46 l 16.49,-82.45 27.37,0 -16.49,82.45" style="font-size:170px;font-style:italic;font-weight:bold;letter-spacing:20px;fill:#c80000;font-family:RR Beaver;-inkscape-font-specification:RR Beaver Bold Italic" /> <path d="m 613.00933,631.29126 27.37,0 -23.8,119 -27.37,0 23.8,-119 0,0" style="font-size:170px;font-style:italic;font-weight:bold;letter-spacing:20px;fill:#c80000;font-family:RR Beaver;-inkscape-font-specification:RR Beaver Bold Italic" /> </g> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.4331683,0,0,0.38716814,381.83246,155.72497)" /> </g></svg>',cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',plus:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="5 -10 59.259258 79.999999" enable-background="new 0 0 100 100" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_79066_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="6.675088" inkscape:cx="46.670641" inkscape:cy="16.037704" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Your_Icon" /><g transform="translate(-23.47037,-20)"><g ><g ><g /></g><g /></g></g><path d="M 67.12963,22.5 H 42.129629 v -25 c 0,-4.142 -3.357,-7.5 -7.5,-7.5 -4.141999,0 -7.5,3.358 -7.5,7.5 v 25 H 2.1296295 c -4.142,0 -7.5,3.358 -7.5,7.5 0,4.143 3.358,7.5 7.5,7.5 H 27.129629 v 25 c 0,4.143 3.358001,7.5 7.5,7.5 4.143,0 7.5,-3.357 7.5,-7.5 v -25 H 67.12963 c 4.143,0 7.5,-3.357 7.5,-7.5 0,-4.142 -3.357,-7.5 -7.5,-7.5 z" inkscape:connector-curvature="0" style="fill:#000000" /></svg>',crossMark:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" viewBox="3.75 -7.5 43.041089 57.023436" version="1.1" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_96505_cc.svg"> <metadata > <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> </cc:Work> </rdf:RDF> </metadata> <defs /> <sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="37.14799" inkscape:cy="24.652776" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /> <g transform="translate(-13.01266,-18.5625)"> <path style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none" d="M 67.335938,21.40625 60.320312,11.0625 C 50.757812,17.542969 43.875,22.636719 38.28125,27.542969 32.691406,22.636719 25.808594,17.546875 16.242188,11.0625 L 9.230469,21.40625 C 18.03125,27.375 24.3125,31.953125 29.398438,36.351562 23.574219,42.90625 18.523438,50.332031 11.339844,61.183594 l 10.421875,6.902344 C 28.515625,57.886719 33.144531,51.046875 38.28125,45.160156 c 5.140625,5.886719 9.765625,12.726563 16.523438,22.925782 L 65.226562,61.183594 C 58.039062,50.335938 52.988281,42.90625 47.167969,36.351562 52.25,31.953125 58.53125,27.375 67.335938,21.40625 z m 0,0" inkscape:connector-curvature="0" /> </g></svg>',checkMark:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" viewBox="3.75 -7.5 48.269674 56.308594" version="1.1" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_96848_cc.svg"> <metadata > <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> </cc:Work> </rdf:RDF> </metadata> <defs /> <sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="40.78518" inkscape:cy="24.259259" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /> <g transform="translate(-9.3300051,-18.878906)"> <path style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none" d="M 27.160156,67.6875 4.632812,45.976562 l 8.675782,-9 11.503906,11.089844 c 7.25,-10.328125 22.84375,-29.992187 40.570312,-36.6875 l 4.414063,11.695313 C 49.894531,30.59375 31.398438,60.710938 31.214844,61.015625 z m 0,0" inkscape:connector-curvature="0" /> </g></svg>',checkCrossMark:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" viewBox="3.75 -7.5 49.752653 49.990111" version="1.1" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_96848_cc.svg"> <metadata > <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> </cc:Work> </rdf:RDF> </metadata> <defs /> <sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="41.024355" inkscape:cy="53.698163" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /> <g transform="matrix(0.59034297,0,0,0.59034297,12.298561,2.5312719)" > <path style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none" d="M 27.160156,67.6875 4.632812,45.976562 l 8.675782,-9 11.503906,11.089844 c 7.25,-10.328125 22.84375,-29.992187 40.570312,-36.6875 l 4.414063,11.695313 C 49.894531,30.59375 31.398438,60.710938 31.214844,61.015625 z m 0,0" inkscape:connector-curvature="0" /> </g> <g transform="matrix(0.46036177,0,0,0.46036177,-0.49935505,-12.592753)" > <path style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none" d="M 67.335938,21.40625 60.320312,11.0625 C 50.757812,17.542969 43.875,22.636719 38.28125,27.542969 32.691406,22.636719 25.808594,17.546875 16.242188,11.0625 L 9.230469,21.40625 C 18.03125,27.375 24.3125,31.953125 29.398438,36.351562 23.574219,42.90625 18.523438,50.332031 11.339844,61.183594 l 10.421875,6.902344 C 28.515625,57.886719 33.144531,51.046875 38.28125,45.160156 c 5.140625,5.886719 9.765625,12.726563 16.523438,22.925782 L 65.226562,61.183594 C 58.039062,50.335938 52.988281,42.90625 47.167969,36.351562 52.25,31.953125 58.53125,27.375 67.335938,21.40625 z m 0,0" inkscape:connector-curvature="0" /> </g></svg>'}
},{}],95:[function(e){"use strict";var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=e("selectize"),r=e("yasgui-utils");n.define("allowRegularTextInput",function(){var e=this;this.onMouseDown=function(){var t=e.onMouseDown;return function(n){if(e.$dropdown.is(":visible")){n.stopPropagation();n.preventDefault()}else{t.apply(this,arguments);var r=this.getValue();this.clear(!0);this.setTextboxValue(r);this.refreshOptions(!0)}}}()});t.fn.endpointCombi=function(e,n){var o=function(n){e.corsEnabled||(e.corsEnabled={});n in e.corsEnabled||t.ajax({url:n,data:{query:"ASK {?x ?y ?z}"},complete:function(t){e.corsEnabled[n]=t.status>0}})},s=function(t){var n=null;e.persistencyPrefix&&(n=e.persistencyPrefix+"endpoint_"+t);var i=[];for(var o in l[0].selectize.options){var s=l[0].selectize.options[o];if(s.optgroup==t){var a={endpoint:s.endpoint};s.text&&(a.label=s.text);i.push(a)}}r.storage.set(n,i)},a=function(t,n){var o=null;e.persistencyPrefix&&(o=e.persistencyPrefix+"endpoint_"+n);var s=r.storage.get(o);if(!s&&"catalogue"==n){s=i();r.storage.set(o,s)}t(s,n)},l=this,u={selectize:{plugins:["allowRegularTextInput"],create:function(e,t){t({endpoint:e,optgroup:"own"})},createOnBlur:!0,onItemAdd:function(t){n.onChange&&n.onChange(t);e.options.api.corsProxy&&o(t)},onOptionRemove:function(){s("own");s("catalogue")},optgroups:[{value:"own",label:"History"},{value:"catalogue",label:"Catalogue"}],optgroupOrder:["own","catalogue"],sortField:"endpoint",valueField:"endpoint",labelField:"endpoint",searchField:["endpoint","text"],render:{option:function(e,t){var n='<a href="javascript:void(0)" class="close pull-right" tabindex="-1" title="Remove from '+("own"==e.optgroup?"history":"catalogue")+'">×</a>',r='<div class="endpointUrl">'+t(e.endpoint)+"</div>",i="";e.text&&(i='<div class="endpointTitle">'+t(e.text)+"</div>");return'<div class="endpointOptionRow">'+n+r+i+"</div>"}}}};n=n?t.extend(!0,{},u,n):u;this.addClass("endpointText form-control");this.selectize(n.selectize);l[0].selectize.$dropdown.off("mousedown","[data-selectable]");l[0].selectize.$dropdown.on("mousedown","[data-selectable]",function(e){var n,r,i=l[0].selectize;if(e.preventDefault){e.preventDefault();e.stopPropagation()}r=t(e.currentTarget);if(t(e.target).hasClass("close")){l[0].selectize.removeOption(r.attr("data-value"));l[0].selectize.refreshOptions()}else if(r.hasClass("create"))i.createItem();else{n=r.attr("data-value");if("undefined"!=typeof n){i.lastQuery=null;i.setTextboxValue("");i.addItem(n);!i.settings.hideSelected&&e.type&&/mouse/.test(e.type)&&i.setActiveOption(i.getOption(n))}}});var p=function(e,t){t.optgroup&&s(t.optgroup)},c=function(e,t){if(e){l[0].selectize.off("option_add",p);e.forEach(function(e){l[0].selectize.addOption({endpoint:e.endpoint,text:e.title,optgroup:t})});l[0].selectize.on("option_add",p)}};a(c,"catalogue");a(c,"own");if(n.value){n.value in l[0].selectize.options||l[0].selectize.addOption({endpoint:n.value,optgroup:"own"});l[0].selectize.addItem(n.value)}return this};var i=function(){var e=[{endpoint:"http%3A%2F%2Fvisualdataweb.infor.uva.es%2Fsparql"},{endpoint:"http%3A%2F%2Fbiolit.rkbexplorer.com%2Fsparql",title:"A Short Biographical Dictionary of English Literature (RKBExplorer)"},{endpoint:"http%3A%2F%2Faemet.linkeddata.es%2Fsparql",title:"AEMET metereological dataset"},{endpoint:"http%3A%2F%2Fsparql.jesandco.org%3A8890%2Fsparql",title:"ASN:US"},{endpoint:"http%3A%2F%2Fdata.allie.dbcls.jp%2Fsparql",title:"Allie Abbreviation And Long Form Database in Life Science"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2FAustrianSkiTeam",title:"Alpine Ski Racers of Austria"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Feuropeana%2Fsparql%2F",title:"Amsterdam Museum as Linked Open Data in the Europeana Data Model"},{endpoint:"http%3A%2F%2Fopendata.aragon.es%2Fsparql",title:"AragoDBPedia"},{endpoint:"http%3A%2F%2Fdata.archiveshub.ac.uk%2Fsparql",title:"Archives Hub Linked Data"},{endpoint:"http%3A%2F%2Fwww.auth.gr%2Fsparql",title:"Aristotle University"},{endpoint:"http%3A%2F%2Facm.rkbexplorer.com%2Fsparql%2F",title:"Association for Computing Machinery (ACM) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fabs.270a.info%2Fsparql",title:"Australian Bureau of Statistics (ABS) Linked Data"},{endpoint:"http%3A%2F%2Flab.environment.data.gov.au%2Fsparql",title:"Australian Climate Observations Reference Network - Surface Air Temperature Dataset"},{endpoint:"http%3A%2F%2Flod.b3kat.de%2Fsparql",title:"B3Kat - Library Union Catalogues of Bavaria, Berlin and Brandenburg"},{endpoint:"http%3A%2F%2Fdati.camera.it%2Fsparql"},{endpoint:"http%3A%2F%2Fbis.270a.info%2Fsparql",title:"Bank for International Settlements (BIS) Linked Data"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fbdgp_20081030",title:"Bdgp"},{endpoint:"http%3A%2F%2Faffymetrix.bio2rdf.org%2Fsparql",title:"Bio2RDF::Affymetrix"},{endpoint:"http%3A%2F%2Fbiomodels.bio2rdf.org%2Fsparql",title:"Bio2RDF::Biomodels"},{endpoint:"http%3A%2F%2Fbioportal.bio2rdf.org%2Fsparql",title:"Bio2RDF::Bioportal"},{endpoint:"http%3A%2F%2Fclinicaltrials.bio2rdf.org%2Fsparql",title:"Bio2RDF::Clinicaltrials"},{endpoint:"http%3A%2F%2Fctd.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ctd"},{endpoint:"http%3A%2F%2Fdbsnp.bio2rdf.org%2Fsparql",title:"Bio2RDF::Dbsnp"},{endpoint:"http%3A%2F%2Fdrugbank.bio2rdf.org%2Fsparql",title:"Bio2RDF::Drugbank"},{endpoint:"http%3A%2F%2Fgenage.bio2rdf.org%2Fsparql",title:"Bio2RDF::Genage"},{endpoint:"http%3A%2F%2Fgendr.bio2rdf.org%2Fsparql",title:"Bio2RDF::Gendr"},{endpoint:"http%3A%2F%2Fgoa.bio2rdf.org%2Fsparql",title:"Bio2RDF::Goa"},{endpoint:"http%3A%2F%2Fhgnc.bio2rdf.org%2Fsparql",title:"Bio2RDF::Hgnc"},{endpoint:"http%3A%2F%2Fhomologene.bio2rdf.org%2Fsparql",title:"Bio2RDF::Homologene"},{endpoint:"http%3A%2F%2Finoh.bio2rdf.org%2Fsparql",title:"Bio2RDF::INOH"},{endpoint:"http%3A%2F%2Finterpro.bio2rdf.org%2Fsparql",title:"Bio2RDF::Interpro"},{endpoint:"http%3A%2F%2Fiproclass.bio2rdf.org%2Fsparql",title:"Bio2RDF::Iproclass"},{endpoint:"http%3A%2F%2Firefindex.bio2rdf.org%2Fsparql",title:"Bio2RDF::Irefindex"},{endpoint:"http%3A%2F%2Fbiopax.kegg.bio2rdf.org%2Fsparql",title:"Bio2RDF::KEGG::BioPAX"},{endpoint:"http%3A%2F%2Flinkedspl.bio2rdf.org%2Fsparql",title:"Bio2RDF::Linkedspl"},{endpoint:"http%3A%2F%2Flsr.bio2rdf.org%2Fsparql",title:"Bio2RDF::Lsr"},{endpoint:"http%3A%2F%2Fmesh.bio2rdf.org%2Fsparql",title:"Bio2RDF::Mesh"},{endpoint:"http%3A%2F%2Fmgi.bio2rdf.org%2Fsparql",title:"Bio2RDF::Mgi"},{endpoint:"http%3A%2F%2Fncbigene.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ncbigene"},{endpoint:"http%3A%2F%2Fndc.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ndc"},{endpoint:"http%3A%2F%2Fnetpath.bio2rdf.org%2Fsparql",title:"Bio2RDF::NetPath"},{endpoint:"http%3A%2F%2Fomim.bio2rdf.org%2Fsparql",title:"Bio2RDF::Omim"},{endpoint:"http%3A%2F%2Forphanet.bio2rdf.org%2Fsparql",title:"Bio2RDF::Orphanet"},{endpoint:"http%3A%2F%2Fpid.bio2rdf.org%2Fsparql",title:"Bio2RDF::PID"},{endpoint:"http%3A%2F%2Fbiopax.pharmgkb.bio2rdf.org%2Fsparql",title:"Bio2RDF::PharmGKB::BioPAX"},{endpoint:"http%3A%2F%2Fpharmgkb.bio2rdf.org%2Fsparql",title:"Bio2RDF::Pharmgkb"},{endpoint:"http%3A%2F%2Fpubchem.bio2rdf.org%2Fsparql",title:"Bio2RDF::PubChem"},{endpoint:"http%3A%2F%2Frhea.bio2rdf.org%2Fsparql",title:"Bio2RDF::Rhea"},{endpoint:"http%3A%2F%2Fspike.bio2rdf.org%2Fsparql",title:"Bio2RDF::SPIKE"},{endpoint:"http%3A%2F%2Fsabiork.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sabiork"},{endpoint:"http%3A%2F%2Fsgd.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sgd"},{endpoint:"http%3A%2F%2Fsider.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sider"},{endpoint:"http%3A%2F%2Ftaxonomy.bio2rdf.org%2Fsparql",title:"Bio2RDF::Taxonomy"},{endpoint:"http%3A%2F%2Fwikipathways.bio2rdf.org%2Fsparql",title:"Bio2RDF::Wikipathways"},{endpoint:"http%3A%2F%2Fwormbase.bio2rdf.org%2Fsparql",title:"Bio2RDF::Wormbase"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fbiomodels%2Fsparql",title:"BioModels RDF"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fbiosamples%2Fsparql",title:"BioSamples RDF"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Fbizkaisense%2Fsparql",title:"BizkaiSense"},{endpoint:"http%3A%2F%2Fbnb.data.bl.uk%2Fsparql"},{endpoint:"http%3A%2F%2Fbudapest.rkbexplorer.com%2Fsparql%2F",title:"Budapest University of Technology and Economics (RKBExplorer)"},{endpoint:"http%3A%2F%2Fbfs.270a.info%2Fsparql",title:"Bundesamt für Statistik (BFS) - Swiss Federal Statistical Office (FSO) Linked Data"},{endpoint:"http%3A%2F%2Fopendata-bundestag.de%2Fsparql",title:"BundestagNebeneinkuenfte"},{endpoint:"http%3A%2F%2Fdata.colinda.org%2Fendpoint.php",title:"COLINDA - Conference Linked Data"},{endpoint:"http%3A%2F%2Fcrtm.linkeddata.es%2Fsparql",title:"CRTM"},{endpoint:"http%3A%2F%2Fdata.fundacionctic.org%2Fsparql",title:"CTIC Public Dataset Catalogs"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fchembl%2Fsparql",title:"ChEMBL RDF"},{endpoint:"http%3A%2F%2Fchebi.bio2rdf.org%2Fsparql",title:"Chemical Entities of Biological Interest (ChEBI)"},{endpoint:"http%3A%2F%2Fciteseer.rkbexplorer.com%2Fsparql%2F",title:"CiteSeer (Research Index) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fcordis.rkbexplorer.com%2Fsparql%2F",title:"Community R&D Information Service (CORDIS) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsemantic.ckan.net%2Fsparql%2F",title:"Comprehensive Knowledge Archive Network"},{endpoint:"http%3A%2F%2Fvocabulary.wolterskluwer.de%2FPoolParty%2Fsparql%2Fcourt",title:"Courts thesaurus"},{endpoint:"http%3A%2F%2Fcultura.linkeddata.es%2Fsparql",title:"CulturaLinkedData"},{endpoint:"http%3A%2F%2Fdblp.rkbexplorer.com%2Fsparql%2F",title:"DBLP Computer Science Bibliography (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdblp.l3s.de%2Fd2r%2Fsparql",title:"DBLP in RDF (L3S)"},{endpoint:"http%3A%2F%2Fdbtune.org%2Fmusicbrainz%2Fsparql",title:"DBTune.org Musicbrainz D2R Server"},{endpoint:"http%3A%2F%2Fdbpedia.org%2Fsparql",title:"DBpedia"},{endpoint:"http%3A%2F%2Feu.dbpedia.org%2Fsparql",title:"DBpedia in Basque"},{endpoint:"http%3A%2F%2Fnl.dbpedia.org%2Fsparql",title:"DBpedia in Dutch"},{endpoint:"http%3A%2F%2Ffr.dbpedia.org%2Fsparql",title:"DBpedia in French"},{endpoint:"http%3A%2F%2Fde.dbpedia.org%2Fsparql",title:"DBpedia in German"},{endpoint:"http%3A%2F%2Fja.dbpedia.org%2Fsparql",title:"DBpedia in Japanese"},{endpoint:"http%3A%2F%2Fpt.dbpedia.org%2Fsparql",title:"DBpedia in Portuguese"},{endpoint:"http%3A%2F%2Fes.dbpedia.org%2Fsparql",title:"DBpedia in Spanish"},{endpoint:"http%3A%2F%2Flive.dbpedia.org%2Fsparql",title:"DBpedia-Live"},{endpoint:"http%3A%2F%2Fdeploy.rkbexplorer.com%2Fsparql%2F",title:"DEPLOY (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.ox.ac.uk%2Fsparql%2F"},{endpoint:"http%3A%2F%2Fdatos.bcn.cl%2Fsparql",title:"Datos.bcn.cl"},{endpoint:"http%3A%2F%2Fdeepblue.rkbexplorer.com%2Fsparql%2F",title:"Deep Blue (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdewey.info%2Fsparql.php",title:"Dewey Decimal Classification (DDC)"},{endpoint:"http%3A%2F%2Frdf.disgenet.org%2Fsparql%2F",title:"DisGeNET"},{endpoint:"http%3A%2F%2Fitaly.rkbexplorer.com%2Fsparql",title:"Diverse Italian ReSIST Partner Institutions (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdutchshipsandsailors.nl%2Fdata%2Fsparql%2F",title:"Dutch Ships and Sailors "},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fdss%2Fsparql%2F",title:"Dutch Ships and Sailors "},{endpoint:"http%3A%2F%2Fwww.eclap.eu%2Fsparql",title:"ECLAP"},{endpoint:"http%3A%2F%2Fcr.eionet.europa.eu%2Fsparql"},{endpoint:"http%3A%2F%2Fera.rkbexplorer.com%2Fsparql%2F",title:"ERA - Australian Research Council publication ratings (RKBExplorer)"},{endpoint:"http%3A%2F%2Fkent.zpr.fer.hr%3A8080%2FeducationalProgram%2Fsparql",title:"Educational programs - SISVU"},{endpoint:"http%3A%2F%2Fwebenemasuno.linkeddata.es%2Fsparql",title:"El Viajero's tourism dataset"},{endpoint:"http%3A%2F%2Fwww.ida.liu.se%2Fprojects%2Fsemtech%2Fopenrdf-sesame%2Frepositories%2Fenergy",title:"Energy efficiency assessments and improvements"},{endpoint:"http%3A%2F%2Fheritagedata.org%2Flive%2Fsparql"},{endpoint:"http%3A%2F%2Fenipedia.tudelft.nl%2Fsparql",title:"Enipedia - Energy Industry Data"},{endpoint:"http%3A%2F%2Fenvironment.data.gov.uk%2Fsparql%2Fbwq%2Fquery",title:"Environment Agency Bathing Water Quality"},{endpoint:"http%3A%2F%2Fecb.270a.info%2Fsparql",title:"European Central Bank (ECB) Linked Data"},{endpoint:"http%3A%2F%2Fsemantic.eea.europa.eu%2Fsparql"},{endpoint:"http%3A%2F%2Feuropeana.ontotext.com%2Fsparql"},{endpoint:"http%3A%2F%2Feventmedia.eurecom.fr%2Fsparql",title:"EventMedia"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fforge%2Fquery",title:"FORGE Course information"},{endpoint:"http%3A%2F%2Ffactforge.net%2Fsparql",title:"Fact Forge"},{endpoint:"http%3A%2F%2Flogd.tw.rpi.edu%2Fsparql"},{endpoint:"http%3A%2F%2Ffrb.270a.info%2Fsparql",title:"Federal Reserve Board (FRB) Linked Data"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflybase",title:"Flybase"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflyted",title:"Flyted"},{endpoint:"http%3A%2F%2Ffao.270a.info%2Fsparql",title:"Food and Agriculture Organization of the United Nations (FAO) Linked Data"},{endpoint:"http%3A%2F%2Fft.rkbexplorer.com%2Fsparql%2F",title:"France Telecom Recherche et Développement (RKBExplorer)"},{endpoint:"http%3A%2F%2Flisbon.rkbexplorer.com%2Fsparql",title:"Fundação da Faculdade de Ciencas da Universidade de Lisboa (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fatlas%2Fsparql",title:"Gene Expression Atlas RDF"},{endpoint:"http%3A%2F%2Fgeo.linkeddata.es%2Fsparql",title:"GeoLinkedData"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2FGeologicTimeScale",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2FGeologicUnit",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2Flithology",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2Ftectonicunit",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fvocabulary.wolterskluwer.de%2FPoolParty%2Fsparql%2Farbeitsrecht",title:"German labor law thesaurus"},{endpoint:"http%3A%2F%2Fdata.globalchange.gov%2Fsparql",title:"Global Change Information System"},{endpoint:"http%3A%2F%2Fwordnet.okfn.gr%3A8890%2Fsparql%2F",title:"Greek Wordnet"},{endpoint:"http%3A%2F%2Flod.hebis.de%2Fsparql",title:"HeBIS - Bibliographic Resources of the Library Union Catalogues of Hessen and parts of the Rhineland Palatinate"},{endpoint:"http%3A%2F%2Fhealthdata.tw.rpi.edu%2Fsparql",title:"HealthData.gov Platform (HDP) on the Semantic Web"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Fhedatuz%2Fsparql",title:"Hedatuz"},{endpoint:"http%3A%2F%2Fgreek-lod.auth.gr%2Ffire-brigade%2Fsparql",title:"Hellenic Fire Brigade"},{endpoint:"http%3A%2F%2Fgreek-lod.auth.gr%2Fpolice%2Fsparql",title:"Hellenic Police"},{endpoint:"http%3A%2F%2Fsetaria.oszk.hu%2Fsparql",title:"Hungarian National Library (NSZL) catalog"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fiati%2Fsparql%2F",title:"IATI as Linked Data"},{endpoint:"http%3A%2F%2Fibm.rkbexplorer.com%2Fsparql%2F",title:"IBM Research GmbH (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwww.icane.es%2Fopendata%2Fsparql",title:"ICANE"},{endpoint:"http%3A%2F%2Fieee.rkbexplorer.com%2Fsparql%2F",title:"IEEE Papers (RKBExplorer)"},{endpoint:"http%3A%2F%2Fieeevis.tw.rpi.edu%2Fsparql",title:"IEEE VIS Source Data"},{endpoint:"http%3A%2F%2Fwww.imagesnippets.com%2Fsparql%2Fimages",title:"Imagesnippets Image Descriptions"},{endpoint:"http%3A%2F%2Fopendatacommunities.org%2Fsparql"},{endpoint:"http%3A%2F%2Fpurl.org%2Ftwc%2Fhub%2Fsparql",title:"Instance Hub (all)"},{endpoint:"http%3A%2F%2Feurecom.rkbexplorer.com%2Fsparql%2F",title:"Institut Eurécom (RKBExplorer)"},{endpoint:"http%3A%2F%2Fimf.270a.info%2Fsparql",title:"International Monetary Fund (IMF) Linked Data"},{endpoint:"http%3A%2F%2Fwww.rechercheisidore.fr%2Fsparql",title:"Isidore"},{endpoint:"http%3A%2F%2Fsparql.kupkb.org%2Fsparql",title:"Kidney and Urinary Pathway Knowledge Base"},{endpoint:"http%3A%2F%2Fkisti.rkbexplorer.com%2Fsparql%2F",title:"Korean Institute of Science Technology and Information (RKBExplorer)"},{endpoint:"http%3A%2F%2Flod.kaist.ac.kr%2Fsparql",title:"Korean Traditional Recipes"},{endpoint:"http%3A%2F%2Flaas.rkbexplorer.com%2Fsparql%2F",title:"LAAS-CNRS (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsmartcity.linkeddata.es%2Fsparql",title:"LCC (Leeds City Council Energy Consumption Linked Data)"},{endpoint:"http%3A%2F%2Flod.ac%2Fbdls%2Fsparql",title:"LODAC BDLS"},{endpoint:"http%3A%2F%2Fdata.linkededucation.org%2Frequest%2Flak-conference%2Fsparql",title:"Learning Analytics and Knowledge (LAK) Dataset"},{endpoint:"http%3A%2F%2Fwww.linklion.org%3A8890%2Fsparql",title:"LinkLion - A Link Repository for the Web of Data"},{endpoint:"http%3A%2F%2Fsparql.reegle.info%2F",title:"Linked Clean Energy Data (reegle.info)"},{endpoint:"http%3A%2F%2Fsparql.contextdatacloud.org",title:"Linked Crowdsourced Data"},{endpoint:"http%3A%2F%2Flinkedlifedata.com%2Fsparql",title:"Linked Life Data"},{endpoint:"http%3A%2F%2Fdata.logainm.ie%2Fsparql",title:"Linked Logainm"},{endpoint:"http%3A%2F%2Fdata.linkedmdb.org%2Fsparql",title:"Linked Movie DataBase"},{endpoint:"http%3A%2F%2Fdata.aalto.fi%2Fsparql",title:"Linked Open Aalto Data Service"},{endpoint:"http%3A%2F%2Fdbmi-icode-01.dbmi.pitt.edu%2FlinkedSPLs%2Fsparql",title:"Linked Structured Product Labels"},{endpoint:"http%3A%2F%2Flinkedgeodata.org%2Fsparql%2F",title:"LinkedGeoData"},{endpoint:"http%3A%2F%2Flinkedspending.aksw.org%2Fsparql",title:"LinkedSpending: OpenSpending becomes Linked Open Data"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Flinkedstats%2Fsparql",title:"LinkedStats"},{endpoint:"http%3A%2F%2Flinkedu.eu%2Fcatalogue%2Fsparql%2F",title:"LinkedUp Catalogue of Educational Datasets"},{endpoint:"http%3A%2F%2Fid.sgcb.mcu.es%2Fsparql",title:"Lista de Encabezamientos de Materia as Linked Open Data"},{endpoint:"http%3A%2F%2Fonto.mondis.cz%2Fopenrdf-sesame%2Frepositories%2Fmondis-record-owlim",title:"MONDIS"},{endpoint:"http%3A%2F%2Fapps.morelab.deusto.es%2Flabman%2Fsparql",title:"MORElab"},{endpoint:"http%3A%2F%2Fsparql.msc2010.org",title:"Mathematics Subject Classification"},{endpoint:"http%3A%2F%2Fdoc.metalex.eu%3A8000%2Fsparql%2F",title:"MetaLex Document Server"},{endpoint:"http%3A%2F%2Frdf.muninn-project.org%2Fsparql",title:"Muninn World War I"},{endpoint:"http%3A%2F%2Flod.sztaki.hu%2Fsparql",title:"National Digital Data Archive of Hungary (partial)"},{endpoint:"http%3A%2F%2Fnsf.rkbexplorer.com%2Fsparql%2F",title:"National Science Foundation (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.nobelprize.org%2Fsparql",title:"Nobel Prizes"},{endpoint:"http%3A%2F%2Fdata.lenka.no%2Fsparql",title:"Norwegian geo-divisions"},{endpoint:"http%3A%2F%2Fspatial.ucd.ie%2Flod%2Fsparql",title:"OSM Semantic Network"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fdon%2Fquery",title:"OUNL DSpace in RDF"},{endpoint:"http%3A%2F%2Fdata.oceandrilling.org%2Fsparql"},{endpoint:"http%3A%2F%2Fonto.beef.org.pl%2Fsparql",title:"OntoBeef"},{endpoint:"http%3A%2F%2Foai.rkbexplorer.com%2Fsparql%2F",title:"Open Archive Initiative Harvest over OAI-PMH (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Focw%2Fquery",title:"Open Courseware Consortium metadata in RDF"},{endpoint:"http%3A%2F%2Fopendata.ccd.uniroma2.it%2FLMF%2Fsparql%2Fselect",title:"Open Data @ Tor Vergata"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2FOpenData",title:"Open Data Thesaurus"},{endpoint:"http%3A%2F%2Fdata.cnr.it%2Fsparql-proxy%2F",title:"Open Data from the Italian National Research Council"},{endpoint:"http%3A%2F%2Fdata.utpl.edu.ec%2Fecuadorresearch%2Flod%2Fsparql",title:"Open Data of Ecuador"},{endpoint:"http%3A%2F%2Fen.openei.org%2Fsparql",title:"OpenEI - Open Energy Info"},{endpoint:"http%3A%2F%2Flod.openlinksw.com%2Fsparql",title:"OpenLink Software LOD Cache"},{endpoint:"http%3A%2F%2Fsparql.openmobilenetwork.org",title:"OpenMobileNetwork"},{endpoint:"http%3A%2F%2Fapps.ideaconsult.net%3A8080%2Fontology",title:"OpenTox"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Fcoins%2Fsparql",title:"OpenUpLabs COINS"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Fdclg%2Fsparql",title:"OpenUpLabs DCLG"},{endpoint:"http%3A%2F%2Fos.services.tso.co.uk%2Fgeo%2Fsparql",title:"OpenUpLabs Geographic"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Flegislation%2Fsparql",title:"OpenUpLabs Legislation"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Ftransport%2Fsparql",title:"OpenUpLabs Transport"},{endpoint:"http%3A%2F%2Fos.rkbexplorer.com%2Fsparql%2F",title:"Ordnance Survey (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.organic-edunet.eu%2Fsparql",title:"Organic Edunet Linked Open Data"},{endpoint:"http%3A%2F%2Foecd.270a.info%2Fsparql",title:"Organisation for Economic Co-operation and Development (OECD) Linked Data"},{endpoint:"https%3A%2F%2Fdata.ox.ac.uk%2Fsparql%2F",title:"OxPoints (University of Oxford)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fprod%2Fquery",title:"PROD - JISC Project Directory in RDF"},{endpoint:"http%3A%2F%2Fld.panlex.org%2Fsparql",title:"PanLex"},{endpoint:"http%3A%2F%2Flinked-data.org%2Fsparql",title:"Phonetics Information Base and Lexicon (PHOIBLE)"},{endpoint:"http%3A%2F%2Flinked.opendata.cz%2Fsparql",title:"Publications of Charles University in Prague"},{endpoint:"http%3A%2F%2Flinkeddata4.dia.fi.upm.es%3A8907%2Fsparql",title:"RDFLicense"},{endpoint:"http%3A%2F%2Frisks.rkbexplorer.com%2Fsparql%2F",title:"RISKS Digest (RKBExplorer)"},{endpoint:"http%3A%2F%2Fruian.linked.opendata.cz%2Fsparql",title:"RUIAN - Register of territorial identification, addresses and real estates of the Czech Republic"},{endpoint:"http%3A%2F%2Fcurriculum.rkbexplorer.com%2Fsparql%2F",title:"ReSIST MSc in Resilient Computing Curriculum (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwiki.rkbexplorer.com%2Fsparql%2F",title:"ReSIST Project Wiki (RKBExplorer)"},{endpoint:"http%3A%2F%2Fresex.rkbexplorer.com%2Fsparql%2F",title:"ReSIST Resilience Mechanisms (RKBExplorer.com)"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Freactome%2Fsparql",title:"Reactome RDF"},{endpoint:"http%3A%2F%2Flod.xdams.org%2Fsparql"},{endpoint:"http%3A%2F%2Frae2001.rkbexplorer.com%2Fsparql%2F",title:"Research Assessment Exercise 2001 (RKBExplorer)"},{endpoint:"http%3A%2F%2Fcourseware.rkbexplorer.com%2Fsparql%2F",title:"Resilient Computing Courseware (RKBExplorer)"},{endpoint:"http%3A%2F%2Flink.informatics.stonybrook.edu%2Fsparql%2F",title:"RxNorm"},{endpoint:"http%3A%2F%2Fdata.rism.info%2Fsparql"},{endpoint:"http%3A%2F%2Fbiordf.net%2Fsparql",title:"SADI Semantic Web Services framework registry"},{endpoint:"http%3A%2F%2Fseek.rkbexplorer.com%2Fsparql%2F",title:"SEEK-AT-WD ICT tools for education - Web-Share"},{endpoint:"http%3A%2F%2Fzbw.eu%2Fbeta%2Fsparql%2Fstw%2Fquery",title:"STW Thesaurus for Economics"},{endpoint:"http%3A%2F%2Fsouthampton.rkbexplorer.com%2Fsparql%2F",title:"School of Electronics and Computer Science, University of Southampton (RKBExplorer)"},{endpoint:"http%3A%2F%2Fserendipity.utpl.edu.ec%2Flod%2Fsparql",title:"Serendipity"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fslidewiki%2Fquery",title:"Slidewiki (RDF/SPARQL)"},{endpoint:"http%3A%2F%2Fsmartlink.open.ac.uk%2Fsmartlink%2Fsparql",title:"SmartLink: Linked Services Non-Functional Properties"},{endpoint:"http%3A%2F%2Fsocialarchive.iath.virginia.edu%2Fsparql%2Feac",title:"Social Networks and Archival Context Fall 2011"},{endpoint:"http%3A%2F%2Fsocialarchive.iath.virginia.edu%2Fsparql%2Fsnac-viaf",title:"Social Networks and Archival Context Fall 2011"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2Fsemweb",title:"Social Semantic Web Thesaurus"},{endpoint:"http%3A%2F%2Flinguistic.linkeddata.es%2Fsparql",title:"Spanish Linguistic Datasets"},{endpoint:"http%3A%2F%2Fcrashmap.okfn.gr%3A8890%2Fsparql",title:"Statistics on Fatal Traffic Accidents in greek roads"},{endpoint:"http%3A%2F%2Fcrime.rkbexplorer.com%2Fsparql%2F",title:"Street level crime reports for England and Wales"},{endpoint:"http%3A%2F%2Fsymbolicdata.org%3A8890%2Fsparql",title:"SymbolicData"},{endpoint:"http%3A%2F%2Fagalpha.mathbiol.org%2Frepositories%2Ftcga",title:"TCGA Roadmap"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Ftcm",title:"TCMGeneDIT Dataset"},{endpoint:"http%3A%2F%2Fdata.linkededucation.org%2Frequest%2Fted%2Fsparql",title:"TED Talks"},{endpoint:"http%3A%2F%2Fdarmstadt.rkbexplorer.com%2Fsparql%2F",title:"Technische Universität Darmstadt (RKBExplorer)"},{endpoint:"http%3A%2F%2Flinguistic.linkeddata.es%2Fterminesp%2Fsparql-editor",title:"Terminesp Linked Data"},{endpoint:"http%3A%2F%2Facademia6.poolparty.biz%2FPoolParty%2Fsparql%2FTesauro-Materias-BUPM",title:"Tesauro materias BUPM"},{endpoint:"http%3A%2F%2Fapps.morelab.deusto.es%2Fteseo%2Fsparql",title:"Teseo"},{endpoint:"http%3A%2F%2Flinkeddata.ge.imati.cnr.it%3A8890%2Fsparql",title:"ThIST"},{endpoint:"http%3A%2F%2Fring.ciard.net%2Fsparql1",title:"The CIARD RING"},{endpoint:"http%3A%2F%2Fvocab.getty.edu%2Fsparql"},{endpoint:"http%3A%2F%2Flod.gesis.org%2Fthesoz%2Fsparql",title:"TheSoz Thesaurus for the Social Sciences (GESIS)"},{endpoint:"http%3A%2F%2Fdigitale.bncf.firenze.sbn.it%2Fopenrdf-workbench%2Frepositories%2FNS%2Fquery",title:"Thesaurus BNCF"},{endpoint:"http%3A%2F%2Ftour-pedia.org%2Fsparql",title:"Tourpedia"},{endpoint:"http%3A%2F%2Ftkm.kiom.re.kr%2Fontology%2Fsparql",title:"Traditional Korean Medicine Ontology"},{endpoint:"http%3A%2F%2Ftransparency.270a.info%2Fsparql",title:"Transparency International Linked Data"},{endpoint:"http%3A%2F%2Fjisc.rkbexplorer.com%2Fsparql%2F",title:"UK JISC (RKBExplorer)"},{endpoint:"http%3A%2F%2Funlocode.rkbexplorer.com%2Fsparql%2F",title:"UN/LOCODE (RKBExplorer)"},{endpoint:"http%3A%2F%2Fuis.270a.info%2Fsparql",title:"UNESCO Institute for Statistics (UIS) Linked Data"},{endpoint:"http%3A%2F%2Fskos.um.es%2Fsparql%2F",title:"UNESCO Thesaurus"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fkis1112%2Fquery",title:"UNISTAT-KIS 2011/2012 in RDF (Key Information Set - UK Universities)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fkis%2Fquery",title:"UNISTAT-KIS in RDF (Key Information Set - UK Universities)"},{endpoint:"http%3A%2F%2Flinkeddata.uriburner.com%2Fsparql",title:"URIBurner"},{endpoint:"http%3A%2F%2Fbeta.sparql.uniprot.org"},{endpoint:"http%3A%2F%2Fdata.utpl.edu.ec%2Futpl%2Flod%2Fsparql",title:"Universidad Técnica Particular de Loja - Linked Open Data"},{endpoint:"http%3A%2F%2Fresrev.ilrt.bris.ac.uk%2Fdata-server-workshop%2Fsparql",title:"University of Bristol"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fhud%2Fquery",title:"University of Huddersfield -- Circulation and Recommendation Data"},{endpoint:"http%3A%2F%2Fnewcastle.rkbexplorer.com%2Fsparql%2F",title:"University of Newcastle upon Tyne (RKBExplorer)"},{endpoint:"http%3A%2F%2Froma.rkbexplorer.com%2Fsparql%2F",title:'Università degli studi di Roma "La Sapienza" (RKBExplorer)'},{endpoint:"http%3A%2F%2Fpisa.rkbexplorer.com%2Fsparql%2F",title:"Università di Pisa (RKBExplorer)"},{endpoint:"http%3A%2F%2Fulm.rkbexplorer.com%2Fsparql%2F",title:"Universität Ulm (RKBExplorer)"},{endpoint:"http%3A%2F%2Firit.rkbexplorer.com%2Fsparql%2F",title:"Université Paul Sabatier - Toulouse 3 (RKB Explorer)"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fverrijktkoninkrijk%2Fsparql%2F",title:"Verrijkt Koninkrijk"},{endpoint:"http%3A%2F%2Fkaunas.rkbexplorer.com%2Fsparql",title:"Vytautas Magnus University, Kaunas (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwebscience.rkbexplorer.com%2Fsparql",title:"Web Science Conference (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsparql.wikipathways.org%2F",title:"WikiPathways"},{endpoint:"http%3A%2F%2Fwww.opmw.org%2Fsparql",title:"Wings workflow provenance dataset"},{endpoint:"http%3A%2F%2Fwordnet.rkbexplorer.com%2Fsparql%2F",title:"WordNet (RKBExplorer)"},{endpoint:"http%3A%2F%2Fworldbank.270a.info%2Fsparql",title:"World Bank Linked Data"},{endpoint:"http%3A%2F%2Fmlode.nlp2rdf.org%2Fsparql"},{endpoint:"http%3A%2F%2Fldf.fi%2Fww1lod%2Fsparql",title:"World War 1 as Linked Open Data"},{endpoint:"http%3A%2F%2Faksw.org%2Fsparql",title:"aksw.org Research Group dataset"},{endpoint:"http%3A%2F%2Fcrm.rkbexplorer.com%2Fsparql",title:"crm"},{endpoint:"http%3A%2F%2Fdata.open.ac.uk%2Fquery",title:"data.open.ac.uk, Linked Data from the Open University"},{endpoint:"http%3A%2F%2Fsparql.data.southampton.ac.uk%2F"},{endpoint:"http%3A%2F%2Fdatos.bne.es%2Fsparql",title:"datos.bne.es"},{endpoint:"http%3A%2F%2Fkaiko.getalp.org%2Fsparql",title:"dbnary"},{endpoint:"http%3A%2F%2Fdigitaleconomy.rkbexplorer.com%2Fsparql",title:"digitaleconomy"},{endpoint:"http%3A%2F%2Fdotac.rkbexplorer.com%2Fsparql%2F",title:"dotAC (RKBExplorer)"},{endpoint:"http%3A%2F%2Fforeign.rkbexplorer.com%2Fsparql%2F",title:"ePrints Harvest (RKBExplorer)"},{endpoint:"http%3A%2F%2Feprints.rkbexplorer.com%2Fsparql%2F",title:"ePrints3 Institutional Archive Collection (RKBExplorer)"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Feducation%2Fsparql",title:"education.data.gov.uk"},{endpoint:"http%3A%2F%2Fepsrc.rkbexplorer.com%2Fsparql",title:"epsrc"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflyatlas",title:"flyatlas"},{endpoint:"http%3A%2F%2Fiserve.kmi.open.ac.uk%2Fiserve%2Fsparql",title:"iServe: Linked Services Registry"},{endpoint:"http%3A%2F%2Fichoose.tw.rpi.edu%2Fsparql",title:"ichoose"},{endpoint:"http%3A%2F%2Fkdata.kr%2Fsparql%2Fendpoint.jsp",title:"kdata"},{endpoint:"http%3A%2F%2Flofd.tw.rpi.edu%2Fsparql",title:"lofd"},{endpoint:"http%3A%2F%2Fprovenanceweb.org%2Fsparql",title:"provenanceweb"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Freference%2Fsparql",title:"reference.data.gov.uk"},{endpoint:"http%3A%2F%2Fforeign.rkbexplorer.com%2Fsparql",title:"rkb-explorer-foreign"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Fstatistics%2Fsparql",title:"statistics.data.gov.uk"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Ftransport%2Fsparql",title:"transport.data.gov.uk"},{endpoint:"http%3A%2F%2Fopendap.tw.rpi.edu%2Fsparql",title:"twc-opendap"},{endpoint:"http%3A%2F%2Fwebconf.rkbexplorer.com%2Fsparql",title:"webconf"},{endpoint:"http%3A%2F%2Fwiktionary.dbpedia.org%2Fsparql",title:"wiktionary.dbpedia.org"},{endpoint:"http%3A%2F%2Fdiwis.imis.athena-innovation.gr%3A8181%2Fsparql",title:"xxxxx"}];e.forEach(function(t,n){e[n].endpoint=decodeURIComponent(t.endpoint)});e.sort(function(e,t){var n=e.title||e.endpoint,r=t.title||t.endpoint;return n.toUpperCase().localeCompare(r.toUpperCase())});return e}},{jquery:void 0,selectize:8,"yasgui-utils":14}],96:[function(e){e("../../node_modules/jquery-ui/resizable.js");e("./outsideclick.js");e("./tab.js");e("./endpointCombi.js")},{"../../node_modules/jquery-ui/resizable.js":6,"./endpointCombi.js":95,"./outsideclick.js":97,"./tab.js":98}],97:[function(e){"use strict";var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.fn.onOutsideClick=function(e,n){n=t.extend({skipFirst:!1,allowedElements:t()},n);var r=t(this),i=function(o){var s=function(e){return!e.is(o.target)&&0===e.has(o.target).length};if(s(r)&&s(n.allowedElements))if(n.skipFirst)n.skipFirst=!1;else{e();t(document).off("mouseup",i)}};t(document).mouseup(i);return this}},{jquery:void 0}],98:[function(e){function t(e){return this.each(function(){var t=n(this),i=t.data("bs.tab");i||t.data("bs.tab",i=new r(this));"string"==typeof e&&i[e]()})}var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=function(e){this.element=n(e)};r.VERSION="3.3.1";r.TRANSITION_DURATION=150;r.prototype.show=function(){var e=this.element,t=e.closest("ul:not(.dropdown-menu)"),r=e.data("target");if(!r){r=e.attr("href");r=r&&r.replace(/.*(?=#[^\s]*$)/,"")}if(!e.parent("li").hasClass("active")){var i=t.find(".active:last a"),o=n.Event("hide.bs.tab",{relatedTarget:e[0]}),s=n.Event("show.bs.tab",{relatedTarget:i[0]});i.trigger(o);e.trigger(s);if(!s.isDefaultPrevented()&&!o.isDefaultPrevented()){var a=n(r);
this.activate(e.closest("li"),t);this.activate(a,a.parent(),function(){i.trigger({type:"hidden.bs.tab",relatedTarget:e[0]});e.trigger({type:"shown.bs.tab",relatedTarget:i[0]})})}}};r.prototype.activate=function(e,t,i){function o(){s.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1);e.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0);if(a){e[0].offsetWidth;e.addClass("in")}else e.removeClass("fade");e.parent(".dropdown-menu")&&e.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0);i&&i()}var s=t.find("> .active"),a=i&&n.support.transition&&(s.length&&s.hasClass("fade")||!!t.find("> .fade").length);s.length&&a?s.one("bsTransitionEnd",o).emulateTransitionEnd(r.TRANSITION_DURATION):o();s.removeClass("in")};var i=n.fn.tab;n.fn.tab=t;n.fn.tab.Constructor=r;n.fn.tab.noConflict=function(){n.fn.tab=i;return this};var o=function(e){e.preventDefault();t.call(n(this),"show")};n(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',o).on("click.bs.tab.data-api",'[data-toggle="pill"]',o)},{jquery:void 0}],99:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("yasgui-utils");e("./jquery/extendJquery.js");var i=function(e){var t='Endpoint is not <a href="http://enable-cors.org/" target="_blank">CORS-enabled</a>';e.api.corsProxy&&(t='Endpoint is not accessible from the YASGUI server and website, and the endpoint is not <a href="http://enable-cors.org/" target="_blank">CORS-enabled</a>');YASGUI.YASR.plugins.error.defaults.corsMessage=n("<div>").append(n("<p>").append("Unable to get response from endpoint. Possible reasons:")).append(n("<ul>").append(n("<li>").text("Incorrect endpoint URL")).append(n("<li>").text("Endpoint is down")).append(n("<li>").html(t)))},o=t.exports=function(t,s){var a={};a.wrapperElement=n('<div class="yasgui"></div>').appendTo(n(t));a.options=n.extend(!0,{},o.defaults,s);i(a.options);a.history=[];a.persistencyPrefix=null;a.options.persistencyPrefix&&(a.persistencyPrefix="function"==typeof a.options.persistencyPrefix?a.options.persistencyPrefix(a):a.options.persistencyPrefix);if(a.persistencyPrefix){var l=r.storage.get(a.persistencyPrefix+"history");l&&(a.history=l)}a.store=function(){a.persistentOptions&&r.storage.set(a.persistencyPrefix,a.persistentOptions)};var u=function(){var e=r.storage.get(a.persistencyPrefix);e||(e={});return e};a.persistentOptions=u();a.tabManager=e("./tabManager.js")(a);a.tabManager.init();a.tracker=e("./tracker.js")(a);return a};o.YASQE=e("./yasqe.js");o.YASR=e("./yasr.js");o.$=n;o.defaults=e("./defaults.js")},{"./defaults.js":93,"./jquery/extendJquery.js":96,"./tabManager.js":102,"./tracker.js":104,"./yasqe.js":106,"./yasr.js":107,jquery:void 0,"yasgui-utils":14}],100:[function(e,t){var n=function(e){var t=[];e||(e=window.location.search.substring(1));if(e.length>0)for(var n=e.split("&"),r=0;r<n.length;r++){var i=n[r].split("="),o=i[0],s=i[1];if(o.length>0&&s&&s.length>0){s=s.replace(/\+/g," ");s=decodeURIComponent(s);t.push({name:i[0],value:s})}}return t};t.exports={getCreateLinkHandler:function(e){return function(){var t=[{name:"outputFormat",value:e.yasr.options.output},{name:"query",value:e.yasqe.getValue()},{name:"contentTypeConstruct",value:e.persistentOptions.yasqe.sparql.acceptHeaderGraph},{name:"contentTypeSelect",value:e.persistentOptions.yasqe.sparql.acceptHeaderSelect},{name:"endpoint",value:e.persistentOptions.yasqe.sparql.endpoint},{name:"requestMethod",value:e.persistentOptions.yasqe.sparql.requestMethod},{name:"tabTitle",value:e.persistentOptions.name}];e.persistentOptions.yasqe.sparql.args.forEach(function(e){t.push(e)});e.persistentOptions.yasqe.sparql.namedGraphs.forEach(function(e){t.push({name:"namedGraph",value:e})});e.persistentOptions.yasqe.sparql.defaultGraphs.forEach(function(e){t.push({name:"defaultGraph",value:e})});var r=[];t.forEach(function(e){r.push(e.name)});var i=n();i.forEach(function(e){-1==r.indexOf(e.name)&&t.push(e)});return t}},getOptionsFromUrl:function(){var e={yasqe:{sparql:{}},yasr:{}},t=n(),r=!1;t.forEach(function(t){if("query"==t.name){r=!0;e.yasqe.value=t.value}else if("outputFormat"==t.name){var n=t.value;"simpleTable"==n&&(n="table");e.yasr.output=n}else if("contentTypeConstruct"==t.name)e.yasqe.sparql.acceptHeaderGraph=t.value;else if("contentTypeSelect"==t.name)e.yasqe.sparql.acceptHeaderSelect=t.value;else if("endpoint"==t.name)e.yasqe.sparql.endpoint=t.value;else if("requestMethod"==t.name)e.yasqe.sparql.requestMethod=t.value;else if("tabTitle"==t.name)e.name=t.value;else if("namedGraph"==t.name){e.yasqe.namedGraphs||(e.yasqe.namedGraphs=[]);e.yasqe.sparql.namedGraphs.push(t)}else if("defaultGraph"==t.name){e.yasqe.defaultGraphs||(e.yasqe.defaultGraphs=[]);e.yasqe.sparql.defaultGraphs.push(t)}else{e.yasqe.args||(e.yasqe.args=[]);e.yasqe.sparql.args.push(t)}});return r?e:null}}},{}],101:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=(e("./utils.js"),e("yasgui-utils")),i=e("underscore"),o=e("./main.js"),s={yasqe:{height:300,sparql:{endpoint:o.YASQE.defaults.sparql.endpoint,acceptHeaderGraph:o.YASQE.defaults.sparql.acceptHeaderGraph,acceptHeaderSelect:o.YASQE.defaults.sparql.acceptHeaderSelect,args:o.YASQE.defaults.sparql.args,defaultGraphs:o.YASQE.defaults.sparql.defaultGraphs,namedGraphs:o.YASQE.defaults.sparql.namedGraphs,requestMethod:o.YASQE.defaults.sparql.requestMethod}}};t.exports=function(t,a,l,u){t.persistentOptions.tabManager.tabs[a]=t.persistentOptions.tabManager.tabs[a]?n.extend(!0,{},s,t.persistentOptions.tabManager.tabs[a]):n.extend(!0,{id:a,name:l},s);var p=t.persistentOptions.tabManager.tabs[a];u&&(p.yasqe.sparql.endpoint=u);var c,d={persistentOptions:p},h=e("./tabPaneMenu.js")(t,d),f=n("<div>",{id:p.id,style:"position:relative","class":"tab-pane",role:"tabpanel"}).appendTo(t.tabManager.$tabPanesParent),g=n("<div>",{"class":"wrapper"}).appendTo(f),m=n("<div>",{"class":"controlbar"}).appendTo(g),E=(h.initWrapper().appendTo(f),function(){n("<button>",{type:"button","class":"menuButton btn btn-default"}).on("click",function(){if(f.hasClass("menu-open")){f.removeClass("menu-open");h.store()}else{h.updateWrapper();f.addClass("menu-open");n(".menu-slide,.menuButton").onOutsideClick(function(){f.removeClass("menu-open");h.store()})}}).append(n("<span>",{"class":"icon-bar"})).append(n("<span>",{"class":"icon-bar"})).append(n("<span>",{"class":"icon-bar"})).appendTo(m);c=n("<select>").appendTo(m).endpointCombi(t,{value:p.yasqe.sparql.endpoint,onChange:function(e){p.yasqe.sparql.endpoint=e;d.refreshYasqe();t.store()}})}),v=n("<div>",{id:"yasqe_"+p.id}).appendTo(g),x=n("<div>",{id:"yasq_"+p.id}).appendTo(g),y={createShareLink:e("./shareLink").getCreateLinkHandler(d)},N=function(){p.yasqe.value=d.yasqe.getValue();var e=null;d.yasr.results.getBindings()&&(e=d.yasr.results.getBindings().length);var i={options:n.extend(!0,{},p),resultSize:e};delete i.options.name;t.history.unshift(i);var o=50;t.history.length>o&&(t.history=t.history.slice(0,o));t.persistencyPrefix&&r.storage.set(t.persistencyPrefix+"history",t.history)};d.setPersistentInYasqe=function(){if(d.yasqe){n.extend(d.yasqe.options.sparql,p.yasqe.sparql);p.yasqe.value&&d.yasqe.setValue(p.yasqe.value)}};n.extend(y,p.yasqe);var I=function(){if(!d.yasr){d.yasqe||A();var e=function(){return p.yasqe.sparql.endpoint+"?"+n.param(d.yasqe.getUrlArguments(p.yasqe.sparql))};o.YASR.plugins.error.defaults.tryQueryLink=e;d.yasr=o.YASR(x[0],n.extend({getUsedPrefixes:d.yasqe.getPrefixesFromQuery},p.yasr))}},A=function(){if(!d.yasqe){E();d.yasqe=o.YASQE(v[0],y);d.yasqe.setSize("100%",p.yasqe.height);d.yasqe.on("blur",function(e){p.yasqe.value=e.getValue();t.store()});var e=null;d.yasqe.options.sparql.callbacks.beforeSend=function(){e=+new Date};d.yasqe.options.sparql.callbacks.complete=function(){var n=+new Date;t.tracker.track(p.yasqe.sparql.endpoint,d.yasqe.getValueWithoutComments(),n-e);d.yasr.setResponse.apply(this,arguments);N()};d.yasqe.query=function(){if(t.options.api.corsProxy&&t.corsEnabled)if(t.corsEnabled[p.yasqe.sparql.endpoint])o.YASQE.executeQuery(d.yasqe);else{var e=n.extend(!0,{},d.yasqe.options.sparql);e.args.push({name:"endpoint",value:e.endpoint});e.args.push({name:"requestMethod",value:e.requestMethod});e.requestMethod="POST";e.endpoint=t.options.api.corsProxy;o.YASQE.executeQuery(d.yasqe,e)}else o.YASQE.executeQuery(d.yasqe)}}};d.onShow=function(){A();d.yasqe.refresh();I();n(d.yasqe.getWrapperElement()).resizable({minHeight:200,handles:"s",resize:function(){i.debounce(function(){d.yasqe.setSize("100%",n(this).height());d.yasqe.refresh()},500)},stop:function(){p.yasqe.height=n(this).height();d.yasqe.refresh();t.store()}})};d.beforeShow=function(){A()};d.refreshYasqe=function(){if(d.yasqe){n.extend(!0,d.yasqe.options,d.persistentOptions.yasqe);d.persistentOptions.yasqe.value&&d.yasqe.setValue(d.persistentOptions.yasqe.value)}};d.destroy=function(){d.yasr||(d.yasr=o.YASR(x[0],{},""));r.storage.remove(d.yasr.getPersistencyId(d.yasr.options.persistency.results.key))};d.getEndpoint=function(){var e=null;r.nestedExists(d.persistentOptions,"yasqe","sparql","endpoint")&&(e=d.persistentOptions.yasqe.sparql.endpoint);return e};return d}},{"./main.js":99,"./shareLink":100,"./tabPaneMenu.js":103,"./utils.js":105,jquery:void 0,underscore:11,"yasgui-utils":14}],102:[function(e,t){"use strict";{var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("yasgui-utils"),e("./imgs.js")}e("jquery-ui/position");t.exports=function(t){t.persistentOptions.tabManager||(t.persistentOptions.tabManager={});var r=t.persistentOptions.tabManager,i={};i.tabs={};var o,s=null,a=null,l=function(e,t){e||(e="Query");t||(t=0);var n=e+(t>0?" "+t:"");u(n)&&(n=l(e,t+1));return n},u=function(e){for(var t in i.tabs)if(i.tabs[t].persistentOptions.name==e)return!0;return!1},p=function(){return Math.random().toString(36).substring(7)};i.init=function(){s=n("<div>",{role:"tabpanel"}).appendTo(t.wrapperElement);o=n("<ul>",{"class":"nav nav-tabs mainTabs",role:"tablist"}).appendTo(s);var l=n("<a>",{role:"addTab"}).click(function(){h()}).text("+");o.append(n("<li>",{role:"presentation"}).append(l));i.$tabPanesParent=n("<div>",{"class":"tab-content"}).appendTo(s);if(!r||n.isEmptyObject(r)){r.tabOrder=[];r.tabs={};r.selected=null}var u=e("./shareLink.js").getOptionsFromUrl();if(u){var f=p();u.id=f;r.tabs[f]=u;r.tabOrder.push(f);r.selected=f}r.tabOrder.length>0?r.tabOrder.forEach(h):h();o.sortable({placeholder:"tab-sortable-highlight",items:'li:has([data-toggle="tab"])',forcePlaceholderSize:!0,update:function(){var e=[];o.find('a[data-toggle="tab"]').each(function(){e.push(n(this).attr("aria-controls"))});r.tabOrder=e;t.store()}});a=n("<div>",{"class":"tabDropDown"}).appendTo(t.wrapperElement);var g=n("<ul>",{"class":"dropdown-menu",role:"menu"}).appendTo(a),m=function(e,t){var r=n("<li>",{role:"presentation"}).appendTo(g);e?r.append(n("<a>",{role:"menuitem",href:"#"}).text(e)).click(function(){a.hide();event.preventDefault();t&&t(a.attr("target-tab"))}):r.addClass("divider")};m("Add new Tab",function(){h()});m("Rename",function(e){o.find('a[href="#'+e+'"]').dblclick()});m("Copy",function(e){var t=p(),i=n.extend(!0,{},r.tabs[e]);i.id=t;r.tabs[t]=i;h(t);c(t)});m();m("Close",d);m("Close others",function(e){o.find('a[role="tab"]').each(function(){var t=n(this).attr("aria-controls");t!=e&&d(t)})});m("Close all",function(){o.find('a[role="tab"]').each(function(){d(n(this).attr("aria-controls"))})})};var c=function(e){o.find('a[aria-controls="'+e+'"]').tab("show");return i.current()},d=function(e){i.tabs[e].destroy();delete i.tabs[e];delete r.tabs[e];var s=r.tabOrder.indexOf(e);s>-1&&r.tabOrder.splice(s,1);var a=null;r.tabOrder[s]?a=s:r.tabOrder[s-1]&&(a=s-1);null!==a&&c(r.tabOrder[a]);o.find('a[href="#'+e+'"]').closest("li").remove();n("#"+e).remove();t.store();return i.current()},h=function(s){var u=!s;s||(s=p());"tabs"in r||(r.tabs={});var c=null;r.tabs[s]&&r.tabs[s].name&&(c=r.tabs[s].name);c||(c=l());var h=null;i.current&&i.current()&&i.current().getEndpoint()&&(h=i.current().getEndpoint());var f=n("<a>",{href:"#"+s,"aria-controls":s,role:"tab","data-toggle":"tab"}).click(function(e){e.preventDefault();n(this).tab("show");i.tabs[s].yasqe.refresh()}).on("shown.bs.tab",function(){r.selected=n(this).attr("aria-controls");i.tabs[s].onShow();t.store()}).append(n("<span>").text(c)).append(n("<button>",{"class":"close",type:"button"}).text("x").click(function(){d(s)})),g=n('<div><input type="text"></div>').keydown(function(){27==event.which||27==event.keyCode?n(this).closest("li").removeClass("rename"):(13==event.which||13==event.keyCode)&&m(n(this).closest("li"))}),m=function(e){var n=e.find('a[role="tab"]').attr("aria-controls"),i=e.find("input").val();f.find("span").text(e.find("input").val());r.tabs[n].name=i;t.store();e.removeClass("rename")},E=n("<li>",{role:"presentation"}).append(f).append(g).dblclick(function(){var e=n(this),t=e.find("span").text();e.addClass("rename");e.find("input").val(t);e.onOutsideClick(function(){m(e)})}).bind("contextmenu",function(e){e.preventDefault();a.show().onOutsideClick(function(){a.hide()},{allowedElements:n(this).closest("li")}).addClass("open").attr("target-tab",E.find('a[role="tab"]').attr("aria-controls")).position({my:"left top-3",at:"left bottom",of:n(this)})});o.find('li:has(a[role="addTab"])').before(E);u&&r.tabOrder.push(s);i.tabs[s]=e("./tab.js")(t,s,c,h);if(u||r.selected==s){i.tabs[s].beforeShow();f.tab("show")}return i.tabs[s]};i.current=function(){return i.tabs[r.selected]};i.addTab=h;return i}},{"./imgs.js":94,"./shareLink.js":100,"./tab.js":101,jquery:void 0,"jquery-ui/position":5,"yasgui-utils":14}],103:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("./imgs.js"),i=(e("selectize"),e("yasgui-utils"));t.exports=function(e,t){var o,s,a,l,u,p,c,d=null,h=null,f=null,g=null,m=null,E=function(){d=n("<nav>",{"class":"menu-slide",id:"navmenu"});d.append(n(i.svg.getElement(r.yasgui)).addClass("yasguiLogo").attr("title","About YASGUI").click(function(){window.open("http://about.yasgui.org","_blank")}));h=n("<div>",{role:"tabpanel"}).appendTo(d);f=n("<ul>",{"class":"nav nav-pills tabPaneMenuTabs",role:"tablist"}).appendTo(h);g=n("<div>",{"class":"tab-content"}).appendTo(h);var E=n("<li>",{role:"presentation"}).appendTo(f),v="yasgui_reqConfig_"+t.persistentOptions.id;E.append(n("<a>",{href:"#"+v,"aria-controls":v,role:"tab","data-toggle":"tab"}).text("Configure Request").click(function(e){e.preventDefault();n(this).tab("show")}));var x=n("<div>",{id:v,role:"tabpanel","class":"tab-pane requestConfig container-fluid"}).appendTo(g),y=n("<div>",{"class":"reqRow"}).appendTo(x);n("<div>",{"class":"rowLabel"}).appendTo(y).append(n("<span>").text("Request Method"));o=n("<button>",{"class":"btn btn-default ","data-toggle":"button"}).text("POST").click(function(){o.addClass("active");s.removeClass("active")});s=n("<button>",{"class":"btn btn-default","data-toggle":"button"}).text("GET").click(function(){s.addClass("active");o.removeClass("active")});n("<div>",{"class":"btn-group col-md-8",role:"group"}).append(s).append(o).appendTo(y);var N=n("<div>",{"class":"reqRow"}).appendTo(x);n("<div>",{"class":"rowLabel"}).appendTo(N).text("Accept Headers");a=n("<select>",{"class":"acceptHeader"}).append(n("<option>",{value:"application/sparql-results+json"}).text("JSON")).append(n("<option>",{value:"application/sparql-results+xml"}).text("XML")).append(n("<option>",{value:"text/csv"}).text("CSV")).append(n("<option>",{value:"text/tab-separated-values"}).text("TSV"));n("<div>",{"class":"col-md-4",role:"group"}).append(n("<label>").text("SELECT").append(a)).appendTo(N);a.selectize();l=n("<select>",{"class":"acceptHeader"}).append(n("<option>",{value:"text/turtle"}).text("Turtle")).append(n("<option>",{value:"application/rdf+xml"}).text("RDF-XML")).append(n("<option>",{value:"text/csv"}).text("CSV")).append(n("<option>",{value:"text/tab-separated-values"}).text("TSV"));n("<div>",{"class":"col-md-4",role:"group"}).append(n("<label>").text("Graph").append(l)).appendTo(N);l.selectize();var I=n("<div>",{"class":"reqRow"}).appendTo(x);n("<div>",{"class":"rowLabel"}).appendTo(I).text("URL Arguments");u=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(I);var A=n("<div>",{"class":"reqRow"}).appendTo(x);n("<div>",{"class":"rowLabel"}).appendTo(A).text("Default graphs");p=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(A);var T=n("<div>",{"class":"reqRow"}).appendTo(x);n("<div>",{"class":"rowLabel"}).appendTo(T).text("Named graphs");c=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(T);var E=n("<li>",{role:"presentation"}).appendTo(f),L="yasgui_history_"+t.persistentOptions.id;E.append(n("<a>",{href:"#"+L,"aria-controls":L,role:"tab","data-toggle":"tab"}).text("History").click(function(e){e.preventDefault();n(this).tab("show")}));var S=n("<div>",{id:L,role:"tabpanel","class":"tab-pane history container-fluid"}).appendTo(g);m=n("<ul>",{"class":"list-group"}).appendTo(S);if(e.options.api.collections){var E=n("<li>",{role:"presentation"}).appendTo(f),b="yasgui_collections_"+t.persistentOptions.id;E.append(n("<a>",{href:"#"+b,"aria-controls":b,role:"tab","data-toggle":"tab"}).text("Collections").click(function(e){e.preventDefault();n(this).tab("show")}));var x=n("<div>",{id:b,role:"tabpanel","class":"tab-pane collections container-fluid"}).appendTo(g)}return d},v=function(e,t,r,i){for(var o=n("<div>",{"class":"textInputsRow"}),s=0;t>s;s++){var a=i&&i[s]?i[s]:"";n("<input>",{type:"text"}).val(a).keyup(function(){var r=!1;e.find(".textInputsRow:last input").each(function(e,t){n(t).val().trim().length>0&&(r=!0)});r&&v(e,t,!0)}).css("width",92/t+"%").appendTo(o)}o.append(n("<button>",{"class":"close",type:"button"}).text("x").click(function(){n(this).closest(".textInputsRow").remove()}));r?o.hide().appendTo(e).show("fast"):o.appendTo(e)},x=function(){0==d.find(".tabPaneMenuTabs li.active").length&&d.find(".tabPaneMenuTabs a:first").tab("show");var r=t.persistentOptions.yasqe;"POST"==r.sparql.requestMethod.toUpperCase()?o.addClass("active"):s.addClass("active");l[0].selectize.setValue(r.sparql.acceptHeaderGraph);a[0].selectize.setValue(r.sparql.acceptHeaderSelect);u.empty();r.sparql.args&&r.sparql.args.length>0&&r.sparql.args.forEach(function(e){var t=[e.name,e.value];v(u,2,!1,t)});v(u,2,!1);p.empty();r.sparql.defaultGraphs&&r.sparql.defaultGraphs.length>0&&v(p,1,!1,r.sparql.defaultGraphs);v(p,1,!1);c.empty();r.sparql.namedGraphs&&r.sparql.namedGraphs.length>0&&v(c,1,!1,r.sparql.namedGraphs);v(c,1,!1);m.empty();0==e.history.length?m.append(n("<a>",{"class":"list-group-item disabled",href:"#"}).text("No items in history yet").click(function(e){e.preventDefault()})):e.history.forEach(function(t){var r=t.options.yasqe.sparql.endpoint;t.resultSize&&(r+=" ("+t.resultSize+" results)");m.append(n("<a>",{"class":"list-group-item",href:"#",title:t.options.yasqe.value}).text(r).click(function(r){var i=e.tabManager.tabs[t.options.id];n.extend(!0,i.persistentOptions,t.options);i.refreshYasqe();e.store();d.closest(".tab-pane").removeClass("menu-open");r.preventDefault()}))})},y=function(){var r=t.persistentOptions.yasqe.sparql;o.hasClass("active")?r.requestMethod="POST":s.hasClass("active")&&(r.requestMethod="GET");r.acceptHeaderGraph=l[0].selectize.getValue();r.acceptHeaderSelect=a[0].selectize.getValue();var i=[];u.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&i.push({name:r[0],value:r[1]?r[1]:""})});r.args=i;var d=[];p.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&d.push(r[0])});r.defaultGraphs=d;var h=[];c.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&h.push(r[0])});r.namedGraphs=h;e.store();t.setPersistentInYasqe()};return{initWrapper:E,updateWrapper:x,store:y}}},{"./imgs.js":94,jquery:void 0,selectize:8,"yasgui-utils":14}],104:[function(e,t){var n=e("yasgui-utils"),r=e("./imgs.js"),i=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports=function(e){var t=!!e.options.tracker.googleAnalyticsId,o=!0,s="yasgui_"+i(e.wrapperElement).closest("[id]").attr("id")+"_trackerId",a=function(){var e=n.storage.get(s);if(null===e)u();else{e=+e;if(0===e){t=!1;o=!1}else if(1===e){t=!0;o=!1}else if(2==e){t=!0;o=!0}}},l=function(){if(e.options.tracker.googleAnalyticsId){a();(function(e,t,n,r,i,o,s){e.GoogleAnalyticsObject=i;e[i]=e[i]||function(){(e[i].q=e[i].q||[]).push(arguments)},e[i].l=1*new Date;o=t.createElement(n),s=t.getElementsByTagName(n)[0];o.async=1;o.src=r;s.parentNode.insertBefore(o,s)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");window._gaq=window._gaq||[];ga("create",e.options.tracker.googleAnalyticsId,"auto");ga("send","pageview")}},u=function(){var t=i("<div>",{"class":"consentWindow"}).appendTo(e.wrapperElement),o=function(){t.hide(400)},l=function(e){var t="no";2==e?t="yes":1==e&&(t="yes/no");p("consent",t);n.storage.set(s,e);a()};t.append(i("<div>",{"class":"consentMsg"}).html("We track user actions (including used endpoints and queries). This data is solely used for research purposes and to get insight into how users use the site. <i>We would appreciate your consent!</i>"));i("<div>",{"class":"buttons"}).appendTo(t).append(i("<button>",{type:"button","class":"btn btn-default"}).append(i(n.svg.getElement(r.checkMark)).height(11).width(11)).append(i("<span>").text(" Yes, allow")).click(function(){l(2);o()})).append(i("<button>",{type:"button","class":"btn btn-default"}).append(i(n.svg.getElement(r.checkCrossMark)).height(13).width(13)).append(i("<span>").html(" Yes, track site usage, but not<br>the queries/endpoints I use")).click(function(){l(1);o()})).append(i("<button>",{type:"button","class":"btn btn-default"}).append(i(n.svg.getElement(r.crossMark)).height(9).width(9)).append(i("<span>").text(" No, disable tracking")).click(function(){l(0);o()})).append(i("<button>",{type:"button","class":"btn btn-default"}).text("Ask me later").click(function(){o()}))},p=function(e,n,r,i,o){t&&_gaq.push(["_trackEvent",e,n,r,i,o])};l();return{enabled:t,track:p,drawConsentWindow:u}}},{"./imgs.js":94,jquery:void 0,"yasgui-utils":14}],105:[function(e,t){(function(){try{return e("jquery")}catch(t){return window.jQuery}})();t.exports={escapeHtmlEntities:function(e){var t={"&":"&","<":"<",">":">"},n=function(e){return t[e]||e};return e.replace(/[&<>]/g,n)}}},{jquery:void 0}],106:[function(e,t){var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=t.exports=e("yasgui-yasqe");r.defaults=n.extend(!0,r.defaults,{persistent:null,consumeShareLink:null,createShareLink:null,sparql:{showQueryButton:!0,acceptHeaderGraph:"text/turtle",acceptHeaderSelect:"application/sparql-results+json"}})},{jquery:void 0,"yasgui-yasqe":43}],107:[function(e,t){(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),e("./main.js"),t.exports=e("yasgui-yasr")},{"./main.js":99,jquery:void 0,"yasgui-yasr":82}]},{},[1])(1)});
//# sourceMappingURL=yasgui.min.js.map |
blueocean-material-icons/src/js/components/svg-icons/notification/event-available.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const NotificationEventAvailable = (props) => (
<SvgIcon {...props}>
<path d="M16.53 11.06L15.47 10l-4.88 4.88-2.12-2.12-1.06 1.06L10.59 17l5.94-5.94zM19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11z"/>
</SvgIcon>
);
NotificationEventAvailable.displayName = 'NotificationEventAvailable';
NotificationEventAvailable.muiName = 'SvgIcon';
export default NotificationEventAvailable;
|
src/components/LoaderButton.js | dddhany/notes-app-client | import React from 'react';
import {Button, Glyphicon} from 'react-bootstrap';
export default ({isLoading, text, loadingText, disabled=false, ...props})=>(
<Button disabled={disabled||isLoading} {...props}>
{isLoading && <Glyphicon glyph="refresh" className="spinning"/>}
{!isLoading ? text : loadingText}
</Button>
); |
src/svg-icons/action/assignment-return.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAssignmentReturn = (props) => (
<SvgIcon {...props}>
<path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm4 12h-4v3l-5-5 5-5v3h4v4z"/>
</SvgIcon>
);
ActionAssignmentReturn = pure(ActionAssignmentReturn);
ActionAssignmentReturn.displayName = 'ActionAssignmentReturn';
ActionAssignmentReturn.muiName = 'SvgIcon';
export default ActionAssignmentReturn;
|
ajax/libs/jquery.fancytree/2.10.0/jquery.fancytree-all.js | sajochiu/cdnjs | /*!
* jquery.fancytree.js
* Dynamic tree view control, with support for lazy loading of branches.
* https://github.com/mar10/fancytree/
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
/** Core Fancytree module.
*/
// Start of local namespace
;(function($, window, document, undefined) {
"use strict";
// prevent duplicate loading
if ( $.ui && $.ui.fancytree ) {
$.ui.fancytree.warn("Fancytree: ignored duplicate include");
return;
}
/* *****************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
// TODO: see qunit.js extractStacktrace()
if(!cond){
msg = msg ? ": " + msg : "";
// consoleApply("assert", [!!cond, msg]);
$.error("Fancytree assertion failed" + msg);
}
}
_assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)");
function consoleApply(method, args){
var i, s,
fn = window.console ? window.console[method] : null;
if(fn){
try{
fn.apply(window.console, args);
} catch(e) {
// IE 8?
s = "";
for( i=0; i<args.length; i++){
s += args[i];
}
fn(s);
}
}
}
/*Return true if x is a FancytreeNode.*/
function _isNode(x){
return !!(x.tree && x.statusNodeType !== undefined);
}
/** Return true if dotted version string is equal or higher than requested version.
*
* See http://jsfiddle.net/mar10/FjSAN/
*/
function isVersionAtLeast(dottedVersion, major, minor, patch){
var i, v, t,
verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }),
testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); });
for( i = 0; i < testParts.length; i++ ){
v = verParts[i] || 0;
t = testParts[i] || 0;
if( v !== t ){
return ( v > t );
}
}
return true;
}
/** Return a wrapper that calls sub.methodName() and exposes
* this : tree
* this._local : tree.ext.EXTNAME
* this._super : base.methodName()
*/
function _makeVirtualFunction(methodName, tree, base, extension, extName){
// $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName);
// if(rexTestSuper && !rexTestSuper.test(func)){
// // extension.methodName() doesn't call _super(), so no wrapper required
// return func;
// }
// Use an immediate function as closure
var proxy = (function(){
var prevFunc = tree[methodName], // org. tree method or prev. proxy
baseFunc = extension[methodName], //
_local = tree.ext[extName],
_super = function(){
return prevFunc.apply(tree, arguments);
},
_superApply = function(args){
return prevFunc.apply(tree, args);
};
// Return the wrapper function
return function(){
var prevLocal = tree._local,
prevSuper = tree._super,
prevSuperApply = tree._superApply;
try{
tree._local = _local;
tree._super = _super;
tree._superApply = _superApply;
return baseFunc.apply(tree, arguments);
}finally{
tree._local = prevLocal;
tree._super = prevSuper;
tree._superApply = prevSuperApply;
}
};
})(); // end of Immediate Function
return proxy;
}
/**
* Subclass `base` by creating proxy functions
*/
function _subclassObject(tree, base, extension, extName){
// $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
for(var attrName in extension){
if(typeof extension[attrName] === "function"){
if(typeof tree[attrName] === "function"){
// override existing method
tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
}else if(attrName.charAt(0) === "_"){
// Create private methods in tree.ext.EXTENSION namespace
tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
}else{
$.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName);
}
}else{
// Create member variables in tree.ext.EXTENSION namespace
if(attrName !== "options"){
tree.ext[extName][attrName] = extension[attrName];
}
}
}
}
function _getResolvedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.resolve();}).promise();
}else{
return $.Deferred(function(){this.resolveWith(context, argArray);}).promise();
}
}
function _getRejectedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.reject();}).promise();
}else{
return $.Deferred(function(){this.rejectWith(context, argArray);}).promise();
}
}
function _makeResolveFunc(deferred, context){
return function(){
deferred.resolveWith(context);
};
}
function _getElementDataAsDict($el){
// Evaluate 'data-NAME' attributes with special treatment for 'data-json'.
var d = $.extend({}, $el.data()),
json = d.json;
delete d.fancytree; // added to container by widget factory
if( json ) {
delete d.json;
// <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5)
d = $.extend(d, json);
}
return d;
}
// TODO: use currying
function _makeNodeTitleMatcher(s){
s = s.toLowerCase();
return function(node){
return node.title.toLowerCase().indexOf(s) >= 0;
};
}
function _makeNodeTitleStartMatcher(s){
var reMatch = new RegExp("^" + s, "i");
return function(node){
return reMatch.test(node.title);
};
}
var i,
FT = null, // initialized below
ENTITY_MAP = {"&": "&", "<": "<", ">": ">", "\"": """, "'": "'", "/": "/"},
IGNORE_KEYCODES = { 16: true, 17: true, 18: true },
SPECIAL_KEYCODES = {
8: "backspace", 9: "tab", 10: "return", 13: "return",
// 16: null, 17: null, 18: null, // ignore shift, ctrl, alt
19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup",
34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up",
39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=",
96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6",
103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".",
111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5",
117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11",
123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=",
188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
221: "]", 222: "'"},
MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" },
//boolean attributes that can be set with equivalent class names in the LI tags
CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),
CLASS_ATTR_MAP = {},
// Top-level Fancytree node attributes, that can be set by dict
NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "),
NODE_ATTR_MAP = {},
// Attribute names that should NOT be added to node.data
NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true};
for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; }
for(i=0; i<NODE_ATTRS.length; i++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; }
/* *****************************************************************************
* FancytreeNode
*/
/**
* Creates a new FancytreeNode
*
* @class FancytreeNode
* @classdesc A FancytreeNode represents the hierarchical data model and operations.
*
* @param {FancytreeNode} parent
* @param {NodeData} obj
*
* @property {Fancytree} tree The tree instance
* @property {FancytreeNode} parent The parent node
* @property {string} key Node id (must be unique inside the tree)
* @property {string} title Display name (may contain HTML)
* @property {object} data Contains all extra data that was passed on node creation
* @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br>
* For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array
* to define a node that has no children.
* @property {boolean} expanded Use isExpanded(), setExpanded() to access this property.
* @property {string} extraClasses Addtional CSS classes, added to the node's `<span>`
* @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
* Note: Also non-folders may have children.
* @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'.
* @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion.
* @property {boolean} selected Use isSelected(), setSelected() to access this property.
* @property {string} tooltip Alternative description used as hover banner
*/
function FancytreeNode(parent, obj){
var i, l, name, cl;
this.parent = parent;
this.tree = parent.tree;
this.ul = null;
this.li = null; // <li id='key' ftnode=this> tag
this.statusNodeType = null; // if this is a temp. node to display the status of its parent
this._isLoading = false; // if this node itself is loading
this._error = null; // {message: '...'} if a load error occured
this.data = {};
// TODO: merge this code with node.toDict()
// copy attributes from obj object
for(i=0, l=NODE_ATTRS.length; i<l; i++){
name = NODE_ATTRS[i];
this[name] = obj[name];
}
// node.data += obj.data
if(obj.data){
$.extend(this.data, obj.data);
}
// copy all other attributes to this.data.NAME
for(name in obj){
if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){
// node.data.NAME = obj.NAME
this.data[name] = obj[name];
}
}
// Fix missing key
if( this.key == null ){ // test for null OR undefined
if( this.tree.options.defaultKey ) {
this.key = this.tree.options.defaultKey(this);
_assert(this.key, "defaultKey() must return a unique key");
} else {
this.key = "_" + (FT._nextNodeKey++);
}
} else {
this.key = "" + this.key; // Convert to string (#217)
}
// Fix tree.activeNode
// TODO: not elegant: we use obj.active as marker to set tree.activeNode
// when loading from a dictionary.
if(obj.active){
_assert(this.tree.activeNode === null, "only one active node allowed");
this.tree.activeNode = this;
}
if( obj.selected ){ // #186
this.tree.lastSelectedNode = this;
}
// TODO: handle obj.focus = true
// Create child nodes
this.children = null;
cl = obj.children;
if(cl && cl.length){
this._setChildren(cl);
}
// Add to key/ref map (except for root node)
// if( parent ) {
this.tree._callHook("treeRegisterNode", this.tree, true, this);
// }
}
FancytreeNode.prototype = /** @lends FancytreeNode# */{
/* Return the direct child FancytreeNode with a given key, index. */
_findDirectChild: function(ptr){
var i, l,
cl = this.children;
if(cl){
if(typeof ptr === "string"){
for(i=0, l=cl.length; i<l; i++){
if(cl[i].key === ptr){
return cl[i];
}
}
}else if(typeof ptr === "number"){
return this.children[ptr];
}else if(ptr.parent === this){
return ptr;
}
}
return null;
},
// TODO: activate()
// TODO: activateSilently()
/* Internal helper called in recursive addChildren sequence.*/
_setChildren: function(children){
_assert(children && (!this.children || this.children.length === 0), "only init supported");
this.children = [];
for(var i=0, l=children.length; i<l; i++){
this.children.push(new FancytreeNode(this, children[i]));
}
},
/**
* Append (or insert) a list of child nodes.
*
* @param {NodeData[]} children array of child node definitions (also single child accepted)
* @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such).
* If omitted, the new children are appended.
* @returns {FancytreeNode} first child added
*
* @see FancytreeNode#applyPatch
*/
addChildren: function(children, insertBefore){
var i, l, pos,
firstNode = null,
nodeList = [];
if($.isPlainObject(children) ){
children = [children];
}
if(!this.children){
this.children = [];
}
for(i=0, l=children.length; i<l; i++){
nodeList.push(new FancytreeNode(this, children[i]));
}
firstNode = nodeList[0];
if(insertBefore == null){
this.children = this.children.concat(nodeList);
}else{
insertBefore = this._findDirectChild(insertBefore);
pos = $.inArray(insertBefore, this.children);
_assert(pos >= 0, "insertBefore must be an existing child");
// insert nodeList after children[pos]
this.children.splice.apply(this.children, [pos, 0].concat(nodeList));
}
if( !this.parent || this.parent.ul || this.tr ){
// render if the parent was rendered (or this is a root node)
this.render();
}
if( this.tree.options.selectMode === 3 ){
this.fixSelection3FromEndNodes();
}
return firstNode;
},
/**
* Append or prepend a node, or append a child node.
*
* This a convenience function that calls addChildren()
*
* @param {NodeData} node node definition
* @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child')
* @returns {FancytreeNode} new node
*/
addNode: function(node, mode){
if(mode === undefined || mode === "over"){
mode = "child";
}
switch(mode){
case "after":
return this.getParent().addChildren(node, this.getNextSibling());
case "before":
return this.getParent().addChildren(node, this);
case "firstChild":
// Insert before the first child if any
var insertBefore = (this.children ? this.children[0] : null);
return this.addChildren(node, insertBefore);
case "child":
case "over":
return this.addChildren(node);
}
_assert(false, "Invalid mode: " + mode);
},
/**
* Append new node after this.
*
* This a convenience function that calls addNode(node, 'after')
*
* @param {NodeData} node node definition
* @returns {FancytreeNode} new node
*/
appendSibling: function(node){
return this.addNode(node, "after");
},
/**
* Modify existing child nodes.
*
* @param {NodePatch} patch
* @returns {$.Promise}
* @see FancytreeNode#addChildren
*/
applyPatch: function(patch) {
// patch [key, null] means 'remove'
if(patch === null){
this.remove();
return _getResolvedPromise(this);
}
// TODO: make sure that root node is not collapsed or modified
// copy (most) attributes to node.ATTR or node.data.ATTR
var name, promise, v,
IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global
for(name in patch){
v = patch[name];
if( !IGNORE_MAP[name] && !$.isFunction(v)){
if(NODE_ATTR_MAP[name]){
this[name] = v;
}else{
this.data[name] = v;
}
}
}
// Remove and/or create children
if(patch.hasOwnProperty("children")){
this.removeChildren();
if(patch.children){ // only if not null and not empty list
// TODO: addChildren instead?
this._setChildren(patch.children);
}
// TODO: how can we APPEND or INSERT child nodes?
}
if(this.isVisible()){
this.renderTitle();
this.renderStatus();
}
// Expand collapse (final step, since this may be async)
if(patch.hasOwnProperty("expanded")){
promise = this.setExpanded(patch.expanded);
}else{
promise = _getResolvedPromise(this);
}
return promise;
},
/** Collapse all sibling nodes.
* @returns {$.Promise}
*/
collapseSiblings: function() {
return this.tree._callHook("nodeCollapseSiblings", this);
},
/** Copy this node as sibling or child of `node`.
*
* @param {FancytreeNode} node source node
* @param {string} [mode=child] 'before' | 'after' | 'child'
* @param {Function} [map] callback function(NodeData) that could modify the new node
* @returns {FancytreeNode} new
*/
copyTo: function(node, mode, map) {
return node.addNode(this.toDict(true, map), mode);
},
/** Count direct and indirect children.
*
* @param {boolean} [deep=true] pass 'false' to only count direct children
* @returns {int} number of child nodes
*/
countChildren: function(deep) {
var cl = this.children, i, l, n;
if( !cl ){
return 0;
}
n = cl.length;
if(deep !== false){
for(i=0, l=n; i<l; i++){
n += cl[i].countChildren();
}
}
return n;
},
// TODO: deactivate()
/** Write to browser console if debugLevel >= 2 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.tree.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
/** Deprecated.
* @deprecated since 2014-02-16. Use resetLazy() instead.
*/
discard: function(){
this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead.");
return this.resetLazy();
},
// TODO: expand(flag)
/**Find all nodes that contain `match` in the title.
*
* @param {string | function(node)} match string to search for, of a function that
* returns `true` if a node is matched.
* @returns {FancytreeNode[]} array of nodes (may be empty)
* @see FancytreeNode#findAll
*/
findAll: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = [];
this.visit(function(n){
if(match(n)){
res.push(n);
}
});
return res;
},
/**Find first node that contains `match` in the title (not including self).
*
* @param {string | function(node)} match string to search for, of a function that
* returns `true` if a node is matched.
* @returns {FancytreeNode} matching node or null
* @example
* <b>fat</b> text
*/
findFirst: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = null;
this.visit(function(n){
if(match(n)){
res = n;
return false;
}
});
return res;
},
/* Apply selection state (internal use only) */
_changeSelectStatusAttrs: function (state) {
var changed = false;
switch(state){
case false:
changed = ( this.selected || this.partsel );
this.selected = false;
this.partsel = false;
break;
case true:
changed = ( !this.selected || !this.partsel );
this.selected = true;
this.partsel = true;
break;
case undefined:
changed = ( this.selected || !this.partsel );
this.selected = false;
this.partsel = true;
break;
default:
_assert(false, "invalid state: " + state);
}
// this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed);
if( changed ){
this.renderStatus();
}
return changed;
},
/**
* Fix selection status, after this node was (de)selected in multi-hier mode.
* This includes (de)selecting all children.
*/
fixSelection3AfterClick: function() {
var flag = this.isSelected();
// this.debug("fixSelection3AfterClick()");
this.visit(function(node){
node._changeSelectStatusAttrs(flag);
});
this.fixSelection3FromEndNodes();
},
/**
* Fix selection status for multi-hier mode.
* Only end-nodes are considered to update the descendants branch and parents.
* Should be called after this node has loaded new children or after
* children have been modified using the API.
*/
fixSelection3FromEndNodes: function() {
// this.debug("fixSelection3FromEndNodes()");
_assert(this.tree.options.selectMode === 3, "expected selectMode 3");
// Visit all end nodes and adjust their parent's `selected` and `partsel`
// attributes. Return selection state true, false, or undefined.
function _walk(node){
var i, l, child, s, state, allSelected,someSelected,
children = node.children;
if( children && children.length ){
// check all children recursively
allSelected = true;
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// the selection state of a node is not relevant; we need the end-nodes
s = _walk(child);
if( s !== false ) {
someSelected = true;
}
if( s !== true ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
}else{
// This is an end-node: simply report the status
// state = ( node.unselectable ) ? undefined : !!node.selected;
state = !!node.selected;
}
node._changeSelectStatusAttrs(state);
return state;
}
_walk(this);
// Update parent's state
this.visitParents(function(node){
var i, l, child, state,
children = node.children,
allSelected = true,
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// When fixing the parents, we trust the sibling status (i.e.
// we don't recurse)
if( child.selected || child.partsel ) {
someSelected = true;
}
if( !child.unselectable && !child.selected ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
node._changeSelectStatusAttrs(state);
});
},
// TODO: focus()
/**
* Update node data. If dict contains 'children', then also replace
* the hole sub tree.
* @param {NodeData} dict
*
* @see FancytreeNode#addChildren
* @see FancytreeNode#applyPatch
*/
fromDict: function(dict) {
// copy all other attributes to this.data.xxx
for(var name in dict){
if(NODE_ATTR_MAP[name]){
// node.NAME = dict.NAME
this[name] = dict[name];
}else if(name === "data"){
// node.data += dict.data
$.extend(this.data, dict.data);
}else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){
// node.data.NAME = dict.NAME
this.data[name] = dict[name];
}
}
if(dict.children){
// recursively set children and render
this.removeChildren();
this.addChildren(dict.children);
}
this.renderTitle();
/*
var children = dict.children;
if(children === undefined){
this.data = $.extend(this.data, dict);
this.render();
return;
}
dict = $.extend({}, dict);
dict.children = undefined;
this.data = $.extend(this.data, dict);
this.removeChildren();
this.addChild(children);
*/
},
/** Return the list of child nodes (undefined for unexpanded lazy nodes).
* @returns {FancytreeNode[] | undefined}
*/
getChildren: function() {
if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes?
return undefined; // Lazy node: unloaded, currently loading, or load error
}
return this.children;
},
/** Return the first child node or null.
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.children ? this.children[0] : null;
},
/** Return the 0-based child index.
* @returns {int}
*/
getIndex: function() {
// return this.parent.children.indexOf(this);
return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7
},
/** Return the hierarchical child index (1-based, e.g. '3.2.4').
* @returns {string}
*/
getIndexHier: function(separator) {
separator = separator || ".";
var res = [];
$.each(this.getParentList(false, true), function(i, o){
res.push(o.getIndex() + 1);
});
return res.join(separator);
},
/** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32".
* @param {boolean} [excludeSelf=false]
* @returns {string}
*/
getKeyPath: function(excludeSelf) {
var path = [],
sep = this.tree.options.keyPathSeparator;
this.visitParents(function(n){
if(n.parent){
path.unshift(n.key);
}
}, !excludeSelf);
return sep + path.join(sep);
},
/** Return the last child of this node or null.
* @returns {FancytreeNode | null}
*/
getLastChild: function() {
return this.children ? this.children[this.children.length - 1] : null;
},
/** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... .
* @returns {int}
*/
getLevel: function() {
var level = 0,
dtn = this.parent;
while( dtn ) {
level++;
dtn = dtn.parent;
}
return level;
},
/** Return the successor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getNextSibling: function() {
// TODO: use indexOf, if available: (not in IE6)
if( this.parent ){
var i, l,
ac = this.parent.children;
for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null
if( ac[i] === this ){
return ac[i+1];
}
}
}
return null;
},
/** Return the parent node (null for the system root node).
* @returns {FancytreeNode | null}
*/
getParent: function() {
// TODO: return null for top-level nodes?
return this.parent;
},
/** Return an array of all parent nodes (top-down).
* @param {boolean} [includeRoot=false] Include the invisible system root node.
* @param {boolean} [includeSelf=false] Include the node itself.
* @returns {FancytreeNode[]}
*/
getParentList: function(includeRoot, includeSelf) {
var l = [],
dtn = includeSelf ? this : this.parent;
while( dtn ) {
if( includeRoot || dtn.parent ){
l.unshift(dtn);
}
dtn = dtn.parent;
}
return l;
},
/** Return the predecessor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getPrevSibling: function() {
if( this.parent ){
var i, l,
ac = this.parent.children;
for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null
if( ac[i] === this ){
return ac[i-1];
}
}
}
return null;
},
/** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded).
* @returns {boolean | undefined}
*/
hasChildren: function() {
if(this.lazy){
if(this.children == null ){
// null or undefined: Not yet loaded
return undefined;
}else if(this.children.length === 0){
// Loaded, but response was empty
return false;
}else if(this.children.length === 1 && this.children[0].isStatusNode() ){
// Currently loading or load error
return undefined;
}
return true;
}
return !!( this.children && this.children.length );
},
/** Return true if node has keyboard focus.
* @returns {boolean}
*/
hasFocus: function() {
return (this.tree.hasFocus() && this.tree.focusNode === this);
},
/** Write to browser console if debugLevel >= 1 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.tree.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/** Return true if node is active (see also FancytreeNode#isSelected).
* @returns {boolean}
*/
isActive: function() {
return (this.tree.activeNode === this);
},
/** Return true if node is a direct child of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isChildOf: function(otherNode) {
return (this.parent && this.parent === otherNode);
},
/** Return true, if node is a direct or indirect sub node of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isDescendantOf: function(otherNode) {
if(!otherNode || otherNode.tree !== this.tree){
return false;
}
var p = this.parent;
while( p ) {
if( p === otherNode ){
return true;
}
p = p.parent;
}
return false;
},
/** Return true if node is expanded.
* @returns {boolean}
*/
isExpanded: function() {
return !!this.expanded;
},
/** Return true if node is the first node of its parent's children.
* @returns {boolean}
*/
isFirstSibling: function() {
var p = this.parent;
return !p || p.children[0] === this;
},
/** Return true if node is a folder, i.e. has the node.folder attribute set.
* @returns {boolean}
*/
isFolder: function() {
return !!this.folder;
},
/** Return true if node is the last node of its parent's children.
* @returns {boolean}
*/
isLastSibling: function() {
var p = this.parent;
return !p || p.children[p.children.length-1] === this;
},
/** Return true if node is lazy (even if data was already loaded)
* @returns {boolean}
*/
isLazy: function() {
return !!this.lazy;
},
/** Return true if node is lazy and loaded. For non-lazy nodes always return true.
* @returns {boolean}
*/
isLoaded: function() {
return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
},
/** Return true if children are currently beeing loaded, i.e. a Ajax request is pending.
* @returns {boolean}
*/
isLoading: function() {
return !!this._isLoading;
},
/*
* @deprecated since v2.4.0: Use isRootNode() instead
*/
isRoot: function() {
return this.isRootNode();
},
/** Return true if this is the (invisible) system root node.
* @returns {boolean}
*/
isRootNode: function() {
return (this.tree.rootNode === this);
},
/** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive).
* @returns {boolean}
*/
isSelected: function() {
return !!this.selected;
},
/** Return true if this node is a temporarily generated system node like
* 'loading', or 'error' (node.statusNodeType contains the type).
* @returns {boolean}
*/
isStatusNode: function() {
return !!this.statusNodeType;
},
/** Return true if this a top level node, i.e. a direct child of the (invisible) system root node.
* @returns {boolean}
*/
isTopLevel: function() {
return (this.tree.rootNode === this.parent);
},
/** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false.
* @returns {boolean}
*/
isUndefined: function() {
return this.hasChildren() === undefined; // also checks if the only child is a status node
},
/** Return true if all parent nodes are expanded. Note: this does not check
* whether the node is scrolled into the visible part of the screen.
* @returns {boolean}
*/
isVisible: function() {
var i, l,
parents = this.getParentList(false, false);
for(i=0, l=parents.length; i<l; i++){
if( ! parents[i].expanded ){ return false; }
}
return true;
},
/** Deprecated.
* @deprecated since 2014-02-16: use load() instead.
*/
lazyLoad: function(discard) {
this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead.");
return this.load(discard);
},
/**
* Load all children of a lazy node if neccessary. The *expanded* state is maintained.
* @param {boolean} [forceReload=false] Pass true to discard any existing nodes before.
* @returns {$.Promise}
*/
load: function(forceReload) {
var res, source,
that = this;
_assert( this.isLazy(), "load() requires a lazy node" );
// _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" );
if( !forceReload && !this.isUndefined() ) {
return _getResolvedPromise(this);
}
if( this.isLoaded() ){
this.resetLazy(); // also collapses
}
// This method is also called by setExpanded() and loadKeyPath(), so we
// have to avoid recursion.
source = this.tree._triggerNodeEvent("lazyLoad", this);
if( source === false ) { // #69
return _getResolvedPromise(this);
}
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
res = this.tree._callHook("nodeLoadChildren", this, source);
if( this.expanded ) {
res.always(function(){
that.render();
});
}
return res;
},
/** Expand all parents and optionally scroll into visible area as neccessary.
* Promise is resolved, when lazy loading and animations are done.
* @param {object} [opts] passed to `setExpanded()`.
* Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
* @returns {$.Promise}
*/
makeVisible: function(opts) {
var i,
that = this,
deferreds = [],
dfd = new $.Deferred(),
parents = this.getParentList(false, false),
len = parents.length,
effects = !(opts && opts.noAnimation === true),
scroll = !(opts && opts.scrollIntoView === false);
// Expand bottom-up, so only the top node is animated
for(i = len - 1; i >= 0; i--){
// that.debug("pushexpand" + parents[i]);
deferreds.push(parents[i].setExpanded(true, opts));
}
$.when.apply($, deferreds).done(function(){
// All expands have finished
// that.debug("expand DONE", scroll);
if( scroll ){
that.scrollIntoView(effects).done(function(){
// that.debug("scroll DONE");
dfd.resolve();
});
} else {
dfd.resolve();
}
});
return dfd.promise();
},
/** Move this node to targetNode.
* @param {FancytreeNode} targetNode
* @param {string} mode <pre>
* 'child': append this node as last child of targetNode.
* This is the default. To be compatble with the D'n'd
* hitMode, we also accept 'over'.
* 'before': add this node as sibling before targetNode.
* 'after': add this node as sibling after targetNode.</pre>
* @param {function} [map] optional callback(FancytreeNode) to allow modifcations
*/
moveTo: function(targetNode, mode, map) {
if(mode === undefined || mode === "over"){
mode = "child";
}
var pos,
prevParent = this.parent,
targetParent = (mode === "child") ? targetNode : targetNode.parent;
if(this === targetNode){
return;
}else if( !this.parent ){
throw "Cannot move system root";
}else if( targetParent.isDescendantOf(this) ){
throw "Cannot move a node to its own descendant";
}
// Unlink this node from current parent
if( this.parent.children.length === 1 ) {
if( this.parent === targetParent ){
return; // #258
}
this.parent.children = this.parent.lazy ? [] : null;
this.parent.expanded = false;
} else {
pos = $.inArray(this, this.parent.children);
_assert(pos >= 0, "invalid source parent");
this.parent.children.splice(pos, 1);
}
// Remove from source DOM parent
// if(this.parent.ul){
// this.parent.ul.removeChild(this.li);
// }
// Insert this node to target parent's child list
this.parent = targetParent;
if( targetParent.hasChildren() ) {
switch(mode) {
case "child":
// Append to existing target children
targetParent.children.push(this);
break;
case "before":
// Insert this node before target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0, "invalid target parent");
targetParent.children.splice(pos, 0, this);
break;
case "after":
// Insert this node after target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0, "invalid target parent");
targetParent.children.splice(pos+1, 0, this);
break;
default:
throw "Invalid mode " + mode;
}
} else {
targetParent.children = [ this ];
}
// Parent has no <ul> tag yet:
// if( !targetParent.ul ) {
// // This is the parent's first child: create UL tag
// // (Hidden, because it will be
// targetParent.ul = document.createElement("ul");
// targetParent.ul.style.display = "none";
// targetParent.li.appendChild(targetParent.ul);
// }
// // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
// if(this.li){
// targetParent.ul.appendChild(this.li);
// }^
// Let caller modify the nodes
if( map ){
targetNode.visit(map, true);
}
// Handle cross-tree moves
if( this.tree !== targetNode.tree ) {
// Fix node.tree for all source nodes
// _assert(false, "Cross-tree move is not yet implemented.");
this.warn("Cross-tree moveTo is experimantal!");
this.visit(function(n){
// TODO: fix selection state and activation, ...
n.tree = targetNode.tree;
}, true);
}
// A collaposed node won't re-render children, so we have to remove it manually
// if( !targetParent.expanded ){
// prevParent.ul.removeChild(this.li);
// }
// Update HTML markup
if( !prevParent.isDescendantOf(targetParent)) {
prevParent.render();
}
if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) {
targetParent.render();
}
// TODO: fix selection state
// TODO: fix active state
/*
var tree = this.tree;
var opts = tree.options;
var pers = tree.persistence;
// Always expand, if it's below minExpandLevel
// tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel());
if ( opts.minExpandLevel >= ftnode.getLevel() ) {
// tree.logDebug ("Force expand for %o", ftnode);
this.bExpanded = true;
}
// In multi-hier mode, update the parents selection state
// DT issue #82: only if not initializing, because the children may not exist yet
// if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing )
// ftnode._fixSelectionState();
// In multi-hier mode, update the parents selection state
if( ftnode.bSelected && opts.selectMode==3 ) {
var p = this;
while( p ) {
if( !p.hasSubSel )
p._setSubSel(true);
p = p.parent;
}
}
// render this node and the new child
if ( tree.bEnableUpdate )
this.render();
return ftnode;
*/
},
/** Set focus relative to this node and optionally activate.
*
* @param {number} where The keyCode that would normally trigger this move,
* e.g. `$.ui.keyCode.LEFT` would collapse the node if it
* is expanded or move to the parent oterwise.
* @param {boolean} [activate=true]
* @returns {$.Promise}
*/
// navigate: function(where, activate) {
// console.time("navigate")
// this._navigate(where, activate)
// console.timeEnd("navigate")
// },
navigate: function(where, activate) {
var i, parents,
handled = true,
KC = $.ui.keyCode,
sib = null;
// Navigate to node
function _goto(n){
if( n ){
try { n.makeVisible(); } catch(e) {} // #272
// Node may still be hidden by a filter
if( ! $(n.span).is(":visible") ) {
n.debug("Navigate: skipping hidden node");
n.navigate(where, activate);
return;
}
return activate === false ? n.setFocus() : n.setActive();
}
}
switch( where ) {
case KC.BACKSPACE:
if( this.parent && this.parent.parent ) {
_goto(this.parent);
}
break;
case KC.LEFT:
if( this.expanded ) {
this.setExpanded(false);
_goto(this);
} else if( this.parent && this.parent.parent ) {
_goto(this.parent);
}
break;
case KC.RIGHT:
if( !this.expanded && (this.children || this.lazy) ) {
this.setExpanded();
_goto(this);
} else if( this.children && this.children.length ) {
_goto(this.children[0]);
}
break;
case KC.UP:
sib = this.getPrevSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getPrevSibling();
}
while( sib && sib.expanded && sib.children && sib.children.length ) {
sib = sib.children[sib.children.length - 1];
}
if( !sib && this.parent && this.parent.parent ){
sib = this.parent;
}
_goto(sib);
break;
case KC.DOWN:
if( this.expanded && this.children && this.children.length ) {
sib = this.children[0];
} else {
parents = this.getParentList(false, true);
for(i=parents.length-1; i>=0; i--) {
sib = parents[i].getNextSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getNextSibling();
}
if( sib ){ break; }
}
}
_goto(sib);
break;
default:
handled = false;
}
},
/**
* Remove this node (not allowed for system root).
*/
remove: function() {
return this.parent.removeChild(this);
},
/**
* Remove childNode from list of direct children.
* @param {FancytreeNode} childNode
*/
removeChild: function(childNode) {
return this.tree._callHook("nodeRemoveChild", this, childNode);
},
/**
* Remove all child nodes and descendents. This converts the node into a leaf.<br>
* If this was a lazy node, it is still considered 'loaded'; call node.resetLazy()
* in order to trigger lazyLoad on next expand.
*/
removeChildren: function() {
return this.tree._callHook("nodeRemoveChildren", this);
},
/**
* This method renders and updates all HTML markup that is required
* to display this node in its current state.<br>
* Note:
* <ul>
* <li>It should only be neccessary to call this method after the node object
* was modified by direct access to its properties, because the common
* API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...)
* already handle this.
* <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus}
* are implied. If changes are more local, calling only renderTitle() or
* renderStatus() may be sufficient and faster.
* <li>If a node was created/removed, node.render() must be called <i>on the parent</i>.
* </ul>
*
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
*/
render: function(force, deep) {
return this.tree._callHook("nodeRender", this, force, deep);
},
/** Create HTML markup for the node's outer <span> (expander, checkbox, icon, and title).
* @see Fancytree_Hooks#nodeRenderTitle
*/
renderTitle: function() {
return this.tree._callHook("nodeRenderTitle", this);
},
/** Update element's CSS classes according to node state.
* @see Fancytree_Hooks#nodeRenderStatus
*/
renderStatus: function() {
return this.tree._callHook("nodeRenderStatus", this);
},
/**
* Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
* event is triggered on next expand.
*/
resetLazy: function() {
this.removeChildren();
this.expanded = false;
this.lazy = true;
this.children = undefined;
this.renderStatus();
},
/** Schedule activity for delayed execution (cancel any pending request).
* scheduleAction('cancel') will only cancel a pending request (if any).
* @param {string} mode
* @param {number} ms
*/
scheduleAction: function(mode, ms) {
if( this.tree.timer ) {
clearTimeout(this.tree.timer);
// this.tree.debug("clearTimeout(%o)", this.tree.timer);
}
this.tree.timer = null;
var self = this; // required for closures
switch (mode) {
case "cancel":
// Simply made sure that timer was cleared
break;
case "expand":
this.tree.timer = setTimeout(function(){
self.tree.debug("setTimeout: trigger expand");
self.setExpanded(true);
}, ms);
break;
case "activate":
this.tree.timer = setTimeout(function(){
self.tree.debug("setTimeout: trigger activate");
self.setActive(true);
}, ms);
break;
default:
throw "Invalid mode " + mode;
}
// this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
},
/**
*
* @param {boolean | PlainObject} [effects=false] animation options.
* @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in
* any case, even if `this` is outside the scroll pane.
* @returns {$.Promise}
*/
scrollIntoView: function(effects, options) {
if( options !== undefined && _isNode(options) ) {
this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead.");
options = {topNode: options};
}
// this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent);
// this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container;
var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop,
opts = $.extend({
effects: (effects === true) ? {duration: 200, queue: false} : effects,
scrollOfs: this.tree.options.scrollOfs,
scrollParent: this.tree.options.scrollParent || this.tree.$container,
topNode: null
}, options),
dfd = new $.Deferred(),
that = this,
nodeHeight = $(this.span).height(),
$container = $(opts.scrollParent),
topOfs = opts.scrollOfs.top || 0,
bottomOfs = opts.scrollOfs.bottom || 0,
containerHeight = $container.height(),// - topOfs - bottomOfs,
scrollTop = $container.scrollTop(),
$animateTarget = $container,
isParentWindow = $container[0] === window,
topNode = opts.topNode || null,
newScrollTop = null;
// this.debug("scrollIntoView(), scrollTop=", scrollTop, opts.scrollOfs);
// _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets
if( !$(this.span).is(":visible") ) {
// We cannot calc offsets for hidden elements
this.warn("scrollIntoView(): node is invisible.");
return _getResolvedPromise();
}
if( isParentWindow ) {
nodeY = $(this.span).offset().top;
topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0;
$animateTarget = $("html,body");
} else {
_assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be an simple element or `window`, not document or body.");
containerOffsetTop = $container.offset().top,
nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent
topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0;
horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight));
containerHeight -= horzScrollbarHeight;
}
// this.debug(" scrollIntoView(), nodeY=", nodeY, "containerHeight=", containerHeight);
if( nodeY < (scrollTop + topOfs) ){
// Node is above visible container area
newScrollTop = nodeY - topOfs;
// this.debug(" scrollIntoView(), UPPER newScrollTop=", newScrollTop);
}else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){
newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs;
// this.debug(" scrollIntoView(), LOWER newScrollTop=", newScrollTop);
// If a topNode was passed, make sure that it is never scrolled
// outside the upper border
if(topNode){
_assert(topNode.isRoot() || $(topNode.span).is(":visible"), "topNode must be visible");
if( topNodeY < newScrollTop ){
newScrollTop = topNodeY - topOfs;
// this.debug(" scrollIntoView(), TOP newScrollTop=", newScrollTop);
}
}
}
if(newScrollTop !== null){
// this.debug(" scrollIntoView(), SET newScrollTop=", newScrollTop);
if(opts.effects){
opts.effects.complete = function(){
dfd.resolveWith(that);
};
$animateTarget.stop(true).animate({
scrollTop: newScrollTop
}, opts.effects);
}else{
$animateTarget[0].scrollTop = newScrollTop;
dfd.resolveWith(this);
}
}else{
dfd.resolveWith(this);
}
return dfd.promise();
},
/**Activate this node.
* @param {boolean} [flag=true] pass false to deactivate
* @param {object} [opts] additional options. Defaults to {noEvents: false}
* @returns {$.Promise}
*/
setActive: function(flag, opts){
return this.tree._callHook("nodeSetActive", this, flag, opts);
},
/**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done.
* @param {boolean} [flag=true] pass false to collapse
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise}
*/
setExpanded: function(flag, opts){
return this.tree._callHook("nodeSetExpanded", this, flag, opts);
},
/**Set keyboard focus to this node.
* @param {boolean} [flag=true] pass false to blur
* @see Fancytree#setFocus
*/
setFocus: function(flag){
return this.tree._callHook("nodeSetFocus", this, flag);
},
/**Select this node, i.e. check the checkbox.
* @param {boolean} [flag=true] pass false to deselect
*/
setSelected: function(flag){
return this.tree._callHook("nodeSetSelected", this, flag);
},
/**Mark a lazy node as 'error', 'loading', or 'ok'.
* @param {string} status 'error', 'ok'
* @param {string} [message]
* @param {string} [details]
*/
setStatus: function(status, message, details){
return this.tree._callHook("nodeSetStatus", this, status, message, details);
},
/**Rename this node.
* @param {string} title
*/
setTitle: function(title){
this.title = title;
this.renderTitle();
},
/**Sort child list by title.
* @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title).
* @param {boolean} [deep=false] pass true to sort all descendant nodes
*/
sortChildren: function(cmp, deep) {
var i,l,
cl = this.children;
if( !cl ){
return;
}
cmp = cmp || function(a, b) {
var x = a.title.toLowerCase(),
y = b.title.toLowerCase();
return x === y ? 0 : x > y ? 1 : -1;
};
cl.sort(cmp);
if( deep ){
for(i=0, l=cl.length; i<l; i++){
if( cl[i].children ){
cl[i].sortChildren(cmp, "$norender$");
}
}
}
if( deep !== "$norender$" ){
this.render();
}
},
/** Convert node (or whole branch) into a plain object.
*
* The result is compatible with node.addChildren().
*
* @param {boolean} [recursive=false] include child nodes
* @param {function} [callback] callback(dict) is called for every node, in order to allow modifications
* @returns {NodeData}
*/
toDict: function(recursive, callback) {
var i, l, node,
dict = {},
self = this;
$.each(NODE_ATTRS, function(i, a){
if(self[a] || self[a] === false){
dict[a] = self[a];
}
});
if(!$.isEmptyObject(this.data)){
dict.data = $.extend({}, this.data);
if($.isEmptyObject(dict.data)){
delete dict.data;
}
}
if( callback ){
callback(dict);
}
if( recursive ) {
if(this.hasChildren()){
dict.children = [];
for(i=0, l=this.children.length; i<l; i++ ){
node = this.children[i];
if( !node.isStatusNode() ){
dict.children.push(node.toDict(true, callback));
}
}
}else{
// dict.children = null;
}
}
return dict;
},
/** Flip expanded status. */
toggleExpanded: function(){
return this.tree._callHook("nodeToggleExpanded", this);
},
/** Flip selection status. */
toggleSelected: function(){
return this.tree._callHook("nodeToggleSelected", this);
},
toString: function() {
return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>";
},
/** Call fn(node) for all child nodes.<br>
* Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visit: function(fn, includeSelf) {
var i, l,
res = true,
children = this.children;
if( includeSelf === true ) {
res = fn(this);
if( res === false || res === "skip" ){
return res;
}
}
if(children){
for(i=0, l=children.length; i<l; i++){
res = children[i].visit(fn, true);
if( res === false ){
break;
}
}
}
return res;
},
/** Call fn(node) for all child nodes and recursively load lazy children.<br>
* <b>Note:</b> If you need this method, you probably should consider to review
* your architecture! Recursivley loading nodes is a perfect way for lazy
* programmers to flood the server with requests ;-)
*
* @param {function} [fn] optional callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {$.Promise}
*/
visitAndLoad: function(fn, includeSelf, _recursion) {
var dfd, res, loaders,
node = this;
// node.debug("visitAndLoad");
if( fn && includeSelf === true ) {
res = fn(node);
if( res === false || res === "skip" ) {
return _recursion ? res : _getResolvedPromise();
}
}
if( !node.children && !node.lazy ) {
return _getResolvedPromise();
}
dfd = new $.Deferred();
loaders = [];
// node.debug("load()...");
node.load().done(function(){
// node.debug("load()... done.");
for(var i=0, l=node.children.length; i<l; i++){
res = node.children[i].visitAndLoad(fn, true, true);
if( res === false ) {
dfd.reject();
break;
} else if ( res !== "skip" ) {
loaders.push(res); // Add promise to the list
}
}
$.when.apply(this, loaders).then(function(){
dfd.resolve();
});
});
return dfd.promise();
},
/** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
* Stop iteration, if fn() returns false.<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visitParents: function(fn, includeSelf) {
// Visit parent nodes (bottom up)
if(includeSelf && fn(this) === false){
return false;
}
var p = this.parent;
while( p ) {
if(fn(p) === false){
return false;
}
p = p.parent;
}
return true;
},
/** Write warning to browser console (prepending node info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
};
/* *****************************************************************************
* Fancytree
*/
/**
* Construct a new tree object.
*
* @class Fancytree
* @classdesc The controller behind a fancytree.
* This class also contains 'hook methods': see {@link Fancytree_Hooks}.
*
* @param {Widget} widget
*
* @property {FancytreeOptions} options
* @property {FancytreeNode} rootNode
* @property {FancytreeNode} activeNode
* @property {FancytreeNode} focusNode
* @property {jQueryObject} $div
* @property {object} widget
* @property {object} ext
* @property {object} data
* @property {object} options
* @property {string} _id
* @property {string} statusClassPropName
* @property {string} ariaPropName
* @property {string} nodeContainerAttrName
* @property {string} $container
* @property {FancytreeNode} lastSelectedNode
*/
function Fancytree(widget) {
this.widget = widget;
this.$div = widget.element;
this.options = widget.options;
if( this.options ) {
if( $.isFunction(this.options.lazyload ) && !$.isFunction(this.options.lazyLoad) ) {
this.options.lazyLoad = function() {
FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead.");
return widget.options.lazyload.apply(this, arguments);
};
}
if( $.isFunction(this.options.loaderror) ) {
$.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead.");
}
if( this.options.fx !== undefined ) {
FT.warn("The 'fx' options was replaced by 'toggleEffect' since 2014-11-30.");
}
}
this.ext = {}; // Active extension instances
// allow to init tree.data.foo from <div data-foo=''>
this.data = _getElementDataAsDict(this.$div);
this._id = $.ui.fancytree._nextId++;
this._ns = ".fancytree-" + this._id; // append for namespaced events
this.activeNode = null;
this.focusNode = null;
this._hasFocus = null;
this.lastSelectedNode = null;
this.systemFocusElement = null;
this.lastQuicksearchTerm = "";
this.lastQuicksearchTime = 0;
this.statusClassPropName = "span";
this.ariaPropName = "li";
this.nodeContainerAttrName = "li";
// Remove previous markup if any
this.$div.find(">ul.fancytree-container").remove();
// Create a node without parent.
var fakeParent = { tree: this },
$ul;
this.rootNode = new FancytreeNode(fakeParent, {
title: "root",
key: "root_" + this._id,
children: null,
expanded: true
});
this.rootNode.parent = null;
// Create root markup
$ul = $("<ul>", {
"class": "ui-fancytree fancytree-container"
}).appendTo(this.$div);
this.$container = $ul;
this.rootNode.ul = $ul[0];
if(this.options.debugLevel == null){
this.options.debugLevel = FT.debugLevel;
}
// Add container to the TAB chain
// See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
if(this.options.aria){
this.$container
.attr("role", "tree")
.attr("aria-multiselectable", true);
}
}
Fancytree.prototype = /** @lends Fancytree# */{
/* Return a context object that can be re-used for _callHook().
* @param {Fancytree | FancytreeNode | EventData} obj
* @param {Event} originalEvent
* @param {Object} extra
* @returns {EventData}
*/
_makeHookContext: function(obj, originalEvent, extra) {
var ctx, tree;
if(obj.node !== undefined){
// obj is already a context object
if(originalEvent && obj.originalEvent !== originalEvent){
$.error("invalid args");
}
ctx = obj;
}else if(obj.tree){
// obj is a FancytreeNode
tree = obj.tree;
ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent };
}else if(obj.widget){
// obj is a Fancytree
ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent };
}else{
$.error("invalid args");
}
if(extra){
$.extend(ctx, extra);
}
return ctx;
},
/* Trigger a hook function: funcName(ctx, [...]).
*
* @param {string} funcName
* @param {Fancytree|FancytreeNode|EventData} contextObject
* @param {any} [_extraArgs] optional additional arguments
* @returns {any}
*/
_callHook: function(funcName, contextObject, _extraArgs) {
var ctx = this._makeHookContext(contextObject),
fn = this[funcName],
args = Array.prototype.slice.call(arguments, 2);
if(!$.isFunction(fn)){
$.error("_callHook('" + funcName + "') is not a function");
}
args.unshift(ctx);
// this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
return fn.apply(this, args);
},
/* Check if current extensions dependencies are met and throw an error if not.
*
* This method may be called inside the `treeInit` hook for custom extensions.
*
* @param {string} extension name of the required extension
* @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present
* @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter)
* @param {string} [message] optional error message (defaults to a descriptve error message)
*/
_requireExtension: function(name, required, before, message) {
before = !!before;
var thisName = this._local.name,
extList = this.options.extensions,
isBefore = $.inArray(name, extList) < $.inArray(thisName, extList),
isMissing = required && this.ext[name] == null,
badOrder = !isMissing && before != null && (before !== isBefore);
_assert(thisName && thisName !== name, "invalid or same name");
if( isMissing || badOrder ){
if( !message ){
if( isMissing || required ){
message = "'" + thisName + "' extension requires '" + name + "'";
if( badOrder ){
message += " to be registered " + (before ? "before" : "after") + " itself";
}
}else{
message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`";
}
}
$.error(message);
return false;
}
return true;
},
/** Activate node with a given key and fire focus and activate events.
*
* A prevously activated node will be deactivated.
* If activeVisible option is set, all parents will be expanded as necessary.
* Pass key = false, to deactivate the current node only.
* @param {string} key
* @returns {FancytreeNode} activated node (null, if not found)
*/
activateKey: function(key) {
var node = this.getNodeByKey(key);
if(node){
node.setActive();
}else if(this.activeNode){
this.activeNode.setActive(false);
}
return node;
},
/** (experimental)
*
* @param {Array} patchList array of [key, NodePatch] arrays
* @returns {$.Promise} resolved, when all patches have been applied
* @see TreePatch
*/
applyPatch: function(patchList) {
var dfd, i, p2, key, patch, node,
patchCount = patchList.length,
deferredList = [];
for(i=0; i<patchCount; i++){
p2 = patchList[i];
_assert(p2.length === 2, "patchList must be an array of length-2-arrays");
key = p2[0];
patch = p2[1];
node = (key === null) ? this.rootNode : this.getNodeByKey(key);
if(node){
dfd = new $.Deferred();
deferredList.push(dfd);
node.applyPatch(patch).always(_makeResolveFunc(dfd, node));
}else{
this.warn("could not find node with key '" + key + "'");
}
}
// Return a promise that is resolved, when ALL patches were applied
return $.when.apply($, deferredList).promise();
},
/* TODO: implement in dnd extension
cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if(dd){
dd.cancel();
}
},
*/
/** Return the number of nodes.
* @returns {integer}
*/
count: function() {
return this.rootNode.countChildren();
},
/** Write to browser console if debugLevel >= 2 (prepending tree name)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
// TODO: disable()
// TODO: enable()
// TODO: enableUpdate()
/** Find the next visible node that starts with `match`, starting at `startNode`
* and wrap-around at the end.
*
* @param {string|function} match
* @param {FancytreeNode} [startNode] defaults to first node
* @returns {FancytreeNode} matching node or null
*/
findNextNode: function(match, startNode, visibleOnly) {
var stopNode = null,
parentChildren = startNode.parent.children,
matchingNode = null,
walkVisible = function(parent, idx, fn) {
var i, grandParent,
parentChildren = parent.children,
siblingCount = parentChildren.length,
node = parentChildren[idx];
// visit node itself
if( node && fn(node) === false ) {
return false;
}
// visit descendants
if( node && node.children && node.expanded ) {
if( walkVisible(node, 0, fn) === false ) {
return false;
}
}
// visit subsequent siblings
for( i = idx + 1; i < siblingCount; i++ ) {
if( walkVisible(parent, i, fn) === false ) {
return false;
}
}
// visit parent's subsequent siblings
grandParent = parent.parent;
if( grandParent ) {
return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn);
} else {
// wrap-around: restart with first node
return walkVisible(parent, 0, fn);
}
};
match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match;
startNode = startNode || this.getFirstChild();
walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){
// Stop iteration if we see the start node a second time
if( node === stopNode ) {
return false;
}
stopNode = stopNode || node;
// Ignore nodes hidden by a filter
if( ! $(node.span).is(":visible") ) {
node.debug("quicksearch: skipping hidden node");
return;
}
// Test if we found a match, but search for a second match if this
// was the currently active node
if( match(node) ) {
// node.debug("quicksearch match " + node.title, startNode);
matchingNode = node;
if( matchingNode !== startNode ) {
return false;
}
}
});
return matchingNode;
},
// TODO: fromDict
/**
* Generate INPUT elements that can be submitted with html forms.
*
* In selectMode 3 only the topmost selected nodes are considered, unless
* `opts.stopOnParents: false` is passed.
*
* @param {boolean | string} [selected=true] Pass false to disable, pass a string to overide the field name (default: 'ft_ID[]')
* @param {boolean | string} [active=true] Pass false to disable, pass a string to overide the field name (default: 'ft_ID_active')
* @param {object} [opts] default { stopOnParents: true }
*/
generateFormElements: function(selected, active, opts) {
// TODO: test case
opts = opts || {};
var nodeList,
selectedName = (typeof selected === "string") ? selected : "ft_" + this._id + "[]",
activeName = (typeof active === "string") ? active : "ft_" + this._id + "_active",
id = "fancytree_result_" + this._id,
$result = $("#" + id),
stopOnParents = this.options.selectMode === 3 && opts.stopOnParents !== false;
if($result.length){
$result.empty();
}else{
$result = $("<div>", {
id: id
}).hide().insertAfter(this.$container);
}
if(selected !== false){
nodeList = this.getSelectedNodes(stopOnParents);
$.each(nodeList, function(idx, node){
$result.append($("<input>", {
type: "checkbox",
name: selectedName,
value: node.key,
checked: true
}));
});
}
if(active !== false && this.activeNode){
$result.append($("<input>", {
type: "radio",
name: activeName,
value: this.activeNode.key,
checked: true
}));
}
},
/**
* Return the currently active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.activeNode;
},
/** Return the first top level node if any (not the invisible root node).
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.rootNode.getFirstChild();
},
/**
* Return node that has keyboard focus or null.
* @returns {FancytreeNode}
*/
getFocusNode: function() {
return this.focusNode;
},
/**
* Return node with a given key or null if not found.
* @param {string} key
* @param {FancytreeNode} [searchRoot] only search below this node
* @returns {FancytreeNode | null}
*/
getNodeByKey: function(key, searchRoot) {
// Search the DOM by element ID (assuming this is faster than traversing all nodes).
// $("#...") has problems, if the key contains '.', so we use getElementById()
var el, match;
if(!searchRoot){
el = document.getElementById(this.options.idPrefix + key);
if( el ){
return el.ftnode ? el.ftnode : null;
}
}
// Not found in the DOM, but still may be in an unrendered part of tree
// TODO: optimize with specialized loop
// TODO: consider keyMap?
searchRoot = searchRoot || this.rootNode;
match = null;
searchRoot.visit(function(node){
// window.console.log("getNodeByKey(" + key + "): ", node.key);
if(node.key === key) {
match = node;
return false;
}
}, true);
return match;
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.rootNode;
},
/**
* Return an array of selected nodes.
* @param {boolean} [stopOnParents=false] only return the topmost selected
* node (useful with selectMode 3)
* @returns {FancytreeNode[]}
*/
getSelectedNodes: function(stopOnParents) {
var nodeList = [];
this.rootNode.visit(function(node){
if( node.selected ) {
nodeList.push(node);
if( stopOnParents === true ){
return "skip"; // stop processing this branch
}
}
});
return nodeList;
},
/** Return true if the tree control has keyboard focus
* @returns {boolean}
*/
hasFocus: function(){
return !!this._hasFocus;
},
/** Write to browser console if debugLevel >= 1 (prepending tree name)
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/*
TODO: isInitializing: function() {
return ( this.phase=="init" || this.phase=="postInit" );
},
TODO: isReloading: function() {
return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
},
TODO: isUserEvent: function() {
return ( this.phase=="userEvent" );
},
*/
/**
* Make sure that a node with a given ID is loaded, by traversing - and
* loading - its parents. This method is ment for lazy hierarchies.
* A callback is executed for every node as we go.
* @example
* tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
* if(status === "loaded") {
* console.log("loaded intermiediate node " + node);
* }else if(status === "ok") {
* node.activate();
* }
* });
*
* @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7')
* @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error')
* @returns {$.Promise}
*/
loadKeyPath: function(keyPathList, callback, _rootNode) {
var deferredList, dfd, i, path, key, loadMap, node, root, segList,
sep = this.options.keyPathSeparator,
self = this;
if(!$.isArray(keyPathList)){
keyPathList = [keyPathList];
}
// Pass 1: handle all path segments for nodes that are already loaded
// Collect distinct top-most lazy nodes in a map
loadMap = {};
for(i=0; i<keyPathList.length; i++){
root = _rootNode || this.rootNode;
path = keyPathList[i];
// strip leading slash
if(path.charAt(0) === sep){
path = path.substr(1);
}
// traverse and strip keys, until we hit a lazy, unloaded node
segList = path.split(sep);
while(segList.length){
key = segList.shift();
// node = _findDirectChild(root, key);
node = root._findDirectChild(key);
if(!node){
this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")");
callback.call(this, key, "error");
break;
}else if(segList.length === 0){
callback.call(this, node, "ok");
break;
}else if(!node.lazy || (node.hasChildren() !== undefined )){
callback.call(this, node, "loaded");
root = node;
}else{
callback.call(this, node, "loaded");
// segList.unshift(key);
if(loadMap[key]){
loadMap[key].push(segList.join(sep));
}else{
loadMap[key] = [segList.join(sep)];
}
break;
}
}
}
// alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap));
// Now load all lazy nodes and continue itearation for remaining paths
deferredList = [];
// Avoid jshint warning 'Don't make functions within a loop.':
function __lazyload(key, node, dfd){
callback.call(self, node, "loading");
node.load().done(function(){
self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self));
}).fail(function(errMsg){
self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")");
callback.call(self, node, "error");
dfd.reject();
});
}
for(key in loadMap){
node = root._findDirectChild(key);
// alert("loadKeyPath: lazy node(" + key + ") = " + node);
dfd = new $.Deferred();
deferredList.push(dfd);
__lazyload(key, node, dfd);
}
// Return a promise that is resolved, when ALL paths were loaded
return $.when.apply($, deferredList).promise();
},
/** Re-fire beforeActivate and activate events. */
reactivate: function(setFocus) {
var res,
node = this.activeNode;
if( !node ) {
return _getResolvedPromise();
}
this.activeNode = null; // Force re-activating
res = node.setActive();
if( setFocus ){
node.setFocus();
}
return res;
},
/** Reload tree from source and return a promise.
* @param [source] optional new source (defaults to initial source data)
* @returns {$.Promise}
*/
reload: function(source) {
this._callHook("treeClear", this);
return this._callHook("treeLoad", this, source);
},
/**Render tree (i.e. create DOM elements for all top-level nodes).
* @param {boolean} [force=false] create DOM elemnts, even is parent is collapsed
* @param {boolean} [deep=false]
*/
render: function(force, deep) {
return this.rootNode.render(force, deep);
},
// TODO: selectKey: function(key, select)
// TODO: serializeArray: function(stopOnParents)
/**
* @param {boolean} [flag=true]
*/
setFocus: function(flag) {
return this._callHook("treeSetFocus", this, flag);
},
/**
* Return all nodes as nested list of {@link NodeData}.
*
* @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children)
* @param {function} [callback(node)] Called for every node
* @returns {Array | object}
* @see FancytreeNode#toDict
*/
toDict: function(includeRoot, callback){
var res = this.rootNode.toDict(true, callback);
return includeRoot ? res : res.children;
},
/* Implicitly called for string conversions.
* @returns {string}
*/
toString: function(){
return "<Fancytree(#" + this._id + ")>";
},
/* _trigger a widget event with additional node ctx.
* @see EventData
*/
_triggerNodeEvent: function(type, node, originalEvent, extra) {
// this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx);
var ctx = this._makeHookContext(node, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if(res !== false && ctx.result !== undefined){
return ctx.result;
}
return res;
},
/* _trigger a widget event with additional tree data. */
_triggerTreeEvent: function(type, originalEvent, extra) {
// this.debug("_trigger(" + type + ")", ctx);
var ctx = this._makeHookContext(this, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if(res !== false && ctx.result !== undefined){
return ctx.result;
}
return res;
},
/** Call fn(node) for all nodes.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @returns {boolean} false, if the iterator was stopped.
*/
visit: function(fn) {
return this.rootNode.visit(fn, false);
},
/** Write warning to browser console (prepending tree info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
};
/**
* These additional methods of the {@link Fancytree} class are 'hook functions'
* that can be used and overloaded by extensions.
* (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.)
* @mixin Fancytree_Hooks
*/
$.extend(Fancytree.prototype,
/** @lends Fancytree_Hooks# */
{
/** Default handling for mouse click events.
*
* @param {EventData} ctx
*/
nodeClick: function(ctx) {
// this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which);
var activate, expand,
// event = ctx.originalEvent,
targetType = ctx.targetType,
node = ctx.node;
// TODO: use switch
// TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
if( targetType === "expander" ) {
// Clicking the expander icon always expands/collapses
this._callHook("nodeToggleExpanded", ctx);
} else if( targetType === "checkbox" ) {
// Clicking the checkbox always (de)selects
this._callHook("nodeToggleSelected", ctx);
if( ctx.options.focusOnSelect ) { // #358
this._callHook("nodeSetFocus", ctx, true);
}
} else {
// Honor `clickFolderMode` for
expand = false;
activate = true;
if( node.folder ) {
switch( ctx.options.clickFolderMode ) {
case 2: // expand only
expand = true;
activate = false;
break;
case 3: // expand and activate
activate = true;
expand = true; //!node.isExpanded();
break;
// else 1 or 4: just activate
}
}
if( activate ) {
this.nodeSetFocus(ctx);
this._callHook("nodeSetActive", ctx, true);
}
if( expand ) {
if(!activate){
// this._callHook("nodeSetFocus", ctx);
}
// this._callHook("nodeSetExpanded", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
}
// Make sure that clicks stop, otherwise <a href='#'> jumps to the top
// if(event.target.localName === "a" && event.target.className === "fancytree-title"){
// event.preventDefault();
// }
// TODO: return promise?
},
/** Collapse all other children of same parent.
*
* @param {EventData} ctx
* @param {object} callOpts
*/
nodeCollapseSiblings: function(ctx, callOpts) {
// TODO: return promise?
var ac, i, l,
node = ctx.node;
if( node.parent ){
ac = node.parent.children;
for (i=0, l=ac.length; i<l; i++) {
if ( ac[i] !== node && ac[i].expanded ){
this._callHook("nodeSetExpanded", ac[i], false, callOpts);
}
}
}
},
/** Default handling for mouse douleclick events.
* @param {EventData} ctx
*/
nodeDblclick: function(ctx) {
// TODO: return promise?
if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) {
// this.nodeSetFocus(ctx);
// this._callHook("nodeSetActive", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
// TODO: prevent text selection on dblclicks
if( ctx.targetType === "title" ) {
ctx.originalEvent.preventDefault();
}
},
/** Default handling for mouse keydown events.
*
* NOTE: this may be called with node == null if tree (but no node) has focus.
* @param {EventData} ctx
*/
nodeKeydown: function(ctx) {
// TODO: return promise?
var matchNode, stamp, res, focusNode,
event = ctx.originalEvent,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
which = event.which,
whichChar = String.fromCharCode(which),
clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey),
$target = $(event.target),
handled = true,
activate = !(event.ctrlKey || !opts.autoActivate );
// (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
// FT.debug("eventToString", which, '"' + String.fromCharCode(which) + '"', '"' + FT.eventToString(event) + '"');
// Set focus to active (or first node) if no other node has the focus yet
if( !node ){
focusNode = (this.getActiveNode() || this.getFirstChild());
if (focusNode){
focusNode.setFocus();
node = ctx.node = this.focusNode;
node.debug("Keydown force focus on active node");
}
}
if( opts.quicksearch && clean && /\w/.test(whichChar) && !$target.is(":input:enabled") ) {
// Allow to search for longer streaks if typed in quickly
stamp = new Date().getTime();
if( stamp - tree.lastQuicksearchTime > 500 ) {
tree.lastQuicksearchTerm = "";
}
tree.lastQuicksearchTime = stamp;
tree.lastQuicksearchTerm += whichChar;
// tree.debug("quicksearch find", tree.lastQuicksearchTerm);
matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode());
if( matchNode ) {
matchNode.setActive();
}
event.preventDefault();
return;
}
switch( FT.eventToString(event) ) {
case "+":
case "=": // 187: '+' @ Chrome, Safari
tree.nodeSetExpanded(ctx, true);
break;
case "-":
tree.nodeSetExpanded(ctx, false);
break;
case "space":
if(opts.checkbox){
tree.nodeToggleSelected(ctx);
}else{
tree.nodeSetActive(ctx, true);
}
break;
case "return":
tree.nodeSetActive(ctx, true);
break;
case "backspace":
case "left":
case "right":
case "up":
case "down":
res = node.navigate(event.which, activate);
break;
default:
handled = false;
}
if(handled){
event.preventDefault();
}
},
// /** Default handling for mouse keypress events. */
// nodeKeypress: function(ctx) {
// var event = ctx.originalEvent;
// },
// /** Trigger lazyLoad event (async). */
// nodeLazyLoad: function(ctx) {
// var node = ctx.node;
// if(this._triggerNodeEvent())
// },
/** Load child nodes (async).
*
* @param {EventData} ctx
* @param {object[]|object|string|$.Promise|function} source
* @returns {$.Promise} The deferred will be resolved as soon as the (ajax)
* data was rendered.
*/
nodeLoadChildren: function(ctx, source) {
var ajax, delay, dfd,
tree = ctx.tree,
node = ctx.node;
if($.isFunction(source)){
source = source();
}
// TOTHINK: move to 'ajax' extension?
if(source.url){
// `source` is an Ajax options object
ajax = $.extend({}, ctx.options.ajax, source);
if(ajax.debugDelay){
// simulate a slow server
delay = ajax.debugDelay;
if($.isArray(delay)){ // random delay range [min..max]
delay = delay[0] + Math.random() * (delay[1] - delay[0]);
}
node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms");
ajax.debugDelay = false;
dfd = $.Deferred(function (dfd) {
setTimeout(function () {
$.ajax(ajax)
.done(function () { dfd.resolveWith(this, arguments); })
.fail(function () { dfd.rejectWith(this, arguments); });
}, delay);
});
}else{
dfd = $.ajax(ajax);
}
// Defer the deferred: we want to be able to reject, even if ajax
// resolved ok.
source = new $.Deferred();
dfd.done(function (data, textStatus, jqXHR) {
var errorObj, res;
if(this.dataType === "json" && typeof data === "string"){
$.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
}
// postProcess is similar to the standard ajax dataFilter hook,
// but it is also called for JSONP
if( ctx.options.postProcess ){
res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, error: null, dataType: this.dataType});
if( res.error ) {
errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error};
errorObj = tree._makeHookContext(node, null, errorObj);
source.rejectWith(this, [errorObj]);
return;
}
data = $.isArray(res) ? res : data;
} else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) {
// Process ASPX WebMethod JSON object inside "d" property
data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d;
}
source.resolveWith(this, [data]);
}).fail(function (jqXHR, textStatus, errorThrown) {
var errorObj = tree._makeHookContext(node, null, {
error: jqXHR,
args: Array.prototype.slice.call(arguments),
message: errorThrown,
details: jqXHR.status + ": " + errorThrown
});
source.rejectWith(this, [errorObj]);
});
}
// #383: accept and convert ECMAScript 6 Promise
if( $.isFunction(source.then) && $.isFunction(source["catch"]) ) {
dfd = source;
source = new $.Deferred();
dfd.then(function(value){
source.resolve(value);
}, function(reason){
source.reject(reason);
});
}
if($.isFunction(source.promise)){
// `source` is a deferred, i.e. ajax request
_assert(!node.isLoading(), "recursive load");
// node._isLoading = true;
tree.nodeSetStatus(ctx, "loading");
source.done(function (children) {
tree.nodeSetStatus(ctx, "ok");
}).fail(function(error){
var ctxErr;
if (error.node && error.error && error.message) {
// error is already a context object
ctxErr = error;
} else {
ctxErr = tree._makeHookContext(node, null, {
error: error, // it can be jqXHR or any custom error
args: Array.prototype.slice.call(arguments),
message: error ? (error.message || error.toString()) : ""
});
}
if( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) {
tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details);
}
});
}
// $.when(source) resolves also for non-deferreds
return $.when(source).done(function(children){
var metaData;
if( $.isPlainObject(children) ){
// We got {foo: 'abc', children: [...]}
// Copy extra properties to tree.data.foo
_assert($.isArray(children.children), "source must contain (or be) an array of children");
_assert(node.isRoot(), "source may only be an object for root nodes");
metaData = children;
children = children.children;
delete metaData.children;
$.extend(tree.data, metaData);
}
_assert($.isArray(children), "expected array of children");
node._setChildren(children);
// trigger fancytreeloadchildren
tree._triggerNodeEvent("loadChildren", node);
// }).always(function(){
// node._isLoading = false;
});
},
/** [Not Implemented] */
nodeLoadKeyPath: function(ctx, keyPathList) {
// TODO: implement and improve
// http://code.google.com/p/dynatree/issues/detail?id=222
},
/**
* Remove a single direct child of ctx.node.
* @param {EventData} ctx
* @param {FancytreeNode} childNode dircect child of ctx.node
*/
nodeRemoveChild: function(ctx, childNode) {
var idx,
node = ctx.node,
opts = ctx.options,
subCtx = $.extend({}, ctx, {node: childNode}),
children = node.children;
// FT.debug("nodeRemoveChild()", node.toString(), childNode.toString());
if( children.length === 1 ) {
_assert(childNode === children[0], "invalid single child");
return this.nodeRemoveChildren(ctx);
}
if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){
this.activeNode.setActive(false); // TODO: don't fire events
}
if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveMarkup(subCtx);
this.nodeRemoveChildren(subCtx);
idx = $.inArray(childNode, children);
_assert(idx >= 0, "invalid child");
// Unlink to support GC
childNode.visit(function(n){
n.parent = null;
}, true);
this._callHook("treeRegisterNode", this, false, childNode);
if ( opts.removeNode ){
opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
}
// remove from child list
children.splice(idx, 1);
},
/**Remove HTML markup for all descendents of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveChildMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if(node.ul){
if( node.isRoot() ) {
$(node.ul).empty();
} else {
$(node.ul).remove();
node.ul = null;
}
node.visit(function(n){
n.li = n.ul = null;
});
}
},
/**Remove all descendants of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildren: function(ctx) {
var subCtx,
tree = ctx.tree,
node = ctx.node,
children = node.children,
opts = ctx.options;
// FT.debug("nodeRemoveChildren()", node.toString());
if(!children){
return;
}
if( this.activeNode && this.activeNode.isDescendantOf(node)){
this.activeNode.setActive(false); // TODO: don't fire events
}
if( this.focusNode && this.focusNode.isDescendantOf(node)){
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveChildMarkup(ctx);
// Unlink children to support GC
// TODO: also delete this.children (not possible using visit())
subCtx = $.extend({}, ctx);
node.visit(function(n){
n.parent = null;
tree._callHook("treeRegisterNode", tree, false, n);
if ( opts.removeNode ){
subCtx.node = n;
opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
}
});
if( node.lazy ){
// 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
node.children = [];
} else{
node.children = null;
}
node.expanded = false; // #449
this.nodeRenderStatus(ctx);
},
/**Remove HTML markup for ctx.node and all its descendents.
* @param {EventData} ctx
*/
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if(node.li){
$(node.li).remove();
node.li = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/**
* Create `<li><span>..</span> .. </li>` tags for this node.
*
* This method takes care that all HTML markup is created that is required
* to display this node in it's current state.
*
* Call this method to create new nodes, or after the strucuture
* was changed (e.g. after moving this node or adding/removing children)
* nodeRenderTitle() and nodeRenderStatus() are implied.
*
* Note: if a node was created/removed, nodeRender() must be called for the
* parent.
* <code>
* <li id='KEY' ftnode=NODE>
* <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'>
* <span class="fancytree-expander"></span>
* <span class="fancytree-checkbox"></span> // only present in checkbox mode
* <span class="fancytree-icon"></span>
* <a href="#" class="fancytree-title"> Node 1 </a>
* </span>
* <ul> // only present if node has children
* <li id='KEY' ftnode=NODE> child1 ... </li>
* <li id='KEY' ftnode=NODE> child2 ... </li>
* </ul>
* </li>
* </code>
*
* @param {EventData} ctx
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
* @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later
*/
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
/* This method must take care of all cases where the current data mode
* (i.e. node hierarchy) does not match the current markup.
*
* - node was not yet rendered:
* create markup
* - node was rendered: exit fast
* - children have been added
* - childern have been removed
*/
var childLI, childNode1, childNode2, i, l, next, subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
firstTime = false,
parent = node.parent,
isRootNode = !parent,
children = node.children;
// FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
if( ! isRootNode && ! parent.ul ) {
// Calling node.collapse on a deep, unrendered node
return;
}
_assert(isRootNode || parent.ul, "parent UL must exist");
// Render the node
if( !isRootNode ){
// Discard markup on force-mode, or if it is not linked to parent <ul>
if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
if(node.li.parentNode !== node.parent.ul){
// May happen, when a top-level node was dropped over another
this.debug("Unlinking " + node + " (must be child of " + node.parent + ")");
}
// this.debug("nodeRemoveMarkup...");
this.nodeRemoveMarkup(ctx);
}
// Create <li><span /> </li>
// node.debug("render...");
if( !node.li ) {
// node.debug("render... really");
firstTime = true;
node.li = document.createElement("li");
node.li.ftnode = node;
if(aria){
// TODO: why doesn't this work:
// node.li.role = "treeitem";
// $(node.li).attr("role", "treeitem")
// .attr("aria-labelledby", "ftal_" + node.key);
}
if( node.key && opts.generateIds ){
node.li.id = opts.idPrefix + node.key;
}
node.span = document.createElement("span");
node.span.className = "fancytree-node";
if(aria){
$(node.span).attr("aria-labelledby", "ftal_" + node.key);
}
node.li.appendChild(node.span);
// Create inner HTML for the <span> (expander, checkbox, icon, and title)
this.nodeRenderTitle(ctx);
// Allow tweaking and binding, after node was created for the first time
if ( opts.createNode ){
opts.createNode.call(tree, {type: "createNode"}, ctx);
}
}else{
// this.nodeRenderTitle(ctx);
this.nodeRenderStatus(ctx);
}
// Allow tweaking after node state was rendered
if ( opts.renderNode ){
opts.renderNode.call(tree, {type: "renderNode"}, ctx);
}
}
// Visit child nodes
if( children ){
if( isRootNode || node.expanded || deep === true ) {
// Create a UL to hold the children
if( !node.ul ){
node.ul = document.createElement("ul");
if((collapsed === true && !_recursive) || !node.expanded){
// hide top UL, so we can use an animation to show it later
node.ul.style.display = "none";
}
if(aria){
$(node.ul).attr("role", "group");
}
if ( node.li ) { // issue #67
node.li.appendChild(node.ul);
} else {
node.tree.$div.append(node.ul);
}
}
// Add child markup
for(i=0, l=children.length; i<l; i++) {
subCtx = $.extend({}, ctx, {node: children[i]});
this.nodeRender(subCtx, force, deep, false, true);
}
// Remove <li> if nodes have moved to another parent
childLI = node.ul.firstChild;
while( childLI ){
childNode2 = childLI.ftnode;
if( childNode2 && childNode2.parent !== node ) {
node.debug("_fixParent: remove missing " + childNode2, childLI);
next = childLI.nextSibling;
childLI.parentNode.removeChild(childLI);
childLI = next;
}else{
childLI = childLI.nextSibling;
}
}
// Make sure, that <li> order matches node.children order.
childLI = node.ul.firstChild;
for(i=0, l=children.length-1; i<l; i++) {
childNode1 = children[i];
childNode2 = childLI.ftnode;
if( childNode1 !== childNode2 ) {
// node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
node.ul.insertBefore(childNode1.li, childNode2.li);
} else {
childLI = childLI.nextSibling;
}
}
}
}else{
// No children: remove markup if any
if( node.ul ){
// alert("remove child markup for " + node);
this.warn("remove child markup for " + node);
this.nodeRemoveChildMarkup(ctx);
}
}
if( !isRootNode ){
// Update element classes according to node state
// this.nodeRenderStatus(ctx);
// Finally add the whole structure to the DOM, so the browser can render
if(firstTime){
parent.ul.appendChild(node.li);
}
}
},
/** Create HTML inside the node's outer <span> (i.e. expander, checkbox,
* icon, and title).
*
* nodeRenderStatus() is implied.
* @param {EventData} ctx
* @param {string} [title] optinal new title
*/
nodeRenderTitle: function(ctx, title) {
// set node connector images, links and text
var id, iconSpanClass, nodeTitle, role, tabindex, tooltip,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
level = node.getLevel(),
ares = [],
iconSrc = node.data.icon;
if(title !== undefined){
node.title = title;
}
if(!node.span){
// Silently bail out if node was not rendered yet, assuming
// node.render() will be called as the node becomes visible
return;
}
// connector (expanded, expandable or simple)
// TODO: optimize this if clause
if( level < opts.minExpandLevel ) {
if( !node.lazy ) {
node.expanded = true;
}
if(level > 1){
if(aria){
ares.push("<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>");
}else{
ares.push("<span class='fancytree-expander fancytree-expander-fixed''></span>");
}
}
// .. else (i.e. for root level) skip expander/connector alltogether
} else {
if(aria){
ares.push("<span role='button' class='fancytree-expander'></span>");
}else{
ares.push("<span class='fancytree-expander'></span>");
}
}
// Checkbox mode
if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) {
if(aria){
ares.push("<span role='checkbox' class='fancytree-checkbox'></span>");
}else{
ares.push("<span class='fancytree-checkbox'></span>");
}
}
// folder or doctype icon
role = aria ? " role='img'" : "";
if( iconSrc === true || (iconSrc !== false && opts.icons !== false) ) {
// opts.icons defines the default behavior, node.icon == true/false can override this
if ( iconSrc && typeof iconSrc === "string" ) {
// node.icon is an image url
iconSrc = (iconSrc.charAt(0) === "/") ? iconSrc : ((opts.imagePath || "") + iconSrc);
ares.push("<img src='" + iconSrc + "' class='fancytree-icon' alt='' />");
} else {
// See if node.iconClass or opts.iconClass() define a class name
iconSpanClass = (opts.iconClass && opts.iconClass.call(tree, node, ctx)) || node.data.iconclass || null;
if( iconSpanClass ) {
ares.push("<span " + role + " class='fancytree-custom-icon " + iconSpanClass + "'></span>");
} else {
ares.push("<span " + role + " class='fancytree-icon'></span>");
}
}
}
// node title
nodeTitle = "";
if ( opts.renderTitle ){
nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || "";
}
if(!nodeTitle){
tooltip = node.tooltip ? " title='" + FT.escapeHtml(node.tooltip) + "'" : "";
id = aria ? " id='ftal_" + node.key + "'" : "";
role = aria ? " role='treeitem'" : "";
tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + node.title + "</span>";
}
ares.push(nodeTitle);
// Note: this will trigger focusout, if node had the focus
//$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly
node.span.innerHTML = ares.join("");
// Update CSS classes
this.nodeRenderStatus(ctx);
},
/** Update element classes according to node state.
* @param {EventData} ctx
*/
nodeRenderStatus: function(ctx) {
// Set classes for current status
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
// nodeContainer = node[tree.nodeContainerAttrName],
hasChildren = node.hasChildren(),
isLastSib = node.isLastSibling(),
aria = opts.aria,
// $ariaElem = aria ? $(node[tree.ariaPropName]) : null,
$ariaElem = $(node.span).find(".fancytree-title"),
cn = opts._classNames,
cnList = [],
statusElem = node[tree.statusClassPropName];
if( !statusElem ){
// if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
return;
}
// Build a list of class names that we will add to the node <span>
cnList.push(cn.node);
if( tree.activeNode === node ){
cnList.push(cn.active);
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// tree.$container.removeAttr("tabindex");
// }else{
// $(">span.fancytree-title", statusElem).removeAttr("tabindex");
// tree.$container.attr("tabindex", "0");
}
if( tree.focusNode === node ){
cnList.push(cn.focused);
if(aria){
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
// TODO: is this the right element for this attribute?
$ariaElem
.attr("aria-activedescendant", true);
// .attr("tabindex", "-1");
}
}else if(aria){
// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
$ariaElem
.removeAttr("aria-activedescendant");
// .removeAttr("tabindex");
}
if( node.expanded ){
cnList.push(cn.expanded);
if(aria){
$ariaElem.attr("aria-expanded", true);
}
}else if(aria){
$ariaElem.removeAttr("aria-expanded");
}
if( node.folder ){
cnList.push(cn.folder);
}
if( hasChildren !== false ){
cnList.push(cn.hasChildren);
}
// TODO: required?
if( isLastSib ){
cnList.push(cn.lastsib);
}
if( node.lazy && node.children == null ){
cnList.push(cn.lazy);
}
if( node.partsel ){
cnList.push(cn.partsel);
}
if( node.unselectable ){
cnList.push(cn.unselectable);
}
if( node._isLoading ){
cnList.push(cn.loading);
}
if( node._error ){
cnList.push(cn.error);
}
if( node.selected ){
cnList.push(cn.selected);
if(aria){
$ariaElem.attr("aria-selected", true);
}
}else if(aria){
$ariaElem.attr("aria-selected", false);
}
if( node.extraClasses ){
cnList.push(node.extraClasses);
}
// IE6 doesn't correctly evaluate multiple class names,
// so we create combined class names that can be used in the CSS
if( hasChildren === false ){
cnList.push(cn.combinedExpanderPrefix + "n" +
(isLastSib ? "l" : "")
);
}else{
cnList.push(cn.combinedExpanderPrefix +
(node.expanded ? "e" : "c") +
(node.lazy && node.children == null ? "d" : "") +
(isLastSib ? "l" : "")
);
}
cnList.push(cn.combinedIconPrefix +
(node.expanded ? "e" : "c") +
(node.folder ? "f" : "")
);
// node.span.className = cnList.join(" ");
statusElem.className = cnList.join(" ");
// TODO: we should not set this in the <span> tag also, if we set it here:
// Maybe most (all) of the classes should be set in LI instead of SPAN?
if(node.li){
node.li.className = isLastSib ? cn.lastsib : "";
}
},
/** Activate node.
* flag defaults to true.
* If flag is true, the node is activated (must be a synchronous operation)
* If flag is false, the node is deactivated (must be a synchronous operation)
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false}
* @returns {$.Promise}
*/
nodeSetActive: function(ctx, flag, callOpts) {
// Handle user click / [space] / [enter], according to clickFolderMode.
callOpts = callOpts || {};
var subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noEvents = (callOpts.noEvents === true),
noFocus = (callOpts.noFocus === true),
isActive = (node === tree.activeNode);
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetActive", flag);
if(isActive === flag){
// Nothing to do
return _getResolvedPromise(node);
}else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
if(flag){
if(tree.activeNode){
_assert(tree.activeNode !== node, "node was active (inconsistency)");
subCtx = $.extend({}, ctx, {node: tree.activeNode});
tree.nodeSetActive(subCtx, false);
_assert(tree.activeNode === null, "deactivate was out of sync?");
}
if(opts.activeVisible){
// tree.nodeMakeVisible(ctx);
node.makeVisible({scrollIntoView: false}); // nodeSetFocus will scroll
}
tree.activeNode = node;
tree.nodeRenderStatus(ctx);
if( !noFocus ) {
tree.nodeSetFocus(ctx);
}
if( !noEvents ) {
tree._triggerNodeEvent("activate", node, ctx.originalEvent);
}
}else{
_assert(tree.activeNode === node, "node was not active (inconsistency)");
tree.activeNode = null;
this.nodeRenderStatus(ctx);
if( !noEvents ) {
ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent);
}
}
return _getResolvedPromise(node);
},
/** Expand or collapse node, return Deferred.promise.
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise} The deferred will be resolved as soon as the (lazy)
* data was retrieved, rendered, and the expand animation finshed.
*/
nodeSetExpanded: function(ctx, flag, callOpts) {
callOpts = callOpts || {};
var _afterLoad, dfd, i, l, parents, prevAC,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noAnimation = (callOpts.noAnimation === true),
noEvents = (callOpts.noEvents === true);
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetExpanded(" + flag + ")");
if((node.expanded && flag) || (!node.expanded && !flag)){
// Nothing to do
// node.debug("nodeSetExpanded(" + flag + "): nothing to do");
return _getResolvedPromise(node);
}else if(flag && !node.lazy && !node.hasChildren() ){
// Prevent expanding of empty nodes
// return _getRejectedPromise(node, ["empty"]);
return _getResolvedPromise(node);
}else if( !flag && node.getLevel() < opts.minExpandLevel ) {
// Prevent collapsing locked levels
return _getRejectedPromise(node, ["locked"]);
}else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
// If this node inside a collpased node, no animation and scrolling is needed
if( !noAnimation && !node.isVisible() ) {
noAnimation = callOpts.noAnimation = true;
}
dfd = new $.Deferred();
// Auto-collapse mode: collapse all siblings
if( flag && !node.expanded && opts.autoCollapse ) {
parents = node.getParentList(false, true);
prevAC = opts.autoCollapse;
try{
opts.autoCollapse = false;
for(i=0, l=parents.length; i<l; i++){
// TODO: should return promise?
this._callHook("nodeCollapseSiblings", parents[i], callOpts);
}
}finally{
opts.autoCollapse = prevAC;
}
}
// Trigger expand/collapse after expanding
dfd.done(function(){
var lastChild = node.getLastChild();
if( flag && opts.autoScroll && !noAnimation && lastChild ) {
// Scroll down to last child, but keep current node visible
lastChild.scrollIntoView(true, {topNode: node}).always(function(){
if( !noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
});
} else {
if( !noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
}
});
// vvv Code below is executed after loading finished:
_afterLoad = function(callback){
var isVisible, isExpanded,
effect = opts.toggleEffect;
node.expanded = flag;
// Create required markup, but make sure the top UL is hidden, so we
// can animate later
tree._callHook("nodeRender", ctx, false, false, true);
// If the currently active node is now hidden, deactivate it
// if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) {
// this.activeNode.deactivate();
// }
// Expanding a lazy node: set 'loading...' and call callback
// if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) {
// this._loadContent();
// return;
// }
// Hide children, if node is collapsed
if( node.ul ) {
isVisible = (node.ul.style.display !== "none");
isExpanded = !!node.expanded;
if ( isVisible === isExpanded ) {
node.warn("nodeSetExpanded: UL.style.display already set");
} else if ( !effect || noAnimation ) {
node.ul.style.display = ( node.expanded || !parent ) ? "" : "none";
} else {
// The UI toggle() effect works with the ext-wide extension,
// while jQuery.animate() has problems when the title span
// has positon: absolute
// duration = opts.fx.duration || 200;
// easing = opts.fx.easing;
// $(node.ul).animate(opts.fx, duration, easing, function(){
// node.debug("nodeSetExpanded: animate start...");
$(node.ul).toggle(effect.effect, effect.options, effect.duration, function(){
// node.debug("nodeSetExpanded: animate done");
callback();
});
return;
}
}
callback();
};
// ^^^ Code above is executed after loading finshed.
// Load lazy nodes, if any. Then continue with _afterLoad()
if(flag && node.lazy && node.hasChildren() === undefined){
// node.debug("nodeSetExpanded: load start...");
node.load().done(function(){
// node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad(function () { dfd.resolveWith(node); });
}).fail(function(errMsg){
_afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); });
});
/*
var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent);
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
node.debug("nodeSetExpanded: load start...");
this._callHook("nodeLoadChildren", ctx, source).done(function(){
node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad.call(tree);
}).fail(function(errMsg){
dfd.rejectWith(node, ["load failed (" + errMsg + ")"]);
});
*/
}else{
_afterLoad(function () { dfd.resolveWith(node); });
}
// node.debug("nodeSetExpanded: returns");
return dfd.promise();
},
/** Focus or blur this node.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetFocus: function(ctx, flag) {
// ctx.node.debug("nodeSetFocus(" + flag + ")");
var ctx2,
tree = ctx.tree,
node = ctx.node;
flag = (flag !== false);
// Blur previous node if any
if(tree.focusNode){
if(tree.focusNode === node && flag){
// node.debug("nodeSetFocus(" + flag + "): nothing to do");
return;
}
ctx2 = $.extend({}, ctx, {node: tree.focusNode});
tree.focusNode = null;
this._triggerNodeEvent("blur", ctx2);
this._callHook("nodeRenderStatus", ctx2);
}
// Set focus to container and node
if(flag){
if( !this.hasFocus() ){
node.debug("nodeSetFocus: forcing container focus");
this._callHook("treeSetFocus", ctx, true, {calledByNode: true});
}
node.makeVisible({scrollIntoView: false});
tree.focusNode = node;
// node.debug("FOCUS...");
// $(node.span).find(".fancytree-title").focus();
this._triggerNodeEvent("focus", ctx);
// if(ctx.options.autoActivate){
// tree.nodeSetActive(ctx, true);
// }
if(ctx.options.autoScroll){
node.scrollIntoView();
}
this._callHook("nodeRenderStatus", ctx);
}
},
/** (De)Select node, return new status (sync).
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetSelected: function(ctx, flag) {
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options;
// flag defaults to true
flag = (flag !== false);
node.debug("nodeSetSelected(" + flag + ")", ctx);
if( node.unselectable){
return;
}
// TODO: !!node.expanded is nicer, but doesn't pass jshint
// https://github.com/jshint/jshint/issues/455
// if( !!node.expanded === !!flag){
if((node.selected && flag) || (!node.selected && !flag)){
return !!node.selected;
}else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){
return !!node.selected;
}
if(flag && opts.selectMode === 1){
// single selection mode
if(tree.lastSelectedNode){
tree.lastSelectedNode.setSelected(false);
}
}else if(opts.selectMode === 3){
// multi.hier selection mode
node.selected = flag;
// this._fixSelectionState(node);
node.fixSelection3AfterClick();
}
node.selected = flag;
this.nodeRenderStatus(ctx);
tree.lastSelectedNode = flag ? node : null;
tree._triggerNodeEvent("select", ctx);
},
/** Show node status (ok, loading, error) using styles and a dummy child node.
*
* @param {EventData} ctx
* @param status
* @param message
* @param details
*/
nodeSetStatus: function(ctx, status, message, details) {
var node = ctx.node,
tree = ctx.tree;
// cn = ctx.options._classNames;
function _clearStatusNode() {
// Remove dedicated dummy node, if any
var firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
try{
// I've seen exceptions here with loadKeyPath...
if(node.ul){
node.ul.removeChild(firstChild.li);
firstChild.li = null; // avoid leaks (DT issue 215)
}
}catch(e){}
if( node.children.length === 1 ){
node.children = [];
}else{
node.children.shift();
}
}
}
function _setStatusNode(data, type) {
// Create/modify the dedicated dummy node for 'loading...' or
// 'error!' status. (only called for direct child of the invisible
// system root)
var firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
$.extend(firstChild, data);
// tree._callHook("nodeRender", firstChild);
tree._callHook("nodeRenderTitle", firstChild);
} else {
data.key = "_statusNode";
node._setChildren([data]);
node.children[0].statusNodeType = type;
tree.render();
}
return node.children[0];
}
switch( status ){
case "ok":
_clearStatusNode();
// $(node.span).removeClass(cn.loading).removeClass(cn.error);
node._isLoading = false;
node._error = null;
node.renderStatus();
break;
case "loading":
// $(node.span).removeClass(cn.error).addClass(cn.loading);
if( !node.parent ) {
_setStatusNode({
title: tree.options.strings.loading + (message ? " (" + message + ") " : ""),
tooltip: details,
extraClasses: "fancytree-statusnode-wait"
}, status);
}
node._isLoading = true;
node._error = null;
node.renderStatus();
break;
case "error":
// $(node.span).removeClass(cn.loading).addClass(cn.error);
_setStatusNode({
title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""),
tooltip: details,
extraClasses: "fancytree-statusnode-error"
}, status);
node._isLoading = false;
node._error = { message: message, details: details };
node.renderStatus();
break;
default:
$.error("invalid node status " + status);
}
},
/**
*
* @param {EventData} ctx
*/
nodeToggleExpanded: function(ctx) {
return this.nodeSetExpanded(ctx, !ctx.node.expanded);
},
/**
* @param {EventData} ctx
*/
nodeToggleSelected: function(ctx) {
return this.nodeSetSelected(ctx, !ctx.node.selected);
},
/** Remove all nodes.
* @param {EventData} ctx
*/
treeClear: function(ctx) {
var tree = ctx.tree;
tree.activeNode = null;
tree.focusNode = null;
tree.$div.find(">ul.fancytree-container").empty();
// TODO: call destructors and remove reference loops
tree.rootNode.children = null;
},
/** Widget was created (called only once, even it re-initialized).
* @param {EventData} ctx
*/
treeCreate: function(ctx) {
},
/** Widget was destroyed.
* @param {EventData} ctx
*/
treeDestroy: function(ctx) {
this.$div.find(">ul.fancytree-container").remove();
this.$source && this.$source.removeClass("ui-helper-hidden");
},
/** Widget was (re-)initialized.
* @param {EventData} ctx
*/
treeInit: function(ctx) {
//this.debug("Fancytree.treeInit()");
this.treeLoad(ctx);
},
/** Parse Fancytree from source, as configured in the options.
* @param {EventData} ctx
* @param {object} [source] optional new source (use last data otherwise)
*/
treeLoad: function(ctx, source) {
var type, $ul,
tree = ctx.tree,
$container = ctx.widget.element,
dfd,
// calling context for root node
rootCtx = $.extend({}, ctx, {node: this.rootNode});
if(tree.rootNode.children){
this.treeClear(ctx);
}
source = source || this.options.source;
if(!source){
type = $container.data("type") || "html";
switch(type){
case "html":
$ul = $container.find(">ul:first");
$ul.addClass("ui-fancytree-source ui-helper-hidden");
source = $.ui.fancytree.parseHtml($ul);
// allow to init tree.data.foo from <ul data-foo=''>
this.data = $.extend(this.data, _getElementDataAsDict($ul));
break;
case "json":
// $().addClass("ui-helper-hidden");
source = $.parseJSON($container.text());
if(source.children){
if(source.title){tree.title = source.title;}
source = source.children;
}
break;
default:
$.error("Invalid data-type: " + type);
}
}else if(typeof source === "string"){
// TODO: source is an element ID
$.error("Not implemented");
}
// $container.addClass("ui-widget ui-widget-content ui-corner-all");
// Trigger fancytreeinit after nodes have been loaded
dfd = this.nodeLoadChildren(rootCtx, source).done(function(){
tree.render();
if( ctx.options.selectMode === 3 ){
tree.rootNode.fixSelection3FromEndNodes();
}
tree._triggerTreeEvent("init", null, { status: true });
}).fail(function(){
tree.render();
tree._triggerTreeEvent("init", null, { status: false });
});
return dfd;
},
/** Node was inserted into or removed from the tree.
* @param {EventData} ctx
* @param {boolean} add
* @param {FancytreeNode} node
*/
treeRegisterNode: function(ctx, add, node) {
},
/** Widget got focus.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
treeSetFocus: function(ctx, flag, callOpts) {
flag = (flag !== false);
// this.debug("treeSetFocus(" + flag + "), callOpts: " + callOpts);
// this.debug(" focusNode: " + this.focusNode);
// this.debug(" activeNode: " + this.activeNode);
if( flag !== this.hasFocus() ){
this._hasFocus = flag;
if( !flag && this.focusNode ) {
// Node also looses focus if widget blurs
this.focusNode.setFocus(false);
}
this.$container.toggleClass("fancytree-treefocus", flag);
this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
}
}
});
/* ******************************************************************************
* jQuery UI widget boilerplate
*/
/**
* The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br>
* This constructor is not called directly. Use `$(selector).fancytree({})`
* to initialize the plugin instead.<br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members:
* var tree = $("#tree").fancytree("getTree");
* var node = $("#tree").fancytree("getActiveNode", "1234");
* </pre>
*
* @mixin Fancytree_Widget
*/
$.widget("ui.fancytree",
/** @lends Fancytree_Widget# */
{
/**These options will be used as defaults
* @type {FancytreeOptions}
*/
options:
{
activeVisible: true,
ajax: {
type: "GET",
cache: false, // false: Append random '_' argument to the request url to prevent caching.
// timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
dataType: "json" // Expect json format and pass json object to callbacks.
}, //
aria: false, // TODO: default to true
autoActivate: true,
autoCollapse: false,
// autoFocus: false,
autoScroll: false,
checkbox: false,
/**defines click behavior*/
clickFolderMode: 4,
debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo)
disabled: false, // TODO: required anymore?
enableAspx: true, // TODO: document
extensions: [],
// fx: { height: "toggle", duration: 200 },
// toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 },
// toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 },
toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 },
generateIds: false,
icons: true,
idPrefix: "ft_",
focusOnSelect: false,
keyboard: true,
keyPathSeparator: "/",
minExpandLevel: 1,
quicksearch: false,
scrollOfs: {top: 0, bottom: 0},
scrollParent: null,
selectMode: 2,
strings: {
loading: "Loading…",
loadError: "Load error!"
},
tabbable: true,
titlesTabbable: false,
_classNames: {
node: "fancytree-node",
folder: "fancytree-folder",
combinedExpanderPrefix: "fancytree-exp-",
combinedIconPrefix: "fancytree-ico-",
hasChildren: "fancytree-has-children",
active: "fancytree-active",
selected: "fancytree-selected",
expanded: "fancytree-expanded",
lazy: "fancytree-lazy",
focused: "fancytree-focused",
partsel: "fancytree-partsel",
unselectable: "fancytree-unselectable",
lastsib: "fancytree-lastsib",
loading: "fancytree-loading",
error: "fancytree-error"
},
// events
lazyLoad: null,
postProcess: null
},
/* Set up the widget, Called on first $().fancytree() */
_create: function() {
this.tree = new Fancytree(this);
this.$source = this.source || this.element.data("type") === "json" ? this.element
: this.element.find(">ul:first");
// Subclass Fancytree instance with all enabled extensions
var extension, extName, i,
extensions = this.options.extensions,
base = this.tree;
for(i=0; i<extensions.length; i++){
extName = extensions[i];
extension = $.ui.fancytree._extensions[extName];
if(!extension){
$.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)");
}
// Add extension options as tree.options.EXTENSION
// _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName);
this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
// Add a namespace tree.ext.EXTENSION, to hold instance data
_assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'");
// this.tree[extName] = extension;
this.tree.ext[extName] = {};
// Subclass Fancytree methods using proxies.
_subclassObject(this.tree, base, extension, extName);
// current extension becomes base for the next extension
base = extension;
}
//
this.tree._callHook("treeCreate", this.tree);
// Note: 'fancytreecreate' event is fired by widget base class
// this.tree._triggerTreeEvent("create");
},
/* Called on every $().fancytree() */
_init: function() {
this.tree._callHook("treeInit", this.tree);
// TODO: currently we call bind after treeInit, because treeInit
// might change tree.$container.
// It would be better, to move ebent binding into hooks altogether
this._bind();
},
/* Use the _setOption method to respond to changes to options */
_setOption: function(key, value) {
var callDefault = true,
rerender = false;
switch( key ) {
case "aria":
case "checkbox":
case "icons":
case "minExpandLevel":
case "tabbable":
// case "nolink":
this.tree._callHook("treeCreate", this.tree);
rerender = true;
break;
case "source":
callDefault = false;
this.tree._callHook("treeLoad", this.tree, value);
break;
}
this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">");
if(callDefault){
// In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
$.Widget.prototype._setOption.apply(this, arguments);
// TODO: In jQuery UI 1.9 and above, you use the _super method instead
// this._super( "_setOption", key, value );
}
if(rerender){
this.tree.render(true, false); // force, not-deep
}
},
/** Use the destroy method to clean up any modifications your widget has made to the DOM */
destroy: function() {
this._unbind();
this.tree._callHook("treeDestroy", this.tree);
// In jQuery UI 1.8, you must invoke the destroy method from the base widget
$.Widget.prototype.destroy.call(this);
// TODO: delete tree and nodes to make garbage collect easier?
// TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
},
// -------------------------------------------------------------------------
/* Remove all event handlers for our namespace */
_unbind: function() {
var ns = this.tree._ns;
this.element.unbind(ns);
this.tree.$container.unbind(ns);
$(document).unbind(ns);
},
/* Add mouse and kyboard handlers to the container */
_bind: function() {
var that = this,
opts = this.options,
tree = this.tree,
ns = tree._ns
// selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" )
;
// Remove all previuous handlers for this tree
this._unbind();
//alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container);
// tree.debug("bind events; container: ", tree.$container);
tree.$container.on("focusin" + ns + " focusout" + ns, function(event){
var node = FT.getNode(event),
flag = (event.type === "focusin");
// tree.debug("Tree container got event " + event.type, node, event);
// tree.treeOnFocusInOut.call(tree, event);
if(node){
// For example clicking into an <input> that is part of a node
tree._callHook("nodeSetFocus", node, flag);
}else{
tree._callHook("treeSetFocus", tree, flag);
}
}).on("selectstart" + ns, "span.fancytree-title", function(event){
// prevent mouse-drags to select text ranges
// tree.debug("<span title> got event " + event.type);
event.preventDefault();
}).on("keydown" + ns, function(event){
// TODO: also bind keyup and keypress
// tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus());
// if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){
if(opts.disabled || opts.keyboard === false ){
return true;
}
var res,
node = tree.focusNode, // node may be null
ctx = tree._makeHookContext(node || tree, event),
prevPhase = tree.phase;
try {
tree.phase = "userEvent";
// If a 'fancytreekeydown' handler returns false, skip the default
// handling (implemented by tree.nodeKeydown()).
if(node){
res = tree._triggerNodeEvent("keydown", node, event);
}else{
res = tree._triggerTreeEvent("keydown", event);
}
if ( res === "preventNav" ){
res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls
} else if ( res !== false ){
res = tree._callHook("nodeKeydown", ctx);
}
return res;
} finally {
tree.phase = prevPhase;
}
}).on("click" + ns + " dblclick" + ns, function(event){
if(opts.disabled){
return true;
}
var ctx,
et = FT.getEventTarget(event),
node = et.node,
tree = that.tree,
prevPhase = tree.phase;
if( !node ){
return true; // Allow bubbling of other events
}
ctx = tree._makeHookContext(node, event);
// that.tree.debug("event(" + event.type + "): node: ", node);
try {
tree.phase = "userEvent";
switch(event.type) {
case "click":
ctx.targetType = et.type;
return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx);
case "dblclick":
ctx.targetType = et.type;
return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx);
}
// } catch(e) {
// // var _ = null; // DT issue 117 // TODO
// $.error(e);
} finally {
tree.phase = prevPhase;
}
});
},
/** Return the active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.tree.activeNode;
},
/** Return the matching node or null.
* @param {string} key
* @returns {FancytreeNode}
*/
getNodeByKey: function(key) {
return this.tree.getNodeByKey(key);
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.tree.rootNode;
},
/** Return the current tree instance.
* @returns {Fancytree}
*/
getTree: function() {
return this.tree;
}
});
// $.ui.fancytree was created by the widget factory. Create a local shortcut:
FT = $.ui.fancytree;
/**
* Static members in the `$.ui.fancytree` namespace.<br>
* <br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access static members:
* var node = $.ui.fancytree.getNode(element);
* alert($.ui.fancytree.version);
* </pre>
*
* @mixin Fancytree_Static
*/
$.extend($.ui.fancytree,
/** @lends Fancytree_Static# */
{
/** @type {string} */
version: "2.10.0", // Set to semver by 'grunt release'
/** @type {string} */
buildType: "production", // Set to 'production' by 'grunt build'
/** @type {int} */
debugLevel: 1, // Set to 1 by 'grunt build'
// Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel
_nextId: 1,
_nextNodeKey: 1,
_extensions: {},
// focusTree: null,
/** Expose class object as $.ui.fancytree._FancytreeClass */
_FancytreeClass: Fancytree,
/** Expose class object as $.ui.fancytree._FancytreeNodeClass */
_FancytreeNodeClass: FancytreeNode,
/* Feature checks to provide backwards compatibility */
jquerySupports: {
// http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
positionMyOfs: isVersionAtLeast($.ui.version, 1, 9)
},
/** Throw an error if condition fails (debug method).
* @param {boolean} cond
* @param {string} msg
*/
assert: function(cond, msg){
return _assert(cond, msg);
},
/** Return a function that executes *fn* at most every *timeout* ms.
* @param {integer} timeout
* @param {function} fn
* @param {boolean} [invokeAsap=false]
* @param {any} [ctx]
*/
debounce: function(timeout, fn, invokeAsap, ctx) {
var timer;
if(arguments.length === 3 && typeof invokeAsap !== "boolean") {
ctx = invokeAsap;
invokeAsap = false;
}
return function() {
var args = arguments;
ctx = ctx || this;
invokeAsap && !timer && fn.apply(ctx, args);
clearTimeout(timer);
timer = setTimeout(function() {
invokeAsap || fn.apply(ctx, args);
timer = null;
}, timeout);
};
},
/** Write message to console if debugLevel >= 2
* @param {string} msg
*/
debug: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments);
},
/** Write error message to console.
* @param {string} msg
*/
error: function(msg){
consoleApply("error", arguments);
},
/** Convert <, >, &, ", ', / to the equivalent entities.
*
* @param {string} s
* @returns {string}
*/
escapeHtml: function(s){
return ("" + s).replace(/[&<>"'\/]/g, function (s) {
return ENTITY_MAP[s];
});
},
/** Make jQuery.position() arguments backwards compatible, i.e. if
* jQuery UI version <= 1.8, convert
* { my: "left+3 center", at: "left bottom", of: $target }
* to
* { my: "left center", at: "left bottom", of: $target, offset: "3 0" }
*
* See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
* and http://jsfiddle.net/mar10/6xtu9a4e/
*/
fixPositionOptions: function(opts) {
if( opts.offset || ("" + opts.my + opts.at ).indexOf("%") >= 0 ) {
$.error("expected new position syntax (but '%' is not supported)");
}
if( ! $.ui.fancytree.jquerySupports.positionMyOfs ) {
var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined]
myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.my),
atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.at),
// convert to numbers
dx = (myParts[2] ? (+myParts[2]) : 0) + (atParts[2] ? (+atParts[2]) : 0),
dy = (myParts[4] ? (+myParts[4]) : 0) + (atParts[4] ? (+atParts[4]) : 0);
opts = $.extend({}, opts, { // make a copy and overwrite
my: myParts[1] + " " + myParts[3],
at: atParts[1] + " " + atParts[3]
});
if( dx || dy ) {
opts.offset = "" + dx + " " + dy;
}
}
return opts;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTargetType: function(event){
return this.getEventTarget(event).type;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {object} Return a {node: FancytreeNode, type: TYPE} object
* TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTarget: function(event){
var tcn = event && event.target ? event.target.className : "",
res = {node: this.getNode(event.target), type: undefined};
// We use a fast version of $(res.node).hasClass()
// See http://jsperf.com/test-for-classname/2
if( /\bfancytree-title\b/.test(tcn) ){
res.type = "title";
}else if( /\bfancytree-expander\b/.test(tcn) ){
res.type = (res.node.hasChildren() === false ? "prefix" : "expander");
}else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){
res.type = "checkbox";
}else if( /\bfancytree-icon\b/.test(tcn) ){
res.type = "icon";
}else if( /\bfancytree-node\b/.test(tcn) ){
// Somewhere near the title
res.type = "title";
}else if( event && event.target && $(event.target).closest(".fancytree-title").length ) {
// #228: clicking an embedded element inside a title
res.type = "title";
}
return res;
},
/** Return a FancytreeNode instance from element.
*
* @param {Element | jQueryObject | Event} el
* @returns {FancytreeNode} matching node or null
*/
getNode: function(el){
if(el instanceof FancytreeNode){
return el; // el already was a FancytreeNode
}else if(el.selector !== undefined){
el = el[0]; // el was a jQuery object: use the DOM element
}else if(el.originalEvent !== undefined){
el = el.target; // el was an Event
}
while( el ) {
if(el.ftnode) {
return el.ftnode;
}
el = el.parentNode;
}
return null;
},
/* Return a Fancytree instance from element.
* TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem
* @param {Element | jQueryObject | Event} el
* @returns {Fancytree} matching tree or null
* /
getTree: function(el){
if(el instanceof Fancytree){
return el; // el already was a Fancytree
}else if(el.selector !== undefined){
el = el[0]; // el was a jQuery object: use the DOM element
}else if(el.originalEvent !== undefined){
el = el.target; // el was an Event
}
...
return null;
},
*/
/** Write message to console if debugLevel >= 1
* @param {string} msg
*/
info: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments);
},
/** Convert a keydown or mouse event to a canonical string like 'ctrl+a', 'ctrl+shift+f2', 'shift+leftdblclick'.
* This is especially handy for switch-statements in event handlers.
* @param {event}
* @returns {string}
*/
eventToString: function(event) {
// Poor-man's hotkeys. See here for a complete implementation:
// https://github.com/jeresig/jquery.hotkeys
var which = event.which,
et = event.type,
s = [];
if( event.altKey ) { s.push("alt"); }
if( event.ctrlKey ) { s.push("ctrl"); }
if( event.metaKey ) { s.push("meta"); }
if( event.shiftKey ) { s.push("shift"); }
if( et === "click" || et === "dblclick" ) {
s.push(MOUSE_BUTTONS[event.button] + et);
} else {
if( !IGNORE_KEYCODES[which] ) {
s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() );
}
}
return s.join("+");
},
/* @deprecated: use eventToString(event) instead.
*/
keyEventToString: function(event) {
this.warn("keyEventToString() is deprecated: use eventToString()");
return this.eventToString(event);
},
/**
* Parse tree data from HTML <ul> markup
*
* @param {jQueryObject} $ul
* @returns {NodeData[]}
*/
parseHtml: function($ul) {
// TODO: understand this:
/*jshint validthis:true */
var extraClasses, i, l, iPos, tmp, tmp2, classes, className,
$children = $ul.find(">li"),
children = [];
$children.each(function() {
var allData,
$li = $(this),
$liSpan = $li.find(">span:first", this),
$liA = $liSpan.length ? null : $li.find(">a:first"),
d = { tooltip: null, data: {} };
if( $liSpan.length ) {
d.title = $liSpan.html();
} else if( $liA && $liA.length ) {
// If a <li><a> tag is specified, use it literally and extract href/target.
d.title = $liA.html();
d.data.href = $liA.attr("href");
d.data.target = $liA.attr("target");
d.tooltip = $liA.attr("title");
} else {
// If only a <li> tag is specified, use the trimmed string up to
// the next child <ul> tag.
d.title = $li.html();
iPos = d.title.search(/<ul/i);
if( iPos >= 0 ){
d.title = d.title.substring(0, iPos);
}
}
d.title = $.trim(d.title);
// Make sure all fields exist
for(i=0, l=CLASS_ATTRS.length; i<l; i++){
d[CLASS_ATTRS[i]] = undefined;
}
// Initialize to `true`, if class is set and collect extraClasses
classes = this.className.split(" ");
extraClasses = [];
for(i=0, l=classes.length; i<l; i++){
className = classes[i];
if(CLASS_ATTR_MAP[className]){
d[className] = true;
}else{
extraClasses.push(className);
}
}
d.extraClasses = extraClasses.join(" ");
// Parse node options from ID, title and class attributes
tmp = $li.attr("title");
if( tmp ){
d.tooltip = tmp; // overrides <a title='...'>
}
tmp = $li.attr("id");
if( tmp ){
d.key = tmp;
}
// Add <li data-NAME='...'> as node.data.NAME
allData = _getElementDataAsDict($li);
if(allData && !$.isEmptyObject(allData)) {
// #56: Allow to set special node.attributes from data-...
for(i=0, l=NODE_ATTRS.length; i<l; i++){
tmp = NODE_ATTRS[i];
tmp2 = allData[tmp];
if( tmp2 != null ) {
delete allData[tmp];
d[tmp] = tmp2;
}
}
// All other data-... goes to node.data...
$.extend(d.data, allData);
}
// Recursive reading of child nodes, if LI tag contains an UL tag
$ul = $li.find(">ul:first");
if( $ul.length ) {
d.children = $.ui.fancytree.parseHtml($ul);
}else{
d.children = d.lazy ? undefined : null;
}
children.push(d);
// FT.debug("parse ", d, children);
});
return children;
},
/** Add Fancytree extension definition to the list of globally available extensions.
*
* @param {object} definition
*/
registerExtension: function(definition){
_assert(definition.name != null, "extensions must have a `name` property.");
_assert(definition.version != null, "extensions must have a `version` property.");
$.ui.fancytree._extensions[definition.name] = definition;
},
/** Inverse of escapeHtml().
*
* @param {string} s
* @returns {string}
*/
unescapeHtml: function(s){
var e = document.createElement("div");
e.innerHTML = s;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
},
/** Write warning message to console.
* @param {string} msg
*/
warn: function(msg){
consoleApply("warn", arguments);
}
});
}(jQuery, window, document));
// Extending Fancytree
// ===================
//
// See also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code.
//
// Every extension should have a comment header containing some information
// about the author, copyright and licensing. Also a pointer to the latest
// source code.
// Prefix with `/*!` so the comment is not removed by the minifier.
/*!
* jquery.fancytree.childcounter.js
*
* Add a child counter bubble to tree nodes.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
// To keep the global namespace clean, we wrap everything in a closure
;(function($, undefined) {
// Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)
"use strict";
// The [coding guidelines](http://contribute.jquery.org/style-guide/js/)
// require jshint compliance.
// But for this sample, we want to allow unused variables for demonstration purpose.
/*jshint unused:false */
// Adding methods
// --------------
// New member functions can be added to the `Fancytree` class.
// This function will be available for every tree instance.
//
// var tree = $("#tree").fancytree("getTree");
// tree.countSelected(false);
$.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly){
var tree = this,
treeOptions = tree.options;
return tree.getSelectedNodes(topOnly).length;
};
// The `FancytreeNode` class can also be easily extended. This would be called
// like
//
// node.toUpper();
$.ui.fancytree._FancytreeNodeClass.prototype.toUpper = function(){
var node = this;
return node.setTitle(node.title.toUpperCase());
};
// Finally, we can extend the widget API and create functions that are called
// like so:
//
// $("#tree").fancytree("widgetMethod1", "abc");
$.ui.fancytree.prototype.widgetMethod1 = function(arg1){
var tree = this.tree;
return arg1;
};
// Register a Fancytree extension
// ------------------------------
// A full blown extension, extension is available for all trees and can be
// enabled like so (see also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html)):
//
// <script src="../src/jquery.fancytree.js" type="text/javascript"></script>
// <script src="../src/jquery.fancytree.childcounter.js" type="text/javascript"></script>
// ...
//
// $("#tree").fancytree({
// extensions: ["childcounter"],
// childcounter: {
// hideExpanded: true
// },
// ...
// });
//
/* 'childcounter' extension */
$.ui.fancytree.registerExtension({
// Every extension must be registered by a unique name.
name: "childcounter",
// Version information should be compliant with [semver](http://semver.org)
version: "1.0.0",
// Extension specific options and their defaults.
// This options will be available as `tree.options.childcounter.hideExpanded`
options: {
deep: true,
hideZeros: true,
hideExpanded: false
},
// Attributes other than `options` (or functions) can be defined here, and
// will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`.
// They can also be accessed as `this._local.foo` from within the extension
// methods.
foo: 42,
// Local functions are prefixed with an underscore '_'.
// Callable as `this._local._appendCounter()`.
_appendCounter: function(bar){
var tree = this;
},
// **Override virtual methods for this extension.**
//
// Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'.
// with a `ctx` argument (see [EventData](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/global.html#EventData)
// for details) and an extended calling context:<br>
// `this` : the Fancytree instance<br>
// `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br>
// `this._super`: the virtual function that was overridden (member of previous extension or Fancytree)
//
// See also the [complete list of available hook functions](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html).
/* Init */
// `treeInit` is triggered when a tree is initalized. We can set up classes or
// bind event handlers here...
treeInit: function(ctx){
var tree = this, // same as ctx.tree,
opts = ctx.options,
extOpts = ctx.options.childcounter;
// Optionally check for dependencies with other extensions
/* this._requireExtension("glyph", false, false); */
// Call the base implementation
this._superApply(arguments);
// Add a class to the tree container
this.$container.addClass("fancytree-ext-childcounter");
},
// Destroy this tree instance (we only call the default implementation, so
// this method could as well be omitted).
treeDestroy: function(ctx){
this._superApply(arguments);
},
// Overload the `renderTitle` hook, to append a counter badge
nodeRenderTitle: function(ctx, title) {
var node = ctx.node,
extOpts = ctx.options.childcounter,
count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter;
// Let the base implementation render the title
this._superApply(arguments);
// Append a counter badge
if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){
$("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count));
}
},
// Overload the `setExpanded` hook, so the counters are updated
nodeSetExpanded: function(ctx, flag, opts) {
var tree = ctx.tree,
node = ctx.node;
// Let the base implementation expand/collapse the node, then redraw the title
// after the animation has finished
return this._superApply(arguments).always(function(){
tree.nodeRenderTitle(ctx);
});
}
// End of extension definition
});
// End of namespace closure
}(jQuery));
/*!
*
* jquery.fancytree.clones.js
* Support faster lookup of nodes by key and shared ref-ids.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
// TODO: see qunit.js extractStacktrace()
if(!cond){
msg = msg ? ": " + msg : "";
$.error("Assertion failed" + msg);
}
}
/* Return first occurrence of member from array. */
function _removeArrayMember(arr, elem) {
// TODO: use Array.indexOf for IE >= 9
var i;
for (i = arr.length - 1; i >= 0; i--) {
if (arr[i] === elem) {
arr.splice(i, 1);
return true;
}
}
return false;
}
// /**
// * Calculate a 32 bit FNV-1a hash
// * Found here: https://gist.github.com/vaiorabbit/5657561
// * Ref.: http://isthe.com/chongo/tech/comp/fnv/
// *
// * @param {string} str the input value
// * @param {boolean} [asString=false] set to true to return the hash value as
// * 8-digit hex string instead of an integer
// * @param {integer} [seed] optionally pass the hash of the previous chunk
// * @returns {integer | string}
// */
// function hashFnv32a(str, asString, seed) {
// /*jshint bitwise:false */
// var i, l,
// hval = (seed === undefined) ? 0x811c9dc5 : seed;
// for (i = 0, l = str.length; i < l; i++) {
// hval ^= str.charCodeAt(i);
// hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
// }
// if( asString ){
// // Convert to 8 digit hex string
// return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
// }
// return hval >>> 0;
// }
/**
* JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
*
* @author <a href="mailto:[email protected]">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:[email protected]">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} key ASCII only
* @param {boolean} [asString=false]
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function hashMurmur3(key, asString, seed) {
/*jshint bitwise:false */
var h1b, k1,
remainder = key.length & 3,
bytes = key.length - remainder,
h1 = seed,
c1 = 0xcc9e2d51,
c2 = 0x1b873593,
i = 0;
while (i < bytes) {
k1 =
((key.charCodeAt(i) & 0xff)) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
}
k1 = 0;
switch (remainder) {
/*jshint -W086:true */
case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1: k1 ^= (key.charCodeAt(i) & 0xff);
k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
h1 ^= h1 >>> 16;
if( asString ){
// Convert to 8 digit hex string
return ("0000000" + (h1 >>> 0).toString(16)).substr(-8);
}
return h1 >>> 0;
}
// console.info(hashMurmur3("costarring"));
// console.info(hashMurmur3("costarring", true));
// console.info(hashMurmur3("liquid"));
// console.info(hashMurmur3("liquid", true));
/*
* Return a unique key for node by calculationg the hash of the parents refKey-list
*/
function calcUniqueKey(node) {
var key,
path = $.map(node.getParentList(false, true), function(e){ return e.refKey || e.key; });
path = path.join("/");
key = "id_" + hashMurmur3(path, true);
// node.debug(path + " -> " + key);
return key;
}
/**
* [ext-clones] Return a list of clone-nodes or null.
* @param {boolean} [includeSelf=false]
* @returns {FancytreeNode[] | null}
*
* @alias FancytreeNode#getCloneList
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function(includeSelf){
var key,
tree = this.tree,
refList = tree.refMap[this.refKey] || null,
keyMap = tree.keyMap;
if( refList ) {
key = this.key;
// Convert key list to node list
if( includeSelf ) {
refList = $.map(refList, function(val){ return keyMap[val]; });
} else {
refList = $.map(refList, function(val){ return val === key ? null : keyMap[val]; });
if( refList.length < 1 ) {
refList = null;
}
}
}
return refList;
};
/**
* [ext-clones] Return true if this node has at least another clone with same refKey.
* @returns {boolean}
*
* @alias FancytreeNode#isClone
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isClone = function(){
var refKey = this.refKey || null,
refList = refKey && this.tree.refMap[refKey] || null;
return !!(refList && refList.length > 1);
};
/**
* [ext-clones] Update key and/or refKey for an existing node.
* @param {string} key
* @param {string} refKey
* @returns {boolean}
*
* @alias FancytreeNode#reRegister
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function(key, refKey){
key = (key == null) ? null : "" + key;
refKey = (refKey == null) ? null : "" + refKey;
// this.debug("reRegister", key, refKey);
var tree = this.tree,
prevKey = this.key,
prevRefKey = this.refKey,
keyMap = tree.keyMap,
refMap = tree.refMap,
refList = refMap[prevRefKey] || null,
// curCloneKeys = refList ? node.getCloneList(true),
modified = false;
// Key has changed: update all references
if( key != null && key !== this.key ) {
if( keyMap[key] ) {
$.error("[ext-clones] reRegister(" + key + "): already exists: " + this);
}
// Update keyMap
delete keyMap[prevKey];
keyMap[key] = this;
// Update refMap
if( refList ) {
refMap[prevRefKey] = $.map(refList, function(e){
return e === prevKey ? key : e;
});
}
this.key = key;
modified = true;
}
// refKey has changed
if( refKey != null && refKey !== this.refKey ) {
// Remove previous refKeys
if( refList ){
if( refList.length === 1 ){
delete refMap[prevRefKey];
}else{
refMap[prevRefKey] = $.map(refList, function(e){
return e === prevKey ? null : e;
});
}
}
// Add refKey
if( refMap[refKey] ) {
refMap[refKey].append(key);
}else{
refMap[refKey] = [ this.key ];
}
this.refKey = refKey;
modified = true;
}
return modified;
};
/**
* [ext-clones] Return all nodes with a given refKey (null if not found).
* @param {string} refKey
* @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node
* @returns {FancytreeNode[] | null}
* @alias Fancytree#getNodesByRef
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function(refKey, rootNode){
var keyMap = this.keyMap,
refList = this.refMap[refKey] || null;
if( refList ) {
// Convert key list to node list
if( rootNode ) {
refList = $.map(refList, function(val){
var node = keyMap[val];
return node.isDescendantOf(rootNode) ? node : null;
});
}else{
refList = $.map(refList, function(val){ return keyMap[val]; });
}
if( refList.length < 1 ) {
refList = null;
}
}
return refList;
};
/**
* [ext-clones] Replace a refKey with a new one.
* @param {string} oldRefKey
* @param {string} newRefKey
* @alias Fancytree#changeRefKey
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeClass.prototype.changeRefKey = function(oldRefKey, newRefKey) {
var i, node,
keyMap = this.keyMap,
refList = this.refMap[oldRefKey] || null;
if (refList) {
for (i = 0; i < refList.length; i++) {
node = keyMap[refList[i]];
node.refKey = newRefKey;
}
delete this.refMap[oldRefKey];
this.refMap[newRefKey] = refList;
}
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "clones",
version: "0.0.3",
// Default options for this extension.
options: {
highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers
highlightClones: false // set 'fancytree-clone' class on any node that has at least one clone
},
treeCreate: function(ctx){
this._superApply(arguments);
ctx.tree.refMap = {};
ctx.tree.keyMap = {};
},
treeInit: function(ctx){
this.$container.addClass("fancytree-ext-clones");
_assert(ctx.options.defaultKey == null);
// Generate unique / reproducible default keys
ctx.options.defaultKey = function(node){
return calcUniqueKey(node);
};
// The default implementation loads initial data
this._superApply(arguments);
},
treeClear: function(ctx){
ctx.tree.refMap = {};
ctx.tree.keyMap = {};
return this._superApply(arguments);
},
treeRegisterNode: function(ctx, add, node) {
var refList, len,
tree = ctx.tree,
keyMap = tree.keyMap,
refMap = tree.refMap,
key = node.key,
refKey = (node && node.refKey != null) ? "" + node.refKey : null;
// ctx.tree.debug("clones.treeRegisterNode", add, node);
if( key === "_statusNode" ){
return this._superApply(arguments);
}
if( add ) {
if( keyMap[node.key] != null ) {
$.error("clones.treeRegisterNode: node.key already exists: " + node);
}
keyMap[key] = node;
if( refKey ) {
refList = refMap[refKey];
if( refList ) {
refList.push(key);
if( refList.length === 2 && ctx.options.clones.highlightClones ) {
// Mark peer node, if it just became a clone (no need to
// mark current node, since it will be rendered later anyway)
keyMap[refList[0]].renderStatus();
}
} else {
refMap[refKey] = [key];
}
// node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]);
}
}else {
if( keyMap[key] == null ) {
$.error("clones.treeRegisterNode: node.key not registered: " + node.key);
}
delete keyMap[key];
if( refKey ) {
refList = refMap[refKey];
// node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]);
if( refList ) {
len = refList.length;
if( len <= 1 ){
_assert(len === 1);
_assert(refList[0] === key);
delete refMap[refKey];
}else{
_removeArrayMember(refList, key);
// Unmark peer node, if this was the only clone
if( len === 2 && ctx.options.clones.highlightClones ) {
// node.debug("clones.treeRegisterNode: last =>", node.getCloneList());
keyMap[refList[0]].renderStatus();
}
}
// node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]);
}
}
}
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
var $span, res,
node = ctx.node;
res = this._superApply(arguments);
if( ctx.options.clones.highlightClones ) {
$span = $(node[ctx.tree.statusClassPropName]);
// Only if span already exists
if( $span.length && node.isClone() ){
// node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones);
$span.addClass("fancytree-clone");
}
}
return res;
},
nodeSetActive: function(ctx, flag) {
var res,
scpn = ctx.tree.statusClassPropName,
node = ctx.node;
res = this._superApply(arguments);
if( ctx.options.clones.highlightActiveClones && node.isClone() ) {
$.each(node.getCloneList(true), function(idx, n){
// n.debug("clones.nodeSetActive: ", flag !== false);
$(n[scpn]).toggleClass("fancytree-active-clone", flag !== false);
});
}
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.dnd.js
*
* Drag-and-drop support.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
var didRegisterDnd = false;
/* Convert number to string and prepend +/-; return empty string for 0.*/
function offsetString(n){
return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n));
}
/* *****************************************************************************
* Drag and drop support
*/
function _initDragAndDrop(tree) {
var dnd = tree.options.dnd || null;
// Register 'connectToFancytree' option with ui.draggable
if( dnd ) {
_registerDnd();
}
// Attach ui.draggable to this Fancytree instance
if(dnd && dnd.dragStart ) {
tree.widget.element.draggable($.extend({
addClasses: false,
// DT issue 244: helper should be child of scrollParent:
appendTo: tree.$container,
// appendTo: "body",
containment: false,
delay: 0,
distance: 4,
revert: false,
scroll: true, // to disable, also set css 'position: inherit' on ul.fancytree-container
scrollSpeed: 7,
scrollSensitivity: 10,
// Delegate draggable.start, drag, and stop events to our handler
connectToFancytree: true,
// Let source tree create the helper element
helper: function(event) {
var $helper, $nodeTag,
sourceNode = $.ui.fancytree.getNode(event.target);
if(!sourceNode){
// #405, DT issue 211: might happen, if dragging a table *header*
return "<div>ERROR?: helper requested but sourceNode not found</div>";
}
$nodeTag = $(sourceNode.span);
// Only event and node argument is available
$helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>")
.css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar
.append($nodeTag.find("span.fancytree-title").clone());
// Attach node reference to helper object
$helper.data("ftSourceNode", sourceNode);
// we return an unconnected element, so `draggable` will add this
// to the parent specified as `appendTo` option
return $helper;
},
start: function(event, ui) {
var sourceNode = ui.helper.data("ftSourceNode");
return !!sourceNode; // Abort dragging if no node could be found
}
}, tree.options.dnd.draggable));
}
// Attach ui.droppable to this Fancytree instance
if(dnd && dnd.dragDrop) {
tree.widget.element.droppable($.extend({
addClasses: false,
tolerance: "intersect",
greedy: false
/*
activate: function(event, ui) {
tree.debug("droppable - activate", event, ui, this);
},
create: function(event, ui) {
tree.debug("droppable - create", event, ui);
},
deactivate: function(event, ui) {
tree.debug("droppable - deactivate", event, ui);
},
drop: function(event, ui) {
tree.debug("droppable - drop", event, ui);
},
out: function(event, ui) {
tree.debug("droppable - out", event, ui);
},
over: function(event, ui) {
tree.debug("droppable - over", event, ui);
}
*/
}, tree.options.dnd.droppable));
}
}
//--- Extend ui.draggable event handling --------------------------------------
function _registerDnd() {
if(didRegisterDnd){
return;
}
// Register proxy-functions for draggable.start/drag/stop
$.ui.plugin.add("draggable", "connectToFancytree", {
start: function(event, ui) {
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null;
if(sourceNode) {
// Adjust helper offset, so cursor is slightly outside top/left corner
draggable.offset.click.top = -2;
draggable.offset.click.left = + 16;
// Trigger dragStart event
// TODO: when called as connectTo..., the return value is ignored(?)
return sourceNode.tree.ext.dnd._onDragEvent("start", sourceNode, null, event, ui, draggable);
}
},
drag: function(event, ui) {
var isHelper, logObject,
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null,
prevTargetNode = ui.helper.data("ftTargetNode") || null,
targetNode = $.ui.fancytree.getNode(event.target);
if(event.target && !targetNode){
// We got a drag event, but the targetNode could not be found
// at the event location. This may happen,
// 1. if the mouse jumped over the drag helper,
// 2. or if a non-fancytree element is dragged
// We ignore it:
isHelper = $(event.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length > 0;
if(isHelper){
logObject = sourceNode || prevTargetNode || $.ui.fancytree;
logObject.debug("Drag event over helper: ignored.");
return;
}
}
ui.helper.data("ftTargetNode", targetNode);
// Leaving a tree node
if(prevTargetNode && prevTargetNode !== targetNode ) {
prevTargetNode.tree.ext.dnd._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
}
if(targetNode){
if(!targetNode.tree.options.dnd.dragDrop) {
// not enabled as drop target
} else if(targetNode === prevTargetNode) {
// Moving over same node
targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
}else{
// Entering this node first time
targetNode.tree.ext.dnd._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
}
}
// else go ahead with standard event handling
},
stop: function(event, ui) {
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
var logObject,
draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null,
targetNode = ui.helper.data("ftTargetNode") || null,
// mouseDownEvent = draggable._mouseDownEvent,
eventType = event.type,
dropped = (eventType === "mouseup" && event.which === 1);
if(!dropped){
logObject = sourceNode || targetNode || $.ui.fancytree;
logObject.debug("Drag was cancelled");
}
if(targetNode) {
if(dropped){
targetNode.tree.ext.dnd._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
}
targetNode.tree.ext.dnd._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
}
if(sourceNode){
sourceNode.tree.ext.dnd._onDragEvent("stop", sourceNode, null, event, ui, draggable);
}
}
});
didRegisterDnd = true;
}
/* *****************************************************************************
*
*/
$.ui.fancytree.registerExtension({
name: "dnd",
version: "0.1.0",
// Default options for this extension.
options: {
// Make tree nodes accept draggables
autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
draggable: null, // Additional options passed to jQuery draggable
droppable: null, // Additional options passed to jQuery droppable
focusOnClick: false, // Focus, although draggable cancels mousedown event (#270)
// helper: null, // Callback
// helperParent: null, // jQuery object (defaults to Fancytree container)
preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
// Events (drag support)
dragStart: null, // Callback(sourceNode, data), return true, to enable dnd
dragStop: null, // Callback(sourceNode, data)
// Events (drop support)
dragEnter: null, // Callback(targetNode, data)
dragOver: null, // Callback(targetNode, data)
dragDrop: null, // Callback(targetNode, data)
dragLeave: null // Callback(targetNode, data)
},
treeInit: function(ctx){
var tree = ctx.tree;
this._superApply(arguments);
// issue #270: draggable eats mousedown events
if( tree.options.dnd.dragStart ){
tree.$container.on("mousedown", function(event){
// if( !tree.hasFocus() && ctx.options.dnd.focusOnClick ) {
if( ctx.options.dnd.focusOnClick ) { // #270
var node = $.ui.fancytree.getNode(event);
if (node){
node.debug("Re-enable focus that was prevented by jQuery UI draggable.");
// node.setFocus();
// $(node.span).closest(":tabbable").focus();
// $(event.target).trigger("focus");
// $(event.target).closest(":tabbable").trigger("focus");
}
setTimeout(function() { // #300
$(event.target).closest(":tabbable").focus();
}, 10);
}
});
}
_initDragAndDrop(tree);
},
/* Override key handler in order to cancel dnd on escape.*/
nodeKeydown: function(ctx) {
var event = ctx.originalEvent;
if( event.which === $.ui.keyCode.ESCAPE) {
this._local._cancelDrag();
}
return this._superApply(arguments);
},
nodeClick: function(ctx) {
// if( ctx.options.dnd.dragStart ){
// ctx.tree.$container.focus();
// }
return this._superApply(arguments);
},
/* Display drop marker according to hitMode ('after', 'before', 'over', 'out', 'start', 'stop'). */
_setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) {
var markerOffsetX = 0,
markerAt = "center",
instData = this._local,
$source = sourceNode ? $(sourceNode.span) : null,
$target = $(targetNode.span);
if( !instData.$dropMarker ) {
instData.$dropMarker = $("<div id='fancytree-drop-marker'></div>")
.hide()
.css({"z-index": 1000})
.prependTo($(this.$div).parent());
// .prependTo("body");
}
// this.$dropMarker.attr("class", hitMode);
if(hitMode === "after" || hitMode === "before" || hitMode === "over"){
// $source && $source.addClass("fancytree-drag-source");
// $target.addClass("fancytree-drop-target");
switch(hitMode){
case "before":
instData
.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-over")
.addClass("fancytree-drop-before");
markerAt = "top";
break;
case "after":
instData.$dropMarker.removeClass("fancytree-drop-before fancytree-drop-over")
.addClass("fancytree-drop-after");
markerAt = "bottom";
break;
default:
instData.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-before")
.addClass("fancytree-drop-over");
$target.addClass("fancytree-drop-target");
markerOffsetX = 8;
}
instData.$dropMarker
.show()
.position($.ui.fancytree.fixPositionOptions({
my: "left" + offsetString(markerOffsetX) + " center",
at: "left " + markerAt,
of: $target
}));
// helper.addClass("fancytree-drop-hover");
} else {
// $source && $source.removeClass("fancytree-drag-source");
$target.removeClass("fancytree-drop-target");
instData.$dropMarker.hide();
// helper.removeClass("fancytree-drop-hover");
}
if(hitMode === "after"){
$target.addClass("fancytree-drop-after");
} else {
$target.removeClass("fancytree-drop-after");
}
if(hitMode === "before"){
$target.addClass("fancytree-drop-before");
} else {
$target.removeClass("fancytree-drop-before");
}
if(accept === true){
if($source){
$source.addClass("fancytree-drop-accept");
}
$target.addClass("fancytree-drop-accept");
helper.addClass("fancytree-drop-accept");
}else{
if($source){
$source.removeClass("fancytree-drop-accept");
}
$target.removeClass("fancytree-drop-accept");
helper.removeClass("fancytree-drop-accept");
}
if(accept === false){
if($source){
$source.addClass("fancytree-drop-reject");
}
$target.addClass("fancytree-drop-reject");
helper.addClass("fancytree-drop-reject");
}else{
if($source){
$source.removeClass("fancytree-drop-reject");
}
$target.removeClass("fancytree-drop-reject");
helper.removeClass("fancytree-drop-reject");
}
},
/*
* Handles drag'n'drop functionality.
*
* A standard jQuery drag-and-drop process may generate these calls:
*
* draggable helper():
* _onDragEvent("helper", sourceNode, null, event, null, null);
* start:
* _onDragEvent("start", sourceNode, null, event, ui, draggable);
* drag:
* _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
* _onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
* stop:
* _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("stop", sourceNode, null, event, ui, draggable);
*/
_onDragEvent: function(eventName, node, otherNode, event, ui, draggable) {
if(eventName !== "over"){
this.debug("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this);
}
var /*$helper, $helperParent,*/ nodeOfs, relPos, relPos2,
enterResponse, hitMode, r,
opts = this.options,
dnd = opts.dnd,
ctx = this._makeHookContext(node, event, {otherNode: otherNode, ui: ui, draggable: draggable}),
res = null,
$nodeTag = $(node.span);
switch (eventName) {
// case "helper":
// // Only event and node argument is available
// $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>")
// .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar
// .append($nodeTag.find("span.fancytree-title").clone());
// // #345: helper parent is now set using draggable.appendTo
// // $helperParent = dnd.helperParent || $("ul.fancytree-container", node.tree.$div);
// // DT issue 244: helper should be child of scrollParent
// // $helperParent.append($helper);
// // Attach node reference to helper object
// $helper.data("ftSourceNode", node);
// // this.debug("helper=%o", $helper);
// // this.debug("helper.sourceNode=%o", $helper.data("ftSourceNode"));
// res = $helper;
// break;
case "start":
if( node.isStatusNode() ) {
res = false;
} else if(dnd.dragStart) {
res = dnd.dragStart(node, ctx);
}
if(res === false) {
this.debug("tree.dragStart() cancelled");
//draggable._clear();
// NOTE: the return value seems to be ignored (drag is not canceled, when false is returned)
// TODO: call this._cancelDrag()?
ui.helper.trigger("mouseup")
.hide();
} else {
$nodeTag.addClass("fancytree-drag-source");
}
break;
case "enter":
if(dnd.preventRecursiveMoves && node.isDescendantOf(otherNode)){
r = false;
}else{
r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null;
}
if(!r){
// convert null, undefined, false to false
res = false;
}else if ( $.isArray(r) ) {
// TODO: also accept passing an object of this format directly
res = {
over: ($.inArray("over", r) >= 0),
before: ($.inArray("before", r) >= 0),
after: ($.inArray("after", r) >= 0)
};
}else{
res = {
over: ((r === true) || (r === "over")),
before: ((r === true) || (r === "before")),
after: ((r === true) || (r === "after"))
};
}
ui.helper.data("enterResponse", res);
this.debug("helper.enterResponse: %o", res);
break;
case "over":
enterResponse = ui.helper.data("enterResponse");
hitMode = null;
if(enterResponse === false){
// Don't call dragOver if onEnter returned false.
// break;
} else if(typeof enterResponse === "string") {
// Use hitMode from onEnter if provided.
hitMode = enterResponse;
} else {
// Calculate hitMode from relative cursor position.
nodeOfs = $nodeTag.offset();
relPos = { x: event.pageX - nodeOfs.left,
y: event.pageY - nodeOfs.top };
relPos2 = { x: relPos.x / $nodeTag.width(),
y: relPos.y / $nodeTag.height() };
if( enterResponse.after && relPos2.y > 0.75 ){
hitMode = "after";
} else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){
hitMode = "after";
} else if(enterResponse.before && relPos2.y <= 0.25) {
hitMode = "before";
} else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) {
hitMode = "before";
} else if(enterResponse.over) {
hitMode = "over";
}
// Prevent no-ops like 'before source node'
// TODO: these are no-ops when moving nodes, but not in copy mode
if( dnd.preventVoidMoves ){
if(node === otherNode){
this.debug(" drop over source node prevented");
hitMode = null;
}else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){
this.debug(" drop after source node prevented");
hitMode = null;
}else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){
this.debug(" drop before source node prevented");
hitMode = null;
}else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){
this.debug(" drop last child over own parent prevented");
hitMode = null;
}
}
// this.debug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling());
ui.helper.data("hitMode", hitMode);
}
// Auto-expand node (only when 'over' the node, not 'before', or 'after')
if(hitMode === "over" && dnd.autoExpandMS && node.hasChildren() !== false && !node.expanded) {
node.scheduleAction("expand", dnd.autoExpandMS);
}
if(hitMode && dnd.dragOver){
// TODO: http://code.google.com/p/dynatree/source/detail?r=625
ctx.hitMode = hitMode;
res = dnd.dragOver(node, ctx);
}
// DT issue 332
// this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false);
this._local._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false && hitMode !== null);
break;
case "drop":
hitMode = ui.helper.data("hitMode");
if(hitMode && dnd.dragDrop){
ctx.hitMode = hitMode;
dnd.dragDrop(node, ctx);
}
break;
case "leave":
// Cancel pending expand request
node.scheduleAction("cancel");
ui.helper.data("enterResponse", null);
ui.helper.data("hitMode", null);
this._local._setDndStatus(otherNode, node, ui.helper, "out", undefined);
if(dnd.dragLeave){
dnd.dragLeave(node, ctx);
}
break;
case "stop":
$nodeTag.removeClass("fancytree-drag-source");
if(dnd.dragStop){
dnd.dragStop(node, ctx);
}
break;
default:
$.error("Unsupported drag event: " + eventName);
}
return res;
},
_cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if(dd){
dd.cancel();
}
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.edit.js
*
* Make node titles editable.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
var isMac = /Mac/.test(navigator.platform),
escapeHtml = $.ui.fancytree.escapeHtml,
unescapeHtml = $.ui.fancytree.unescapeHtml;
/**
* [ext-edit] Start inline editing of current node title.
*
* @alias FancytreeNode#editStart
* @requires Fancytree
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){
var $input,
node = this,
tree = this.tree,
local = tree.ext.edit,
instOpts = tree.options.edit,
$title = $(".fancytree-title", node.span),
eventData = {
node: node,
tree: tree,
options: tree.options,
isNew: $(node.span).hasClass("fancytree-edit-new"),
orgTitle: node.title,
input: null,
dirty: false
};
// beforeEdit may want to modify the title before editing
if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false ) {
return false;
}
$.ui.fancytree.assert(!local.currentNode, "recursive edit");
local.currentNode = this;
local.eventData = eventData;
// Disable standard Fancytree mouse- and key handling
tree.widget._unbind();
// #116: ext-dnd prevents the blur event, so we have to catch outer clicks
$(document).on("mousedown.fancytree-edit", function(event){
if( ! $(event.target).hasClass("fancytree-edit-input") ){
node.editEnd(true, event);
}
});
// Replace node with <input>
$input = $("<input />", {
"class": "fancytree-edit-input",
type: "text",
value: unescapeHtml(eventData.orgTitle)
});
local.eventData.input = $input;
if ( instOpts.adjustWidthOfs != null ) {
$input.width($title.width() + instOpts.adjustWidthOfs);
}
if ( instOpts.inputCss != null ) {
$input.css(instOpts.inputCss);
}
$title.html($input);
// Focus <input> and bind keyboard handler
$input
.focus()
.change(function(event){
$input.addClass("fancytree-edit-dirty");
}).keydown(function(event){
switch( event.which ) {
case $.ui.keyCode.ESCAPE:
node.editEnd(false, event);
break;
case $.ui.keyCode.ENTER:
node.editEnd(true, event);
return false; // so we don't start editmode on Mac
}
event.stopPropagation();
}).blur(function(event){
return node.editEnd(true, event);
});
instOpts.edit.call(node, {type: "edit"}, eventData);
};
/**
* [ext-edit] Stop inline editing.
* @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified)
* @alias FancytreeNode#editEnd
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){
var newVal,
node = this,
tree = this.tree,
local = tree.ext.edit,
eventData = local.eventData,
instOpts = tree.options.edit,
$title = $(".fancytree-title", node.span),
$input = $title.find("input.fancytree-edit-input");
// eventData.isNew = $(node.span).hasClass("fancytree-edit-new");
if( instOpts.trim ) {
$input.val($.trim($input.val()));
}
newVal = $input.val();
// eventData.dirty = $input.hasClass("fancytree-edit-dirty") || ;
eventData.dirty = ( newVal !== node.title );
// Find out, if saving is required
if( applyChanges === false ) {
// If true/false was passed, honor this (except in rename mode, if unchanged)
eventData.save = false;
} else if( eventData.isNew ) {
// In create mode, we save everyting, except for empty text
eventData.save = (newVal !== "");
} else {
// In rename mode, we save everyting, except for empty or unchanged text
eventData.save = eventData.dirty && (newVal !== "");
}
// Allow to break (keep editor open), modify input, or re-define data.save
if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){
return false;
}
if( eventData.save && instOpts.save.call(node, {type: "save"}, eventData) === false){
return false;
}
$input
.removeClass("fancytree-edit-dirty")
.unbind();
// Unbind outer-click handler
$(document).off(".fancytree-edit");
if( eventData.save ) {
node.setTitle( escapeHtml(newVal) );
// $(node.span).removeClass("fancytree-edit-new");
node.setFocus();
}else{
if( eventData.isNew ) {
node.remove();
node = eventData.node = null;
local.relatedNode.setFocus();
} else {
node.renderTitle();
node.setFocus();
}
}
local.eventData = null;
local.currentNode = null;
local.relatedNode = null;
// Re-enable mouse and keyboard handling
tree.widget._bind();
// Set keyboard focus, even if setFocus() claims 'nothing to do'
$(tree.$container).focus();
eventData.input = null;
instOpts.close.call(node, {type: "close"}, eventData);
return true;
};
/**
* [ext-edit] Create a new child or sibling node and start edit mode.
*
* @param {String} [mode='child'] 'before', 'after', or 'child'
* @param {Object} [init] NodeData (or simple title string)
* @alias FancytreeNode#editCreateNode
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode, init){
var newNode,
self = this;
mode = mode || "child";
if( init == null ) {
init = { title: "" };
} else if( typeof init === "string" ) {
init = { title: init };
} else {
$.ui.fancytree.assert($.isPlainObject(init));
}
// Make sure node is expanded (and loaded) in 'child' mode
if( mode === "child" && !this.isExpanded() && this.hasChildren() !== false ) {
this.setExpanded().done(function(){
self.editCreateNode(mode, init);
});
return;
}
newNode = this.addNode(init, mode);
newNode.makeVisible(/*{noAnimation: true}*/).done(function(){
$(newNode.span).addClass("fancytree-edit-new");
self.tree.ext.edit.relatedNode = self;
newNode.editStart();
});
};
/**
* [ext-edit] Check if any node in this tree in edit mode.
*
* @returns {FancytreeNode | null}
* @alias Fancytree#isEditing
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeClass.prototype.isEditing = function(){
return this.ext.edit.currentNode;
};
/**
* [ext-edit] Check if this node is in edit mode.
* @returns {Boolean} true if node is currently beeing edited
* @alias FancytreeNode#isEditing
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){
return this.tree.ext.edit.currentNode === this;
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "edit",
version: "0.2.0",
// Default options for this extension.
options: {
adjustWidthOfs: 4, // null: don't adjust input size to content
allowEmpty: false, // Prevent empty input
inputCss: {minWidth: "3em"},
triggerCancel: ["esc", "tab", "click"],
// triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"],
triggerStart: ["f2", "shift+click", "mac+enter"],
trim: true, // Trim whitespace before save
// Events:
beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available)
beforeEdit: $.noop, // Return false to prevent edit mode
close: $.noop, // Editor was removed
edit: $.noop, // Editor was opened (available as data.input)
// keypress: $.noop, // Not yet implemented
save: $.noop // Save data.input.val() or return false to keep editor open
},
// Local attributes
currentNode: null,
treeInit: function(ctx){
this._superApply(arguments);
this.$container.addClass("fancytree-ext-edit");
},
nodeClick: function(ctx) {
if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){
if( ctx.originalEvent.shiftKey ){
ctx.node.editStart();
return false;
}
}
return this._superApply(arguments);
},
nodeDblclick: function(ctx) {
if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){
ctx.node.editStart();
return false;
}
return this._superApply(arguments);
},
nodeKeydown: function(ctx) {
switch( ctx.originalEvent.which ) {
case 113: // [F2]
if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){
ctx.node.editStart();
return false;
}
break;
case $.ui.keyCode.ENTER:
if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){
ctx.node.editStart();
return false;
}
break;
}
return this._superApply(arguments);
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.filter.js
*
* Remove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
function _escapeRegex(str){
/*jshint regexdash:true */
return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1");
}
$.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(filter, branchMode, opts){
var leavesOnly, match, re,
count = 0,
hideMode = this.options.filter.mode === "hide";
opts = opts || {};
leavesOnly = !!opts.leavesOnly && !branchMode;
// Default to 'match title substring (not case sensitive)'
if(typeof filter === "string"){
match = _escapeRegex(filter); // make sure a '.' is treated literally
re = new RegExp(".*" + match + ".*", "i");
filter = function(node){
return !!re.exec(node.title);
};
}
this.enableFilter = true;
this.lastFilterArgs = arguments;
this.$div.addClass("fancytree-ext-filter");
if( hideMode ){
this.$div.addClass("fancytree-ext-filter-hide");
} else {
this.$div.addClass("fancytree-ext-filter-dimm");
}
// Reset current filter
this.visit(function(node){
delete node.match;
delete node.subMatch;
});
// Adjust node.hide, .match, .subMatch flags
this.visit(function(node){
if ((!leavesOnly || node.children == null) && filter(node)) {
count++;
node.match = true;
node.visitParents(function(p){
p.subMatch = true;
if( opts.autoExpand && !p.expanded ) {
p.setExpanded(true, {noAnimation: true, noEvents: true, scrollIntoView: false});
p._filterAutoExpanded = true;
}
});
if( branchMode ) {
node.visit(function(p){
p.match = true;
});
return "skip";
}
}
});
// Redraw
this.render();
return count;
};
/**
* [ext-filter] Dimm or hide nodes.
*
* @param {function | string} filter
* @param {boolean} [opts={autoExpand: false, leavesOnly: false}]
* @returns {integer} count
* @alias Fancytree#filterNodes
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.filterNodes = function(filter, opts) {
if( typeof opts === "boolean" ) {
opts = { leavesOnly: opts };
this.warn("Fancytree.filterNodes() leavesOnly option is deprecated since 2015-04-20.");
}
return this._applyFilterImpl(filter, false, opts);
};
/**
* @deprecated
*/
$.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){
this.warn("Fancytree.applyFilter() is deprecated since 2014-05-10. Use .filterNodes() instead.");
return this.filterNodes.apply(this, arguments);
};
/**
* [ext-filter] Dimm or hide whole branches.
*
* @param {function | string} filter
* @param {boolean} [opts={autoExpand: false}]
* @returns {integer} count
* @alias Fancytree#filterBranches
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.filterBranches = function(filter, opts){
return this._applyFilterImpl(filter, true, opts);
};
/**
* [ext-filter] Reset the filter.
*
* @alias Fancytree#clearFilter
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){
this.visit(function(node){
delete node.match;
delete node.subMatch;
if( node._filterAutoExpanded && node.expanded ) {
node.setExpanded(false, {noAnimation: true, noEvents: true, scrollIntoView: false});
}
delete node._filterAutoExpanded;
});
this.enableFilter = false;
this.lastFilterArgs = null;
this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide");
this.render();
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "filter",
version: "0.4.0",
// Default options for this extension.
options: {
autoApply: true, // re-apply last filter if lazy data is loaded
mode: "dimm"
},
// treeInit: function(ctx){
// this._superApply(arguments);
// },
nodeLoadChildren: function(ctx, source) {
return this._superApply(arguments).done(function() {
if( ctx.tree.enableFilter && ctx.tree.lastFilterArgs && ctx.options.filter.autoApply ) {
ctx.tree._applyFilterImpl.apply(ctx.tree, ctx.tree.lastFilterArgs);
}
});
},
nodeSetExpanded: function(ctx, flag, callOpts) {
delete ctx.node._filterAutoExpanded;
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
// Set classes for current status
var res,
node = ctx.node,
tree = ctx.tree,
$span = $(node[tree.statusClassPropName]);
res = this._superApply(arguments);
// nothing to do, if node was not yet rendered
if( !$span.length || !tree.enableFilter ) {
return res;
}
$span
.toggleClass("fancytree-match", !!node.match)
.toggleClass("fancytree-submatch", !!node.subMatch)
.toggleClass("fancytree-hide", !(node.match || node.subMatch));
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.glyph.js
*
* Use glyph fonts as instead of icon sprites.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
function _getIcon(opts, type){
return opts.map[type];
}
$.ui.fancytree.registerExtension({
name: "glyph",
version: "0.2.0",
// Default options for this extension.
options: {
map: {
checkbox: "icon-check-empty",
checkboxSelected: "icon-check",
checkboxUnknown: "icon-check icon-muted",
error: "icon-exclamation-sign",
expanderClosed: "icon-caret-right",
expanderLazy: "icon-angle-right",
expanderOpen: "icon-caret-down",
doc: "icon-file-alt",
noExpander: "",
// Default node icons.
// (Use tree.options.iconClass(node) callback to define custom icons
// based on node data)
docOpen: "icon-file-alt",
loading: "icon-refresh icon-spin",
folder: "icon-folder-close-alt",
folderOpen: "icon-folder-open-alt"
}
},
treeInit: function(ctx){
var tree = ctx.tree;
this._superApply(arguments);
tree.$container.addClass("fancytree-ext-glyph");
},
nodeRenderStatus: function(ctx) {
var icon, span,
node = ctx.node,
$span = $(node.span),
opts = ctx.options.glyph,
// callback = opts.icon,
map = opts.map
// $span = $(node.span)
;
this._superApply(arguments);
if( node.isRoot() ){
return;
}
span = $span.children("span.fancytree-expander").get(0);
if( span ){
if( node.isLoading() ){
icon = "loading";
}else if( node.expanded ){
icon = "expanderOpen";
}else if( node.isUndefined() ){
icon = "expanderLazy";
}else if( node.hasChildren() ){
icon = "expanderClosed";
}else{
icon = "noExpander";
}
span.className = "fancytree-expander " + map[icon];
}
if( node.tr ){
span = $("td", node.tr).children("span.fancytree-checkbox").get(0);
}else{
span = $span.children("span.fancytree-checkbox").get(0);
}
if( span ){
icon = node.selected ? "checkboxSelected" : (node.partsel ? "checkboxUnknown" : "checkbox");
span.className = "fancytree-checkbox " + map[icon];
}
// Icon (note that this does not match .fancytree-custom-icon, that might
// be set by opts.iconClass)
span = $span.children("span.fancytree-icon").get(0);
if( span ){
if( node.folder ){
icon = node.expanded ? _getIcon(opts, "folderOpen") : _getIcon(opts, "folder");
}else{
icon = node.expanded ? _getIcon(opts, "docOpen") : _getIcon(opts, "doc");
}
span.className = "fancytree-icon " + icon;
}
},
nodeSetStatus: function(ctx, status, message, details) {
var span,
opts = ctx.options.glyph,
node = ctx.node;
this._superApply(arguments);
if(node.parent){
span = $("span.fancytree-expander", node.span).get(0);
}else{
span = $(".fancytree-statusnode-wait, .fancytree-statusnode-error", node[this.nodeContainerAttrName])
.find("span.fancytree-expander").get(0);
}
if( status === "loading"){
// $("span.fancytree-expander", ctx.node.span).addClass(_getIcon(opts, "loading"));
span.className = "fancytree-expander " + _getIcon(opts, "loading");
}else if( status === "error"){
span.className = "fancytree-expander " + _getIcon(opts, "error");
}
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.gridnav.js
*
* Support keyboard navigation for trees with embedded input controls.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
// Allow these navigation keys even when input controls are focused
var KC = $.ui.keyCode,
// which keys are *not* handled by embedded control, but passed to tree
// navigation handler:
NAV_KEYS = {
"text": [KC.UP, KC.DOWN],
"checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"select-one": [KC.LEFT, KC.RIGHT],
"select-multiple": [KC.LEFT, KC.RIGHT]
};
/* Calculate TD column index (considering colspans).*/
function getColIdx($tr, $td) {
var colspan,
td = $td.get(0),
idx = 0;
$tr.children().each(function () {
if( this === td ) {
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return idx;
}
/* Find TD at given column index (considering colspans).*/
function findTdAtColIdx($tr, colIdx) {
var colspan,
res = null,
idx = 0;
$tr.children().each(function () {
if( idx >= colIdx ) {
res = $(this);
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return res;
}
/* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */
function findNeighbourTd($target, keyCode){
var $tr, colIdx,
$td = $target.closest("td"),
$tdNext = null;
switch( keyCode ){
case KC.LEFT:
$tdNext = $td.prev();
break;
case KC.RIGHT:
$tdNext = $td.next();
break;
case KC.UP:
case KC.DOWN:
$tr = $td.parent();
colIdx = getColIdx($tr, $td);
while( true ) {
$tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next();
if( !$tr.length ) {
break;
}
// Skip hidden rows
if( $tr.is(":hidden") ) {
continue;
}
// Find adjacent cell in the same column
$tdNext = findTdAtColIdx($tr, colIdx);
// Skip cells that don't conatain a focusable element
if( $tdNext && $tdNext.find(":input").length ) {
break;
}
}
break;
}
return $tdNext;
}
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "gridnav",
version: "0.0.1",
// Default options for this extension.
options: {
autofocusInput: false, // Focus first embedded input if node gets activated
handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node
},
treeInit: function(ctx){
// gridnav requires the table extension to be loaded before itself
this._requireExtension("table", true, true);
this._superApply(arguments);
this.$container.addClass("fancytree-ext-gridnav");
// Activate node if embedded input gets focus (due to a click)
this.$container.on("focusin", function(event){
var ctx2,
node = $.ui.fancytree.getNode(event.target);
if( node && !node.isActive() ){
// Call node.setActive(), but also pass the event
ctx2 = ctx.tree._makeHookContext(node, event);
ctx.tree._callHook("nodeSetActive", ctx2, true);
}
});
},
nodeSetActive: function(ctx, flag) {
var $outer,
opts = ctx.options.gridnav,
node = ctx.node,
event = ctx.originalEvent || {},
triggeredByInput = $(event.target).is(":input");
flag = (flag !== false);
this._superApply(arguments);
if( flag ){
if( ctx.options.titlesTabbable ){
if( !triggeredByInput ) {
$(node.span).find("span.fancytree-title").focus();
node.setFocus();
}
// If one node is tabbable, the container no longer needs to be
ctx.tree.$container.attr("tabindex", "-1");
// ctx.tree.$container.removeAttr("tabindex");
} else if( opts.autofocusInput && !triggeredByInput ){
// Set focus to input sub input (if node was clicked, but not
// when TAB was pressed )
$outer = $(node.tr || node.span);
$outer.find(":input:enabled:first").focus();
}
}
},
nodeKeydown: function(ctx) {
var inputType, handleKeys, $td,
opts = ctx.options.gridnav,
event = ctx.originalEvent,
$target = $(event.target);
// jQuery
inputType = $target.is(":input:enabled") ? $target.prop("type") : null;
// ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType);
if( inputType && opts.handleCursorKeys ){
handleKeys = NAV_KEYS[inputType];
if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){
$td = findNeighbourTd($target, event.which);
// ctx.node.debug("ignore keydown in input", event.which, handleKeys);
if( $td && $td.length ) {
$td.find(":input:enabled").focus();
// Prevent Fancytree default navigation
return false;
}
}
return true;
}
// ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType);
return this._superApply(arguments);
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.persist.js
*
* Persist tree status in cookiesRemove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @depends: js-cookie or jquery-cookie
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/* global Cookies:false */
/*******************************************************************************
* Private functions and variables
*/
var cookieGetter, cookieRemover, cookieSetter,
_assert = $.ui.fancytree.assert,
ACTIVE = "active",
EXPANDED = "expanded",
FOCUS = "focus",
SELECTED = "selected";
if( typeof Cookies === "function" ) {
// Assume https://github.com/js-cookie/js-cookie
cookieSetter = Cookies.set;
cookieGetter = Cookies.get;
cookieRemover = Cookies.remove;
} else {
// Fall back to https://github.com/carhartl/jquery-cookie
cookieSetter = cookieGetter = $.cookie;
cookieRemover = $.removeCookie;
}
/* Recursively load lazy nodes
* @param {string} mode 'load', 'expand', false
*/
function _loadLazyNodes(tree, local, keyList, mode, dfd) {
var i, key, l, node,
foundOne = false,
deferredList = [],
missingKeyList = [];
keyList = keyList || [];
dfd = dfd || $.Deferred();
for( i=0, l=keyList.length; i<l; i++ ) {
key = keyList[i];
node = tree.getNodeByKey(key);
if( node ) {
if( mode && node.isUndefined() ) {
foundOne = true;
tree.debug("_loadLazyNodes: " + node + " is lazy: loading...");
if( mode === "expand" ) {
deferredList.push(node.setExpanded());
} else {
deferredList.push(node.load());
}
} else {
tree.debug("_loadLazyNodes: " + node + " already loaded.");
node.setExpanded();
}
} else {
missingKeyList.push(key);
tree.debug("_loadLazyNodes: " + node + " was not yet found.");
}
}
$.when.apply($, deferredList).always(function(){
// All lazy-expands have finished
if( foundOne && missingKeyList.length > 0 ) {
// If we read new nodes from server, try to resolve yet-missing keys
_loadLazyNodes(tree, local, missingKeyList, mode, dfd);
} else {
if( missingKeyList.length ) {
tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList);
for( i=0, l=missingKeyList.length; i<l; i++ ) {
key = keyList[i];
local._appendKey(EXPANDED, keyList[i], false);
}
}
dfd.resolve();
}
});
return dfd;
}
/**
* [ext-persist] Remove persistence cookies of the given type(s).
* Called like
* $("#tree").fancytree("getTree").clearCookies("active expanded focus selected");
*
* @alias Fancytree#clearCookies
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){
var local = this.ext.persist,
prefix = local.cookiePrefix;
types = types || "active expanded focus selected";
if(types.indexOf(ACTIVE) >= 0){
local._data(prefix + ACTIVE, null);
}
if(types.indexOf(EXPANDED) >= 0){
local._data(prefix + EXPANDED, null);
}
if(types.indexOf(FOCUS) >= 0){
local._data(prefix + FOCUS, null);
}
if(types.indexOf(SELECTED) >= 0){
local._data(prefix + SELECTED, null);
}
};
/**
* [ext-persist] Return persistence information from cookies
*
* Called like
* $("#tree").fancytree("getTree").getPersistData();
*
* @alias Fancytree#getPersistData
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){
var local = this.ext.persist,
prefix = local.cookiePrefix,
delim = local.cookieDelimiter,
res = {};
res[ACTIVE] = local._data(prefix + ACTIVE);
res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim);
res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim);
res[FOCUS] = local._data(prefix + FOCUS);
return res;
};
/* *****************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "persist",
version: "0.3.0",
// Default options for this extension.
options: {
cookieDelimiter: "~",
cookiePrefix: undefined, // 'fancytree-<treeId>-' by default
cookie: {
raw: false,
expires: "",
path: "",
domain: "",
secure: false
},
expandLazy: false, // true: recursively expand and load lazy nodes
overrideSource: true, // true: cookie takes precedence over `source` data attributes.
store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore
types: "active expanded focus selected"
},
/* Generic read/write string data to cookie, sessionStorage or localStorage. */
_data: function(key, value){
var ls = this._local.localStorage; // null, sessionStorage, or localStorage
if( value === undefined ) {
return ls ? ls.getItem(key) : cookieGetter(key);
} else if ( value === null ) {
if( ls ) {
ls.removeItem(key);
} else {
cookieRemover(key);
}
} else {
if( ls ) {
ls.setItem(key, value);
} else {
cookieSetter(key, value, this.options.persist.cookie);
}
}
},
/* Append `key` to a cookie. */
_appendKey: function(type, key, flag){
key = "" + key; // #90
var local = this._local,
instOpts = this.options.persist,
delim = instOpts.cookieDelimiter,
cookieName = local.cookiePrefix + type,
data = local._data(cookieName),
keyList = data ? data.split(delim) : [],
idx = $.inArray(key, keyList);
// Remove, even if we add a key, so the key is always the last entry
if(idx >= 0){
keyList.splice(idx, 1);
}
// Append key to cookie
if(flag){
keyList.push(key);
}
local._data(cookieName, keyList.join(delim));
},
treeInit: function(ctx){
var tree = ctx.tree,
opts = ctx.options,
local = this._local,
instOpts = this.options.persist;
// For 'auto' or 'cookie' mode, the cookie plugin must be available
_assert(instOpts.store === "localStore" || cookieGetter, "Missing required plugin for 'persist' extension: js.cookie.js or jquery.cookie.js");
local.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-");
local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0;
local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0;
local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0;
local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0;
if( instOpts.store === "cookie" || !window.localStorage ) {
local.localStorage = null;
} else {
local.localStorage = (instOpts.store === "local") ? window.localStorage : window.sessionStorage;
}
// Bind init-handler to apply cookie state
tree.$div.bind("fancytreeinit", function(event){
var cookie, dfd, i, keyList, node,
prevFocus = local._data(local.cookiePrefix + FOCUS); // record this before node.setActive() overrides it;
// tree.debug("document.cookie:", document.cookie);
cookie = local._data(local.cookiePrefix + EXPANDED);
keyList = cookie && cookie.split(instOpts.cookieDelimiter);
if( local.storeExpanded ) {
// Recursively load nested lazy nodes if expandLazy is 'expand' or 'load'
// Also remove expand-cookies for unmatched nodes
dfd = _loadLazyNodes(tree, local, keyList, instOpts.expandLazy ? "expand" : false , null);
} else {
// nothing to do
dfd = new $.Deferred().resolve();
}
dfd.done(function(){
if(local.storeSelected){
cookie = local._data(local.cookiePrefix + SELECTED);
if(cookie){
keyList = cookie.split(instOpts.cookieDelimiter);
for(i=0; i<keyList.length; i++){
node = tree.getNodeByKey(keyList[i]);
if(node){
if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){
// node.setSelected();
node.selected = true;
node.renderStatus();
}
}else{
// node is no longer member of the tree: remove from cookie also
local._appendKey(SELECTED, keyList[i], false);
}
}
}
// In selectMode 3 we have to fix the child nodes, since we
// only stored the selected *top* nodes
if( tree.options.selectMode === 3 ){
tree.visit(function(n){
if( n.selected ) {
n.fixSelection3AfterClick();
return "skip";
}
});
}
}
if(local.storeActive){
cookie = local._data(local.cookiePrefix + ACTIVE);
if(cookie && (opts.persist.overrideSource || !tree.activeNode)){
node = tree.getNodeByKey(cookie);
if(node){
node.debug("persist: set active", cookie);
// We only want to set the focus if the container
// had the keyboard focus before
node.setActive(true, {noFocus: true});
}
}
}
if(local.storeFocus && prevFocus){
node = tree.getNodeByKey(prevFocus);
if(node){
// node.debug("persist: set focus", cookie);
if( tree.options.titlesTabbable ) {
$(node.span).find(".fancytree-title").focus();
} else {
$(tree.$container).focus();
}
// node.setFocus();
}
}
tree._triggerTreeEvent("restore", null, {});
});
});
// Init the tree
return this._superApply(arguments);
},
nodeSetActive: function(ctx, flag, opts) {
var res,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeActive){
local._data(local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null);
}
return res;
},
nodeSetExpanded: function(ctx, flag, opts) {
var res,
node = ctx.node,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeExpanded){
local._appendKey(EXPANDED, node.key, flag);
}
return res;
},
nodeSetFocus: function(ctx, flag) {
var res,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if( local.storeFocus ) {
local._data(local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null);
}
return res;
},
nodeSetSelected: function(ctx, flag) {
var res, selNodes,
tree = ctx.tree,
node = ctx.node,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeSelected){
if( tree.options.selectMode === 3 ){
// In selectMode 3 we only store the the selected *top* nodes.
// De-selecting a node may also de-select some parents, so we
// calculate the current status again
selNodes = $.map(tree.getSelectedNodes(true), function(n){
return n.key;
});
selNodes = selNodes.join(ctx.options.persist.cookieDelimiter);
local._data(local.cookiePrefix + SELECTED, selNodes);
} else {
local._appendKey(SELECTED, node.key, flag);
}
}
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.table.js
*
* Render tree as table (aka 'treegrid', 'tabletree').
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
msg = msg || "";
if(!cond){
$.error("Assertion failed " + msg);
}
}
function insertSiblingAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/* Show/hide all rows that are structural descendants of `parent`. */
function setChildRowVisibility(parent, flag) {
parent.visit(function(node){
var tr = node.tr;
// currentFlag = node.hide ? false : flag; // fix for ext-filter
if(tr){
tr.style.display = (node.hide || !flag) ? "none" : "";
}
if(!node.expanded){
return "skip";
}
});
}
/* Find node that is rendered in previous row. */
function findPrevRowNode(node){
var i, last, prev,
parent = node.parent,
siblings = parent ? parent.children : null;
if(siblings && siblings.length > 1 && siblings[0] !== node){
// use the lowest descendant of the preceeding sibling
i = $.inArray(node, siblings);
prev = siblings[i - 1];
_assert(prev.tr);
// descend to lowest child (with a <tr> tag)
while(prev.children){
last = prev.children[prev.children.length - 1];
if(!last.tr){
break;
}
prev = last;
}
}else{
// if there is no preceding sibling, use the direct parent
prev = parent;
}
return prev;
}
$.ui.fancytree.registerExtension({
name: "table",
version: "0.2.1",
// Default options for this extension.
options: {
checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx)
customStatus: false, // true: generate renderColumns events for status nodes
indentation: 16, // indent every node level by 16px
nodeColumnIdx: 0 // render node expander, icon, and title to this column (default: #0)
},
// Overide virtual methods for this extension.
// `this` : is this extension object
// `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
treeInit: function(ctx){
var i, $row, tdRole,
tree = ctx.tree,
$table = tree.widget.element;
$table.addClass("fancytree-container fancytree-ext-table");
tree.tbody = $table.find("> tbody")[0];
tree.columnCount = $("thead >tr >th", $table).length;
$(tree.tbody).empty();
tree.rowFragment = document.createDocumentFragment();
$row = $("<tr />");
tdRole = "";
if(ctx.options.aria){
$row.attr("role", "row");
tdRole = " role='gridcell'";
}
for(i=0; i<tree.columnCount; i++) {
if(ctx.options.table.nodeColumnIdx === i){
$row.append("<td" + tdRole + "><span class='fancytree-node' /></td>");
}else{
$row.append("<td" + tdRole + " />");
}
}
tree.rowFragment.appendChild($row.get(0));
// Make sure that status classes are set on the node's <tr> elements
tree.statusClassPropName = "tr";
tree.ariaPropName = "tr";
this.nodeContainerAttrName = "tr";
this._superApply(arguments);
// standard Fancytree created a root UL
$(tree.rootNode.ul).remove();
tree.rootNode.ul = null;
tree.$container = $table;
// Add container to the TAB chain
this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
if(this.options.aria){
tree.$container
.attr("role", "treegrid")
.attr("aria-readonly", true);
}
},
/* Called by nodeRender to sync node order with tag order.*/
// nodeFixOrder: function(ctx) {
// },
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// node.debug("nodeRemoveChildMarkup()");
node.visit(function(n){
if(n.tr){
$(n.tr).remove();
n.tr = null;
}
});
},
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// node.debug("nodeRemoveMarkup()");
if(node.tr){
$(node.tr).remove();
node.tr = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/* Override standard render. */
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx,
tree = ctx.tree,
node = ctx.node,
opts = ctx.options,
isRootNode = !node.parent;
if( !_recursive ){
ctx.hasCollapsedParents = node.parent && !node.parent.expanded;
}
// $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr));
if( !isRootNode ){
if(!node.tr){
if( ctx.hasCollapsedParents /*&& !node.parent.tr*/ ) {
// #166: we assume that the parent will be (recursively) rendered
// later anyway.
node.debug("nodeRender ignored due to unrendered parent");
return;
}
// Create new <tr> after previous row
newRow = tree.rowFragment.firstChild.cloneNode(true);
prevNode = findPrevRowNode(node);
// $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key);
_assert(prevNode);
if(collapsed === true && _recursive){
// hide all child rows, so we can use an animation to show it later
newRow.style.display = "none";
}else if(deep && ctx.hasCollapsedParents){
// also hide this row if deep === true but any parent is collapsed
newRow.style.display = "none";
// newRow.style.color = "red";
}
if(!prevNode.tr){
_assert(!prevNode.parent, "prev. row must have a tr, or is system root");
tree.tbody.appendChild(newRow);
}else{
insertSiblingAfter(prevNode.tr, newRow);
}
node.tr = newRow;
if( node.key && opts.generateIds ){
node.tr.id = opts.idPrefix + node.key;
}
node.tr.ftnode = node;
if(opts.aria){
// TODO: why doesn't this work:
// node.li.role = "treeitem";
$(node.tr).attr("aria-labelledby", "ftal_" + node.key);
}
node.span = $("span.fancytree-node", node.tr).get(0);
// Set icon, link, and title (normally this is only required on initial render)
this.nodeRenderTitle(ctx);
// Allow tweaking, binding, after node was created for the first time
// tree._triggerNodeEvent("createNode", ctx);
if ( opts.createNode ){
opts.createNode.call(tree, {type: "createNode"}, ctx);
}
} else {
if( force ) {
// Set icon, link, and title (normally this is only required on initial render)
this.nodeRenderTitle(ctx); // triggers renderColumns()
} else {
// Update element classes according to node state
this.nodeRenderStatus(ctx);
}
}
}
// Allow tweaking after node state was rendered
// tree._triggerNodeEvent("renderNode", ctx);
if ( opts.renderNode ){
opts.renderNode.call(tree, {type: "renderNode"}, ctx);
}
// Visit child nodes
// Add child markup
children = node.children;
if(children && (isRootNode || deep || node.expanded)){
for(i=0, l=children.length; i<l; i++) {
subCtx = $.extend({}, ctx, {node: children[i]});
subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded;
this.nodeRender(subCtx, force, deep, collapsed, true);
}
}
// Make sure, that <tr> order matches node.children order.
if(children && !_recursive){ // we only have to do it once, for the root branch
prevTr = node.tr || null;
firstTr = tree.tbody.firstChild;
// Iterate over all descendants
node.visit(function(n){
if(n.tr){
if(!n.parent.expanded && n.tr.style.display !== "none"){
// fix after a node was dropped over a collapsed
n.tr.style.display = "none";
setChildRowVisibility(n, false);
}
if(n.tr.previousSibling !== prevTr){
node.debug("_fixOrder: mismatch at node: " + n);
var nextTr = prevTr ? prevTr.nextSibling : firstTr;
tree.tbody.insertBefore(n.tr, nextTr);
}
prevTr = n.tr;
}
});
}
// Update element classes according to node state
// if(!isRootNode){
// this.nodeRenderStatus(ctx);
// }
},
nodeRenderTitle: function(ctx, title) {
var $cb,
node = ctx.node,
opts = ctx.options;
this._superApply(arguments);
// Move checkbox to custom column
if(opts.checkbox && opts.table.checkboxColumnIdx != null ){
$cb = $("span.fancytree-checkbox", node.span).detach();
$(node.tr).find("td").eq(+opts.table.checkboxColumnIdx).html($cb);
}
// Update element classes according to node state
if( ! node.isRoot() ){
this.nodeRenderStatus(ctx);
}
if( !opts.table.customStatus && node.isStatusNode() ) {
// default rendering for status node: leave other cells empty
} else if ( opts.renderColumns ) {
// Let user code write column content
opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx);
}
},
nodeRenderStatus: function(ctx) {
var indent,
node = ctx.node,
opts = ctx.options;
this._superApply(arguments);
$(node.tr).removeClass("fancytree-node");
// indent
indent = (node.getLevel() - 1) * opts.table.indentation;
$(node.span).css({marginLeft: indent + "px"});
},
/* Expand node, return Deferred.promise. */
nodeSetExpanded: function(ctx, flag, opts) {
var dfd = new $.Deferred(),
subOpts = $.extend({}, opts, {noEvents: true, noAnimation: true});
opts = opts || {};
function _afterExpand(ok) {
flag = (flag !== false);
setChildRowVisibility(ctx.node, flag);
if( ok ) {
if( flag && ctx.options.autoScroll && !opts.noAnimation && ctx.node.hasChildren() ) {
// Scroll down to last child, but keep current node visible
ctx.node.getLastChild().scrollIntoView(true, {topNode: ctx.node}).always(function(){
if( !opts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.resolveWith(ctx.node);
});
} else {
if( !opts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.resolveWith(ctx.node);
}
} else {
if( !opts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.rejectWith(ctx.node);
}
}
// Call base-expand with disabled events and animation
this._super(ctx, flag, subOpts).done(function () {
_afterExpand(true);
}).fail(function () {
_afterExpand(false);
});
return dfd.promise();
},
nodeSetStatus: function(ctx, status, message, details) {
if(status === "ok"){
var node = ctx.node,
firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
$(firstChild.tr).remove();
}
}
return this._superApply(arguments);
},
treeClear: function(ctx) {
this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode));
return this._superApply(arguments);
},
treeDestroy: function(ctx) {
this.$container.find("tbody").empty();
this.$source && this.$source.removeClass("ui-helper-hidden");
}
/*,
treeSetFocus: function(ctx, flag) {
// alert("treeSetFocus" + ctx.tree.$container);
ctx.tree.$container.focus();
$.ui.fancytree.focusTree = ctx.tree;
}*/
});
}(jQuery, window, document));
/*!
* jquery.fancytree.themeroller.js
*
* Enable jQuery UI ThemeRoller styles.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @see http://jqueryui.com/themeroller/
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "themeroller",
version: "0.0.1",
// Default options for this extension.
options: {
activeClass: "ui-state-active",
foccusClass: "ui-state-focus",
hoverClass: "ui-state-hover",
selectedClass: "ui-state-highlight"
},
treeInit: function(ctx){
this._superApply(arguments);
var $el = ctx.widget.element;
if($el[0].nodeName === "TABLE"){
$el.addClass("ui-widget ui-corner-all");
$el.find(">thead tr").addClass("ui-widget-header");
$el.find(">tbody").addClass("ui-widget-conent");
}else{
$el.addClass("ui-widget ui-widget-content ui-corner-all");
}
$el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){
var node = $.ui.fancytree.getNode(event.target),
flag = (event.type === "mouseenter");
node.debug("hover: " + flag);
$(node.tr ? node.tr : node.span).toggleClass("ui-state-hover ui-corner-all", flag);
});
},
treeDestroy: function(ctx){
this._superApply(arguments);
ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all");
},
nodeRenderStatus: function(ctx){
var node = ctx.node,
$el = $(node.tr ? node.tr : node.span);
this._superApply(arguments);
/*
.ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons.
.ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons.
.ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons.
.ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons.
.ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
.ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
.ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons.
*/
$el.toggleClass("ui-state-active", node.isActive());
$el.toggleClass("ui-state-focus", node.hasFocus());
$el.toggleClass("ui-state-highlight", node.isSelected());
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.wide.js
* Support for 100% wide selection bars.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.10.0
* @date 2015-06-26T22:37
*/
;(function($, window, document, undefined) {
"use strict";
var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"]
/*******************************************************************************
* Private functions and variables
*/
// var _assert = $.ui.fancytree.assert;
/* Calculate inner width without scrollbar */
// function realInnerWidth($el) {
// // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/
// // inst.contWidth = parseFloat(this.$container.css("width"), 10);
// // 'Client width without scrollbar' - 'padding'
// return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10));
// }
/* Create a global embedded CSS style for the tree. */
function defineHeadStyleElement(id, cssText) {
id = "fancytree-style-" + id;
var $headStyle = $("#" + id);
if( !cssText ) {
$headStyle.remove();
return null;
}
if( !$headStyle.length ) {
$headStyle = $("<style />")
.attr("id", id)
.addClass("fancytree-style")
.prop("type", "text/css")
.appendTo("head");
}
try {
$headStyle.html(cssText);
} catch ( e ) {
// fix for IE 6-8
$headStyle[0].styleSheet.cssText = cssText;
}
return $headStyle;
}
/* Calculate the CSS rules that indent title spans. */
function renderLevelCss(containerId, depth, levelOfs, lineOfs, measureUnit) {
var i,
prefix = "#" + containerId + " span.fancytree-level-",
rules = [];
for(i = 0; i < depth; i++) {
rules.push(prefix + (i + 1) + " span.fancytree-title { padding-left: " +
(i * levelOfs + lineOfs) + measureUnit + "; }");
}
// Some UI animations wrap the UL inside a DIV and set position:relative on both.
// This breaks the left:0 and padding-left:nn settings of the title
rules.push("#" + containerId +
" div.ui-effects-wrapper ul li span.fancytree-title " +
"{ padding-left: 3px; position: static; width: auto; }");
return rules.join("\n");
}
// /**
// * [ext-wide] Recalculate the width of the selection bar after the tree container
// * was resized.<br>
// * May be called explicitly on container resize, since there is no resize event
// * for DIV tags.
// *
// * @alias Fancytree#wideUpdate
// * @requires jquery.fancytree.wide.js
// */
// $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){
// var inst = this.ext.wide,
// prevCw = inst.contWidth,
// prevLo = inst.lineOfs;
// inst.contWidth = realInnerWidth(this.$container);
// // Each title is precceeded by 2 or 3 icons (16px + 3 margin)
// // + 1px title border and 3px title padding
// // TODO: use code from treeInit() below
// inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19;
// if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) {
// this.debug("wideUpdate: " + inst.contWidth);
// this.visit(function(node){
// node.tree._callHook("nodeRenderTitle", node);
// });
// }
// };
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "wide",
version: "0.0.3",
// Default options for this extension.
options: {
iconWidth: null, // Adjust this if @fancy-icon-width != "16px"
iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px"
levelOfs: null // Adjust this if ul padding != "16px"
},
treeCreate: function(ctx){
this._superApply(arguments);
this.$container.addClass("fancytree-ext-wide");
var containerId, cssText, iconSpacingUnit, iconWidthUnit, levelOfsUnit,
instOpts = ctx.options.wide,
// css sniffing
$dummyLI = $("<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />")
.appendTo(ctx.tree.$container),
$dummyIcon = $dummyLI.find(".fancytree-icon"),
$dummyUL = $dummyLI.find("ul"),
// $dummyTitle = $dummyLI.find(".fancytree-title"),
iconSpacing = instOpts.iconSpacing || $dummyIcon.css("margin-left"),
iconWidth = instOpts.iconWidth || $dummyIcon.css("width"),
levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left");
$dummyLI.remove();
iconSpacingUnit = iconSpacing.match(reNumUnit)[2];
iconSpacing = parseFloat(iconSpacing, 10);
iconWidthUnit = iconWidth.match(reNumUnit)[2];
iconWidth = parseFloat(iconWidth, 10);
levelOfsUnit = levelOfs.match(reNumUnit)[2];
if( iconSpacingUnit !== iconWidthUnit || levelOfsUnit !== iconWidthUnit ) {
$.error("iconWidth, iconSpacing, and levelOfs must have the same css measure unit");
}
this._local.measureUnit = iconWidthUnit;
this._local.levelOfs = parseFloat(levelOfs);
this._local.lineOfs = (ctx.options.checkbox ? 3 : 2) * (iconWidth + iconSpacing) + iconSpacing;
this._local.maxDepth = 10;
// Get/Set a unique Id on the container (if not already exists)
containerId = this.$container.uniqueId().attr("id");
// Generated css rules for some levels (extended on demand)
cssText = renderLevelCss(containerId, this._local.maxDepth,
this._local.levelOfs, this._local.lineOfs, this._local.measureUnit);
defineHeadStyleElement(containerId, cssText);
},
treeDestroy: function(ctx){
// Remove generated css rules
defineHeadStyleElement(this.$container.attr("id"), null);
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
var containerId, cssText, res,
node = ctx.node,
level = node.getLevel();
res = this._superApply(arguments);
// Generate some more level-n rules if required
if( level > this._local.maxDepth ) {
containerId = this.$container.attr("id");
this._local.maxDepth *= 2;
node.debug("Define global ext-wide css up to level " + this._local.maxDepth);
cssText = renderLevelCss(containerId, this._local.maxDepth,
this._local.levelOfs, this._local.lineOfs, this._local.measureUnit);
defineHeadStyleElement(containerId, cssText);
}
// Add level-n class to apply indentation padding.
// (Setting element style would not work, since it cannot easily be
// overriden while animations run)
$(node.span).addClass("fancytree-level-" + level);
return res;
}
});
}(jQuery, window, document));
|
packages/react-error-overlay/src/containers/StackFrame.js | peopleticker/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React, { Component } from 'react';
import CodeBlock from './StackFrameCodeBlock';
import { getPrettyURL } from '../utils/getPrettyURL';
import { darkGray } from '../styles';
import type { StackFrame as StackFrameType } from '../utils/stack-frame';
import type { ErrorLocation } from '../utils/parseCompileError';
const linkStyle = {
fontSize: '0.9em',
marginBottom: '0.9em',
};
const anchorStyle = {
textDecoration: 'none',
color: darkGray,
cursor: 'pointer',
};
const codeAnchorStyle = {
cursor: 'pointer',
};
const toggleStyle = {
marginBottom: '1.5em',
color: darkGray,
cursor: 'pointer',
border: 'none',
display: 'block',
width: '100%',
textAlign: 'left',
background: '#fff',
fontFamily: 'Consolas, Menlo, monospace',
fontSize: '1em',
padding: '0px',
lineHeight: '1.5',
};
type Props = {|
frame: StackFrameType,
contextSize: number,
critical: boolean,
showCode: boolean,
editorHandler: (errorLoc: ErrorLocation) => void,
|};
type State = {|
compiled: boolean,
|};
class StackFrame extends Component<Props, State> {
state = {
compiled: false,
};
toggleCompiled = () => {
this.setState(state => ({
compiled: !state.compiled,
}));
};
getErrorLocation(): ErrorLocation | null {
const {
_originalFileName: fileName,
_originalLineNumber: lineNumber,
} = this.props.frame;
// Unknown file
if (!fileName) {
return null;
}
// e.g. "/path-to-my-app/webpack/bootstrap eaddeb46b67d75e4dfc1"
const isInternalWebpackBootstrapCode = fileName.trim().indexOf(' ') !== -1;
if (isInternalWebpackBootstrapCode) {
return null;
}
// Code is in a real file
return { fileName, lineNumber: lineNumber || 1 };
}
editorHandler = () => {
const errorLoc = this.getErrorLocation();
if (!errorLoc) {
return;
}
this.props.editorHandler(errorLoc);
};
onKeyDown = (e: SyntheticKeyboardEvent<>) => {
if (e.key === 'Enter') {
this.editorHandler();
}
};
render() {
const { frame, contextSize, critical, showCode } = this.props;
const {
fileName,
lineNumber,
columnNumber,
_scriptCode: scriptLines,
_originalFileName: sourceFileName,
_originalLineNumber: sourceLineNumber,
_originalColumnNumber: sourceColumnNumber,
_originalScriptCode: sourceLines,
} = frame;
const functionName = frame.getFunctionName();
const compiled = this.state.compiled;
const url = getPrettyURL(
sourceFileName,
sourceLineNumber,
sourceColumnNumber,
fileName,
lineNumber,
columnNumber,
compiled
);
let codeBlockProps = null;
if (showCode) {
if (
compiled &&
scriptLines &&
scriptLines.length !== 0 &&
lineNumber != null
) {
codeBlockProps = {
lines: scriptLines,
lineNum: lineNumber,
columnNum: columnNumber,
contextSize,
main: critical,
};
} else if (
!compiled &&
sourceLines &&
sourceLines.length !== 0 &&
sourceLineNumber != null
) {
codeBlockProps = {
lines: sourceLines,
lineNum: sourceLineNumber,
columnNum: sourceColumnNumber,
contextSize,
main: critical,
};
}
}
const canOpenInEditor =
this.getErrorLocation() !== null && this.props.editorHandler !== null;
return (
<div>
<div>{functionName}</div>
<div style={linkStyle}>
<a
style={canOpenInEditor ? anchorStyle : null}
onClick={canOpenInEditor ? this.editorHandler : null}
onKeyDown={canOpenInEditor ? this.onKeyDown : null}
tabIndex={canOpenInEditor ? '0' : null}
>
{url}
</a>
</div>
{codeBlockProps && (
<span>
<a
onClick={canOpenInEditor ? this.editorHandler : null}
style={canOpenInEditor ? codeAnchorStyle : null}
>
<CodeBlock {...codeBlockProps} />
</a>
<button style={toggleStyle} onClick={this.toggleCompiled}>
{'View ' + (compiled ? 'source' : 'compiled')}
</button>
</span>
)}
</div>
);
}
}
export default StackFrame;
|
app/javascript/mastodon/features/ui/components/list_panel.js | MitarashiDango/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { fetchLists } from 'mastodon/actions/lists';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { NavLink, withRouter } from 'react-router-dom';
import Icon from 'mastodon/components/icon';
const getOrderedLists = createSelector([state => state.get('lists')], lists => {
if (!lists) {
return lists;
}
return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))).take(4);
});
const mapStateToProps = state => ({
lists: getOrderedLists(state),
});
export default @withRouter
@connect(mapStateToProps)
class ListPanel extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
lists: ImmutablePropTypes.list,
};
componentDidMount () {
const { dispatch } = this.props;
dispatch(fetchLists());
}
render () {
const { lists } = this.props;
if (!lists || lists.isEmpty()) {
return null;
}
return (
<div>
<hr />
{lists.map(list => (
<NavLink key={list.get('id')} className='column-link column-link--transparent' strict to={`/lists/${list.get('id')}`}><Icon className='column-link__icon' id='list-ul' fixedWidth />{list.get('title')}</NavLink>
))}
</div>
);
}
}
|
packages/bonde-styleguide/src/cards/ClickableCard/ClickableCard.js | ourcities/rebu-client | import React from 'react'
import PropTypes from 'prop-types'
import {
Card,
Flexbox,
Text,
IconColorful
} from '../../'
const ClickableCard = ({
sectionTitle,
minHeight,
iconName,
label,
description,
onClick
}) => (
<Card title={sectionTitle} minHeight={minHeight} onClick={onClick} middle>
<Flexbox horizontal padding={{ x: 18 }}>
<IconColorful name={iconName} />
<Flexbox fullSize padding={{ left: 20 }}>
<Text fontSize={16} fontWeight={900} lineHeight={1.25}>{label}</Text>
<Text fontSize={13} lineHeight={1.54} color='#4a4a4a'>{description}</Text>
</Flexbox>
</Flexbox>
</Card>
)
ClickableCard.propTypes = {
sectionTitle: PropTypes.string,
minHeight: PropTypes.number,
iconName: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired
}
ClickableCard.defaultProps = {
minHeight: 110
}
ClickableCard.displayName = 'ClickableCard'
/* @component */
export default ClickableCard
|
packages/material-ui/src/resetPasswordComponents.js | js-accounts/react | import PropTypes from 'prop-types';
/* eslint-disable no-shadow */
import React from 'react';
import Flexbox from 'flexbox-react';
import getContext from 'recompose/getContext';
import Container from './Container';
import Content from './Content';
import FormError from './FormError';
import Header from './components/header';
import Avatar from './components/avatar';
import PasswordField from './components/password';
import SubmitButton from './components/submitButton';
const ResetPasswordFields = ({ children }) =>
<Flexbox flexDirection="column" justifyContent="center" alignItems="center">
{children}
</Flexbox>;
ResetPasswordFields.propTypes = {
children: PropTypes.node,
};
const LoginButton = getContext({
setFormType: PropTypes.func,
})(({ setFormType, ...otherProps }) =>
<Flexbox>
<a
href="#/"
style={{
fontFamily: 'Roboto',
textDecoration: 'none',
fontSize: 16,
}}
onClick={() => setFormType('login')}
{...otherProps}
>
Log in
</a>
</Flexbox>);
const Footer = ({ ...otherProps }) =>
<LoginButton {...otherProps} />;
Footer.propTypes = {
SignupButton: PropTypes.node,
};
export default {
Container,
Content,
Avatar,
ResetPasswordFields,
ResetPasswordPasswordField: PasswordField,
ResetPasswordPasswordConfirmField: PasswordField,
ResetPasswordButton: SubmitButton,
Header,
Footer,
FormError,
};
|
test/PageItemSpec.js | AlexKVal/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import PageItem from '../src/PageItem';
describe('PageItem', function () {
it('Should output a "list item" as root element, and an "anchor" as a child item', function () {
let instance = ReactTestUtils.renderIntoDocument(
<PageItem href="#">Text</PageItem>
);
let node = React.findDOMNode(instance);
assert.equal(node.nodeName, 'LI');
assert.equal(node.children.length, 1);
assert.equal(node.children[0].nodeName, 'A');
});
it('Should output "disabled" attribute as a class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<PageItem disabled href="#">Text</PageItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled'));
});
it('Should output "next" attribute as a class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<PageItem previous href="#">Previous</PageItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'previous'));
});
it('Should output "previous" attribute as a class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<PageItem next href="#">Next</PageItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'next'));
});
it('Should call "onSelect" when item is clicked', function (done) {
function handleSelect(key, href) {
assert.equal(key, 1);
assert.equal(href, undefined);
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<PageItem eventKey={1} onSelect={handleSelect}>Next</PageItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
});
it('Should not call "onSelect" when item disabled and is clicked', function () {
function handleSelect() {
throw new Error('onSelect should not be called');
}
let instance = ReactTestUtils.renderIntoDocument(
<PageItem disabled onSelect={handleSelect}>Next</PageItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
});
it('Should set target attribute on anchor', function () {
let instance = ReactTestUtils.renderIntoDocument(
<PageItem next href="#" target="_blank">Next</PageItem>
);
let anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a');
assert.equal(React.findDOMNode(anchor).getAttribute('target'), '_blank');
});
it('Should call "onSelect" with target attribute', function (done) {
function handleSelect(key, href, target) {
assert.equal(target, '_blank');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<PageItem eventKey={1} onSelect={handleSelect} target="_blank">Next</PageItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
});
});
|
docs/app/Examples/elements/Step/States/index.js | shengnian/shengnian-ui-react | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const States = () => (
<ExampleSection title='States'>
<ComponentExample
title='Active'
description='A step can be highlighted as active.'
examplePath='elements/Step/States/StepExampleActive'
/>
<ComponentExample
title='Completed'
description='A step can show that a user has completed it.'
examplePath='elements/Step/States/StepExampleCompleted'
/>
<ComponentExample
description='A step can show that a user has completed it when its group is ordered.'
examplePath='elements/Step/States/StepExampleCompletedOrdered'
/>
<ComponentExample
title='Disabled'
description='A step can show that it cannot be selected.'
examplePath='elements/Step/States/StepExampleDisabled'
/>
</ExampleSection>
)
export default States
|
ajax/libs/react-widgets/3.1.6/react-widgets-globalize.js | holtkamp/cdnjs | /*! (c) 2016 Jason Quense | https://github.com/jquense/react-widgets/blob/master/License.txt */
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/*** IMPORTS FROM imports-loader ***/
var module = __webpack_require__(1);
var args = [Globalize];
if (typeof module === 'function') {
module.apply(null, args || [])
}
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var babelHelpers = __webpack_require__(2);
exports.__esModule = true;
exports['default'] = globalizeLocalizers;
var _react = __webpack_require__(3);
var _configure = __webpack_require__(4);
var _configure2 = babelHelpers.interopRequireDefault(_configure);
function endOfDecade(date) {
date = new Date(date);
date.setFullYear(date.getFullYear() + 10);
date.setMilliseconds(date.getMilliseconds() - 1);
return date;
}
function endOfCentury(date) {
date = new Date(date);
date.setFullYear(date.getFullYear() + 100);
date.setMilliseconds(date.getMilliseconds() - 1);
return date;
}
function globalizeLocalizers(globalize) {
var localizers = globalize.load ? newGlobalize(globalize) : oldGlobalize(globalize);
_configure2['default'].setLocalizers(localizers);
return localizers;
}
function newGlobalize(globalize) {
var locale = function locale(culture) {
return culture ? globalize(culture) : globalize;
};
var date = {
formats: {
date: { date: 'short' },
time: { time: 'short' },
'default': { datetime: 'medium' },
header: 'MMMM yyyy',
footer: { date: 'full' },
weekday: 'eeeeee',
dayOfMonth: 'dd',
month: 'MMM',
year: 'yyyy',
decade: function decade(dt, culture, l) {
return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfDecade(dt), l.formats.year, culture);
},
century: function century(dt, culture, l) {
return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfCentury(dt), l.formats.year, culture);
}
},
propType: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object, _react.PropTypes.func]),
firstOfWeek: function firstOfWeek(culture) {
var date = new Date();
//cldr-data doesn't seem to be zero based
var localeDay = Math.max(parseInt(locale(culture).formatDate(date, { raw: 'e' }), 10) - 1, 0);
return Math.abs(date.getDay() - localeDay);
},
parse: function parse(value, format, culture) {
format = typeof format === 'string' ? { raw: format } : format;
return locale(culture).parseDate(value, format);
},
format: function format(value, _format, culture) {
_format = typeof _format === 'string' ? { raw: _format } : _format;
return locale(culture).formatDate(value, _format);
}
};
var number = {
formats: {
'default': { maximumFractionDigits: 0 }
},
propType: _react.PropTypes.oneOfType([_react.PropTypes.object, _react.PropTypes.func]),
// TODO major bump consistent ordering
parse: function parse(value, culture) {
return locale(culture).parseNumber(value);
},
format: function format(value, _format2, culture) {
if (value == null) return value;
if (_format2 && _format2.currency) return locale(culture).formatCurrency(value, _format2.currency, _format2);
return locale(culture).formatNumber(value, _format2);
},
decimalChar: function decimalChar(format, culture) {
var str = this.format(1.1, { raw: '0.0' }, culture);
return str[str.length - 2] || '.';
},
precision: function precision(format) {
return !format || format.maximumFractionDigits == null ? null : format.maximumFractionDigits;
}
};
return { date: date, number: number };
}
function oldGlobalize(globalize) {
var shortNames = Object.create(null);
function getCulture(culture) {
return culture ? globalize.findClosestCulture(culture) : globalize.culture();
}
function firstOfWeek(culture) {
culture = getCulture(culture);
return culture && culture.calendar.firstDay || 0;
}
function shortDay(dayOfTheWeek) {
var culture = getCulture(arguments[1]),
name = culture.name,
days = function days() {
return culture.calendar.days.namesShort.slice();
};
var names = shortNames[name] || (shortNames[name] = days());
return names[dayOfTheWeek.getDay()];
}
var date = {
formats: {
date: 'd',
time: 't',
'default': 'f',
header: 'MMMM yyyy',
footer: 'D',
weekday: shortDay,
dayOfMonth: 'dd',
month: 'MMM',
year: 'yyyy',
decade: function decade(dt, culture, l) {
return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfDecade(dt), l.formats.year, culture);
},
century: function century(dt, culture, l) {
return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfCentury(dt), l.formats.year, culture);
}
},
firstOfWeek: firstOfWeek,
parse: function parse(value, format, culture) {
return globalize.parseDate(value, format, culture);
},
format: function format(value, _format3, culture) {
return globalize.format(value, _format3, culture);
}
};
function formatData(format, _culture) {
var culture = getCulture(_culture),
numFormat = culture.numberFormat;
if (typeof format === 'string') {
if (format.indexOf('p') !== -1) numFormat = numFormat.percent;
if (format.indexOf('c') !== -1) numFormat = numFormat.curency;
}
return numFormat;
}
var number = {
formats: {
'default': 'D'
},
// TODO major bump consistent ordering
parse: function parse(value, culture) {
return globalize.parseFloat(value, 10, culture);
},
format: function format(value, _format4, culture) {
return globalize.format(value, _format4, culture);
},
decimalChar: function decimalChar(format, culture) {
var data = formatData(format, culture);
return data['.'] || '.';
},
precision: function precision(format, _culture) {
var data = formatData(format, _culture);
if (typeof format === 'string' && format.length > 1) return parseFloat(format.substr(1));
return data ? data.decimals : null;
}
};
return { date: date, number: number };
}
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports === "object") {
factory(exports);
} else {
factory(root.babelHelpers = {});
}
})(this, function (global) {
var babelHelpers = global;
babelHelpers.createDecoratedObject = function (descriptors) {
var target = {};
for (var i = 0; i < descriptors.length; i++) {
var descriptor = descriptors[i];
var decorators = descriptor.decorators;
var key = descriptor.key;
delete descriptor.key;
delete descriptor.decorators;
descriptor.enumerable = true;
descriptor.configurable = true;
if ("value" in descriptor || descriptor.initializer) descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {
var decorator = decorators[f];
if (typeof decorator === "function") {
descriptor = decorator(target, key, descriptor) || descriptor;
} else {
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
}
if (descriptor.initializer) {
descriptor.value = descriptor.initializer.call(target);
}
Object.defineProperty(target, key, descriptor);
}
return target;
};
babelHelpers.objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
babelHelpers.interopRequireWildcard = function (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;
}
};
babelHelpers.interopRequireDefault = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
babelHelpers._extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
})
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = window.React;
/***/ },
/* 4 */
/***/ function(module, exports) {
module.exports = window.ReactWidgets;
/***/ }
/******/ ]); |
src/components/User/SingleReview.js | andresmechali/shareify | import React from 'react';
import PropTypes from 'prop-types';
const SingleReview = (props) => {
console.log(props);
return (
<div>
<div className="ui-block-title">
<a href={`/user/${props.review.userFrom._id}`}>{`${props.review.userFrom.firstName} ${props.review.userFrom.lastName}`}</a>
<span style={{float: "right"}}>{props.review.rate}</span>
</div>
<div className="ui-block-content">
{props.review.comment}
</div>
</div>
)
};
SingleReview.propTypes = {
review: PropTypes.object.isRequired,
};
export default SingleReview; |
src/routes/contact/index.js | bmatthews/haze-lea | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import Contact from './Contact';
const title = 'Contact Us';
function action() {
return {
chunks: ['contact'],
title,
component: (
<Layout>
<Contact title={title} />
</Layout>
),
};
}
export default action;
|
ajax/libs/angular.js/0.9.2/angular-scenario.min.js | ComputerWolf/cdnjs | /*!
* jQuery JavaScript Library v1.4.2
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Sat Feb 13 22:33:48 2010 -0500
*/
(function(aM,C){var a=function(aY,aZ){return new a.fn.init(aY,aZ)},n=aM.jQuery,R=aM.$,ab=aM.document,X,P=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,aW=/^.[^:#\[\.,]*$/,ax=/\S/,M=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,e=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,b=navigator.userAgent,u,K=false,ad=[],aG,at=Object.prototype.toString,ap=Object.prototype.hasOwnProperty,g=Array.prototype.push,F=Array.prototype.slice,s=Array.prototype.indexOf;a.fn=a.prototype={init:function(aY,a1){var a0,a2,aZ,a3;if(!aY){return this}if(aY.nodeType){this.context=this[0]=aY;this.length=1;return this}if(aY==="body"&&!a1){this.context=ab;this[0]=ab.body;this.selector="body";this.length=1;return this}if(typeof aY==="string"){a0=P.exec(aY);if(a0&&(a0[1]||!a1)){if(a0[1]){a3=(a1?a1.ownerDocument||a1:ab);aZ=e.exec(aY);if(aZ){if(a.isPlainObject(a1)){aY=[ab.createElement(aZ[1])];a.fn.attr.call(aY,a1,true)}else{aY=[a3.createElement(aZ[1])]}}else{aZ=J([a0[1]],[a3]);aY=(aZ.cacheable?aZ.fragment.cloneNode(true):aZ.fragment).childNodes}return a.merge(this,aY)}else{a2=ab.getElementById(a0[2]);if(a2){if(a2.id!==a0[2]){return X.find(aY)}this.length=1;this[0]=a2}this.context=ab;this.selector=aY;return this}}else{if(!a1&&/^\w+$/.test(aY)){this.selector=aY;this.context=ab;aY=ab.getElementsByTagName(aY);return a.merge(this,aY)}else{if(!a1||a1.jquery){return(a1||X).find(aY)}else{return a(a1).find(aY)}}}}else{if(a.isFunction(aY)){return X.ready(aY)}}if(aY.selector!==C){this.selector=aY.selector;this.context=aY.context}return a.makeArray(aY,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(aY){return aY==null?this.toArray():(aY<0?this.slice(aY)[0]:this[aY])},pushStack:function(aZ,a1,aY){var a0=a();if(a.isArray(aZ)){g.apply(a0,aZ)}else{a.merge(a0,aZ)}a0.prevObject=this;a0.context=this.context;if(a1==="find"){a0.selector=this.selector+(this.selector?" ":"")+aY}else{if(a1){a0.selector=this.selector+"."+a1+"("+aY+")"}}return a0},each:function(aZ,aY){return a.each(this,aZ,aY)},ready:function(aY){a.bindReady();if(a.isReady){aY.call(ab,a)}else{if(ad){ad.push(aY)}}return this},eq:function(aY){return aY===-1?this.slice(aY):this.slice(aY,+aY+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(aY){return this.pushStack(a.map(this,function(a0,aZ){return aY.call(a0,aZ,a0)}))},end:function(){return this.prevObject||a(null)},push:g,sort:[].sort,splice:[].splice};a.fn.init.prototype=a.fn;a.extend=a.fn.extend=function(){var a3=arguments[0]||{},a2=1,a1=arguments.length,a5=false,a6,a0,aY,aZ;if(typeof a3==="boolean"){a5=a3;a3=arguments[1]||{};a2=2}if(typeof a3!=="object"&&!a.isFunction(a3)){a3={}}if(a1===a2){a3=this;--a2}for(;a2<a1;a2++){if((a6=arguments[a2])!=null){for(a0 in a6){aY=a3[a0];aZ=a6[a0];if(a3===aZ){continue}if(a5&&aZ&&(a.isPlainObject(aZ)||a.isArray(aZ))){var a4=aY&&(a.isPlainObject(aY)||a.isArray(aY))?aY:a.isArray(aZ)?[]:{};a3[a0]=a.extend(a5,a4,aZ)}else{if(aZ!==C){a3[a0]=aZ}}}}}return a3};a.extend({noConflict:function(aY){aM.$=R;if(aY){aM.jQuery=n}return a},isReady:false,ready:function(){if(!a.isReady){if(!ab.body){return setTimeout(a.ready,13)}a.isReady=true;if(ad){var aZ,aY=0;while((aZ=ad[aY++])){aZ.call(ab,a)}ad=null}if(a.fn.triggerHandler){a(ab).triggerHandler("ready")}}},bindReady:function(){if(K){return}K=true;if(ab.readyState==="complete"){return a.ready()}if(ab.addEventListener){ab.addEventListener("DOMContentLoaded",aG,false);aM.addEventListener("load",a.ready,false)}else{if(ab.attachEvent){ab.attachEvent("onreadystatechange",aG);aM.attachEvent("onload",a.ready);var aY=false;try{aY=aM.frameElement==null}catch(aZ){}if(ab.documentElement.doScroll&&aY){x()}}}},isFunction:function(aY){return at.call(aY)==="[object Function]"},isArray:function(aY){return at.call(aY)==="[object Array]"},isPlainObject:function(aZ){if(!aZ||at.call(aZ)!=="[object Object]"||aZ.nodeType||aZ.setInterval){return false}if(aZ.constructor&&!ap.call(aZ,"constructor")&&!ap.call(aZ.constructor.prototype,"isPrototypeOf")){return false}var aY;for(aY in aZ){}return aY===C||ap.call(aZ,aY)},isEmptyObject:function(aZ){for(var aY in aZ){return false}return true},error:function(aY){throw aY},parseJSON:function(aY){if(typeof aY!=="string"||!aY){return null}aY=a.trim(aY);if(/^[\],:{}\s]*$/.test(aY.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){return aM.JSON&&aM.JSON.parse?aM.JSON.parse(aY):(new Function("return "+aY))()}else{a.error("Invalid JSON: "+aY)}},noop:function(){},globalEval:function(a0){if(a0&&ax.test(a0)){var aZ=ab.getElementsByTagName("head")[0]||ab.documentElement,aY=ab.createElement("script");aY.type="text/javascript";if(a.support.scriptEval){aY.appendChild(ab.createTextNode(a0))}else{aY.text=a0}aZ.insertBefore(aY,aZ.firstChild);aZ.removeChild(aY)}},nodeName:function(aZ,aY){return aZ.nodeName&&aZ.nodeName.toUpperCase()===aY.toUpperCase()},each:function(a1,a5,a0){var aZ,a2=0,a3=a1.length,aY=a3===C||a.isFunction(a1);if(a0){if(aY){for(aZ in a1){if(a5.apply(a1[aZ],a0)===false){break}}}else{for(;a2<a3;){if(a5.apply(a1[a2++],a0)===false){break}}}}else{if(aY){for(aZ in a1){if(a5.call(a1[aZ],aZ,a1[aZ])===false){break}}}else{for(var a4=a1[0];a2<a3&&a5.call(a4,a2,a4)!==false;a4=a1[++a2]){}}}return a1},trim:function(aY){return(aY||"").replace(M,"")},makeArray:function(a0,aZ){var aY=aZ||[];if(a0!=null){if(a0.length==null||typeof a0==="string"||a.isFunction(a0)||(typeof a0!=="function"&&a0.setInterval)){g.call(aY,a0)}else{a.merge(aY,a0)}}return aY},inArray:function(a0,a1){if(a1.indexOf){return a1.indexOf(a0)}for(var aY=0,aZ=a1.length;aY<aZ;aY++){if(a1[aY]===a0){return aY}}return -1},merge:function(a2,a0){var a1=a2.length,aZ=0;if(typeof a0.length==="number"){for(var aY=a0.length;aZ<aY;aZ++){a2[a1++]=a0[aZ]}}else{while(a0[aZ]!==C){a2[a1++]=a0[aZ++]}}a2.length=a1;return a2},grep:function(aZ,a3,aY){var a0=[];for(var a1=0,a2=aZ.length;a1<a2;a1++){if(!aY!==!a3(aZ[a1],a1)){a0.push(aZ[a1])}}return a0},map:function(aZ,a4,aY){var a0=[],a3;for(var a1=0,a2=aZ.length;a1<a2;a1++){a3=a4(aZ[a1],a1,aY);if(a3!=null){a0[a0.length]=a3}}return a0.concat.apply([],a0)},guid:1,proxy:function(a0,aZ,aY){if(arguments.length===2){if(typeof aZ==="string"){aY=a0;a0=aY[aZ];aZ=C}else{if(aZ&&!a.isFunction(aZ)){aY=aZ;aZ=C}}}if(!aZ&&a0){aZ=function(){return a0.apply(aY||this,arguments)}}if(a0){aZ.guid=a0.guid=a0.guid||aZ.guid||a.guid++}return aZ},uaMatch:function(aZ){aZ=aZ.toLowerCase();var aY=/(webkit)[ \/]([\w.]+)/.exec(aZ)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(aZ)||/(msie) ([\w.]+)/.exec(aZ)||!/compatible/.test(aZ)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(aZ)||[];return{browser:aY[1]||"",version:aY[2]||"0"}},browser:{}});u=a.uaMatch(b);if(u.browser){a.browser[u.browser]=true;a.browser.version=u.version}if(a.browser.webkit){a.browser.safari=true}if(s){a.inArray=function(aY,aZ){return s.call(aZ,aY)}}X=a(ab);if(ab.addEventListener){aG=function(){ab.removeEventListener("DOMContentLoaded",aG,false);a.ready()}}else{if(ab.attachEvent){aG=function(){if(ab.readyState==="complete"){ab.detachEvent("onreadystatechange",aG);a.ready()}}}}function x(){if(a.isReady){return}try{ab.documentElement.doScroll("left")}catch(aY){setTimeout(x,1);return}a.ready()}function aV(aY,aZ){if(aZ.src){a.ajax({url:aZ.src,async:false,dataType:"script"})}else{a.globalEval(aZ.text||aZ.textContent||aZ.innerHTML||"")}if(aZ.parentNode){aZ.parentNode.removeChild(aZ)}}function an(aY,a6,a4,a0,a3,a5){var aZ=aY.length;if(typeof a6==="object"){for(var a1 in a6){an(aY,a1,a6[a1],a0,a3,a4)}return aY}if(a4!==C){a0=!a5&&a0&&a.isFunction(a4);for(var a2=0;a2<aZ;a2++){a3(aY[a2],a6,a0?a4.call(aY[a2],a2,a3(aY[a2],a6)):a4,a5)}return aY}return aZ?a3(aY[0],a6):C}function aP(){return(new Date).getTime()}(function(){a.support={};var a4=ab.documentElement,a3=ab.createElement("script"),aY=ab.createElement("div"),aZ="script"+aP();aY.style.display="none";aY.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var a6=aY.getElementsByTagName("*"),a5=aY.getElementsByTagName("a")[0];if(!a6||!a6.length||!a5){return}a.support={leadingWhitespace:aY.firstChild.nodeType===3,tbody:!aY.getElementsByTagName("tbody").length,htmlSerialize:!!aY.getElementsByTagName("link").length,style:/red/.test(a5.getAttribute("style")),hrefNormalized:a5.getAttribute("href")==="/a",opacity:/^0.55$/.test(a5.style.opacity),cssFloat:!!a5.style.cssFloat,checkOn:aY.getElementsByTagName("input")[0].value==="on",optSelected:ab.createElement("select").appendChild(ab.createElement("option")).selected,parentNode:aY.removeChild(aY.appendChild(ab.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};a3.type="text/javascript";try{a3.appendChild(ab.createTextNode("window."+aZ+"=1;"))}catch(a1){}a4.insertBefore(a3,a4.firstChild);if(aM[aZ]){a.support.scriptEval=true;delete aM[aZ]}try{delete a3.test}catch(a1){a.support.deleteExpando=false}a4.removeChild(a3);if(aY.attachEvent&&aY.fireEvent){aY.attachEvent("onclick",function a7(){a.support.noCloneEvent=false;aY.detachEvent("onclick",a7)});aY.cloneNode(true).fireEvent("onclick")}aY=ab.createElement("div");aY.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var a0=ab.createDocumentFragment();a0.appendChild(aY.firstChild);a.support.checkClone=a0.cloneNode(true).cloneNode(true).lastChild.checked;a(function(){var a8=ab.createElement("div");a8.style.width=a8.style.paddingLeft="1px";ab.body.appendChild(a8);a.boxModel=a.support.boxModel=a8.offsetWidth===2;ab.body.removeChild(a8).style.display="none";a8=null});var a2=function(a8){var ba=ab.createElement("div");a8="on"+a8;var a9=(a8 in ba);if(!a9){ba.setAttribute(a8,"return;");a9=typeof ba[a8]==="function"}ba=null;return a9};a.support.submitBubbles=a2("submit");a.support.changeBubbles=a2("change");a4=a3=aY=a6=a5=null})();a.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var aI="jQuery"+aP(),aH=0,aT={};a.extend({cache:{},expando:aI,noData:{embed:true,object:true,applet:true},data:function(a0,aZ,a2){if(a0.nodeName&&a.noData[a0.nodeName.toLowerCase()]){return}a0=a0==aM?aT:a0;var a3=a0[aI],aY=a.cache,a1;if(!a3&&typeof aZ==="string"&&a2===C){return null}if(!a3){a3=++aH}if(typeof aZ==="object"){a0[aI]=a3;a1=aY[a3]=a.extend(true,{},aZ)}else{if(!aY[a3]){a0[aI]=a3;aY[a3]={}}}a1=aY[a3];if(a2!==C){a1[aZ]=a2}return typeof aZ==="string"?a1[aZ]:a1},removeData:function(a0,aZ){if(a0.nodeName&&a.noData[a0.nodeName.toLowerCase()]){return}a0=a0==aM?aT:a0;var a2=a0[aI],aY=a.cache,a1=aY[a2];if(aZ){if(a1){delete a1[aZ];if(a.isEmptyObject(a1)){a.removeData(a0)}}}else{if(a.support.deleteExpando){delete a0[a.expando]}else{if(a0.removeAttribute){a0.removeAttribute(a.expando)}}delete aY[a2]}}});a.fn.extend({data:function(aY,a0){if(typeof aY==="undefined"&&this.length){return a.data(this[0])}else{if(typeof aY==="object"){return this.each(function(){a.data(this,aY)})}}var a1=aY.split(".");a1[1]=a1[1]?"."+a1[1]:"";if(a0===C){var aZ=this.triggerHandler("getData"+a1[1]+"!",[a1[0]]);if(aZ===C&&this.length){aZ=a.data(this[0],aY)}return aZ===C&&a1[1]?this.data(a1[0]):aZ}else{return this.trigger("setData"+a1[1]+"!",[a1[0],a0]).each(function(){a.data(this,aY,a0)})}},removeData:function(aY){return this.each(function(){a.removeData(this,aY)})}});a.extend({queue:function(aZ,aY,a1){if(!aZ){return}aY=(aY||"fx")+"queue";var a0=a.data(aZ,aY);if(!a1){return a0||[]}if(!a0||a.isArray(a1)){a0=a.data(aZ,aY,a.makeArray(a1))}else{a0.push(a1)}return a0},dequeue:function(a1,a0){a0=a0||"fx";var aY=a.queue(a1,a0),aZ=aY.shift();if(aZ==="inprogress"){aZ=aY.shift()}if(aZ){if(a0==="fx"){aY.unshift("inprogress")}aZ.call(a1,function(){a.dequeue(a1,a0)})}}});a.fn.extend({queue:function(aY,aZ){if(typeof aY!=="string"){aZ=aY;aY="fx"}if(aZ===C){return a.queue(this[0],aY)}return this.each(function(a1,a2){var a0=a.queue(this,aY,aZ);if(aY==="fx"&&a0[0]!=="inprogress"){a.dequeue(this,aY)}})},dequeue:function(aY){return this.each(function(){a.dequeue(this,aY)})},delay:function(aZ,aY){aZ=a.fx?a.fx.speeds[aZ]||aZ:aZ;aY=aY||"fx";return this.queue(aY,function(){var a0=this;setTimeout(function(){a.dequeue(a0,aY)},aZ)})},clearQueue:function(aY){return this.queue(aY||"fx",[])}});var ao=/[\n\t]/g,S=/\s+/,av=/\r/g,aQ=/href|src|style/,d=/(button|input)/i,z=/(button|input|object|select|textarea)/i,j=/^(a|area)$/i,I=/radio|checkbox/;a.fn.extend({attr:function(aY,aZ){return an(this,aY,aZ,true,a.attr)},removeAttr:function(aY,aZ){return this.each(function(){a.attr(this,aY,"");if(this.nodeType===1){this.removeAttribute(aY)}})},addClass:function(a5){if(a.isFunction(a5)){return this.each(function(a8){var a7=a(this);a7.addClass(a5.call(this,a8,a7.attr("class")))})}if(a5&&typeof a5==="string"){var aY=(a5||"").split(S);for(var a1=0,a0=this.length;a1<a0;a1++){var aZ=this[a1];if(aZ.nodeType===1){if(!aZ.className){aZ.className=a5}else{var a2=" "+aZ.className+" ",a4=aZ.className;for(var a3=0,a6=aY.length;a3<a6;a3++){if(a2.indexOf(" "+aY[a3]+" ")<0){a4+=" "+aY[a3]}}aZ.className=a.trim(a4)}}}}return this},removeClass:function(a3){if(a.isFunction(a3)){return this.each(function(a7){var a6=a(this);a6.removeClass(a3.call(this,a7,a6.attr("class")))})}if((a3&&typeof a3==="string")||a3===C){var a4=(a3||"").split(S);for(var a0=0,aZ=this.length;a0<aZ;a0++){var a2=this[a0];if(a2.nodeType===1&&a2.className){if(a3){var a1=(" "+a2.className+" ").replace(ao," ");for(var a5=0,aY=a4.length;a5<aY;a5++){a1=a1.replace(" "+a4[a5]+" "," ")}a2.className=a.trim(a1)}else{a2.className=""}}}}return this},toggleClass:function(a1,aZ){var a0=typeof a1,aY=typeof aZ==="boolean";if(a.isFunction(a1)){return this.each(function(a3){var a2=a(this);a2.toggleClass(a1.call(this,a3,a2.attr("class"),aZ),aZ)})}return this.each(function(){if(a0==="string"){var a4,a3=0,a2=a(this),a5=aZ,a6=a1.split(S);while((a4=a6[a3++])){a5=aY?a5:!a2.hasClass(a4);a2[a5?"addClass":"removeClass"](a4)}}else{if(a0==="undefined"||a0==="boolean"){if(this.className){a.data(this,"__className__",this.className)}this.className=this.className||a1===false?"":a.data(this,"__className__")||""}}})},hasClass:function(aY){var a1=" "+aY+" ";for(var a0=0,aZ=this.length;a0<aZ;a0++){if((" "+this[a0].className+" ").replace(ao," ").indexOf(a1)>-1){return true}}return false},val:function(a5){if(a5===C){var aZ=this[0];if(aZ){if(a.nodeName(aZ,"option")){return(aZ.attributes.value||{}).specified?aZ.value:aZ.text}if(a.nodeName(aZ,"select")){var a3=aZ.selectedIndex,a6=[],a7=aZ.options,a2=aZ.type==="select-one";if(a3<0){return null}for(var a0=a2?a3:0,a4=a2?a3+1:a7.length;a0<a4;a0++){var a1=a7[a0];if(a1.selected){a5=a(a1).val();if(a2){return a5}a6.push(a5)}}return a6}if(I.test(aZ.type)&&!a.support.checkOn){return aZ.getAttribute("value")===null?"on":aZ.value}return(aZ.value||"").replace(av,"")}return C}var aY=a.isFunction(a5);return this.each(function(ba){var a9=a(this),bb=a5;if(this.nodeType!==1){return}if(aY){bb=a5.call(this,ba,a9.val())}if(typeof bb==="number"){bb+=""}if(a.isArray(bb)&&I.test(this.type)){this.checked=a.inArray(a9.val(),bb)>=0}else{if(a.nodeName(this,"select")){var a8=a.makeArray(bb);a("option",this).each(function(){this.selected=a.inArray(a(this).val(),a8)>=0});if(!a8.length){this.selectedIndex=-1}}else{this.value=bb}}})}});a.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(aZ,aY,a4,a7){if(!aZ||aZ.nodeType===3||aZ.nodeType===8){return C}if(a7&&aY in a.attrFn){return a(aZ)[aY](a4)}var a0=aZ.nodeType!==1||!a.isXMLDoc(aZ),a3=a4!==C;aY=a0&&a.props[aY]||aY;if(aZ.nodeType===1){var a2=aQ.test(aY);if(aY==="selected"&&!a.support.optSelected){var a5=aZ.parentNode;if(a5){a5.selectedIndex;if(a5.parentNode){a5.parentNode.selectedIndex}}}if(aY in aZ&&a0&&!a2){if(a3){if(aY==="type"&&d.test(aZ.nodeName)&&aZ.parentNode){a.error("type property can't be changed")}aZ[aY]=a4}if(a.nodeName(aZ,"form")&&aZ.getAttributeNode(aY)){return aZ.getAttributeNode(aY).nodeValue}if(aY==="tabIndex"){var a6=aZ.getAttributeNode("tabIndex");return a6&&a6.specified?a6.value:z.test(aZ.nodeName)||j.test(aZ.nodeName)&&aZ.href?0:C}return aZ[aY]}if(!a.support.style&&a0&&aY==="style"){if(a3){aZ.style.cssText=""+a4}return aZ.style.cssText}if(a3){aZ.setAttribute(aY,""+a4)}var a1=!a.support.hrefNormalized&&a0&&a2?aZ.getAttribute(aY,2):aZ.getAttribute(aY);return a1===null?C:a1}return a.style(aZ,aY,a4)}});var aC=/\.(.*)$/,A=function(aY){return aY.replace(/[^\w\s\.\|`]/g,function(aZ){return"\\"+aZ})};a.event={add:function(a1,a5,ba,a3){if(a1.nodeType===3||a1.nodeType===8){return}if(a1.setInterval&&(a1!==aM&&!a1.frameElement)){a1=aM}var aZ,a9;if(ba.handler){aZ=ba;ba=aZ.handler}if(!ba.guid){ba.guid=a.guid++}var a6=a.data(a1);if(!a6){return}var bb=a6.events=a6.events||{},a4=a6.handle,a4;if(!a4){a6.handle=a4=function(){return typeof a!=="undefined"&&!a.event.triggered?a.event.handle.apply(a4.elem,arguments):C}}a4.elem=a1;a5=a5.split(" ");var a8,a2=0,aY;while((a8=a5[a2++])){a9=aZ?a.extend({},aZ):{handler:ba,data:a3};if(a8.indexOf(".")>-1){aY=a8.split(".");a8=aY.shift();a9.namespace=aY.slice(0).sort().join(".")}else{aY=[];a9.namespace=""}a9.type=a8;a9.guid=ba.guid;var a0=bb[a8],a7=a.event.special[a8]||{};if(!a0){a0=bb[a8]=[];if(!a7.setup||a7.setup.call(a1,a3,aY,a4)===false){if(a1.addEventListener){a1.addEventListener(a8,a4,false)}else{if(a1.attachEvent){a1.attachEvent("on"+a8,a4)}}}}if(a7.add){a7.add.call(a1,a9);if(!a9.handler.guid){a9.handler.guid=ba.guid}}a0.push(a9);a.event.global[a8]=true}a1=null},global:{},remove:function(bd,a8,aZ,a4){if(bd.nodeType===3||bd.nodeType===8){return}var bg,a3,a5,bb=0,a1,a6,a9,a2,a7,aY,bf,bc=a.data(bd),a0=bc&&bc.events;if(!bc||!a0){return}if(a8&&a8.type){aZ=a8.handler;a8=a8.type}if(!a8||typeof a8==="string"&&a8.charAt(0)==="."){a8=a8||"";for(a3 in a0){a.event.remove(bd,a3+a8)}return}a8=a8.split(" ");while((a3=a8[bb++])){bf=a3;aY=null;a1=a3.indexOf(".")<0;a6=[];if(!a1){a6=a3.split(".");a3=a6.shift();a9=new RegExp("(^|\\.)"+a.map(a6.slice(0).sort(),A).join("\\.(?:.*\\.)?")+"(\\.|$)")}a7=a0[a3];if(!a7){continue}if(!aZ){for(var ba=0;ba<a7.length;ba++){aY=a7[ba];if(a1||a9.test(aY.namespace)){a.event.remove(bd,bf,aY.handler,ba);a7.splice(ba--,1)}}continue}a2=a.event.special[a3]||{};for(var ba=a4||0;ba<a7.length;ba++){aY=a7[ba];if(aZ.guid===aY.guid){if(a1||a9.test(aY.namespace)){if(a4==null){a7.splice(ba--,1)}if(a2.remove){a2.remove.call(bd,aY)}}if(a4!=null){break}}}if(a7.length===0||a4!=null&&a7.length===1){if(!a2.teardown||a2.teardown.call(bd,a6)===false){ag(bd,a3,bc.handle)}bg=null;delete a0[a3]}}if(a.isEmptyObject(a0)){var be=bc.handle;if(be){be.elem=null}delete bc.events;delete bc.handle;if(a.isEmptyObject(bc)){a.removeData(bd)}}},trigger:function(aY,a2,a0){var a7=aY.type||aY,a1=arguments[3];if(!a1){aY=typeof aY==="object"?aY[aI]?aY:a.extend(a.Event(a7),aY):a.Event(a7);if(a7.indexOf("!")>=0){aY.type=a7=a7.slice(0,-1);aY.exclusive=true}if(!a0){aY.stopPropagation();if(a.event.global[a7]){a.each(a.cache,function(){if(this.events&&this.events[a7]){a.event.trigger(aY,a2,this.handle.elem)}})}}if(!a0||a0.nodeType===3||a0.nodeType===8){return C}aY.result=C;aY.target=a0;a2=a.makeArray(a2);a2.unshift(aY)}aY.currentTarget=a0;var a3=a.data(a0,"handle");if(a3){a3.apply(a0,a2)}var a8=a0.parentNode||a0.ownerDocument;try{if(!(a0&&a0.nodeName&&a.noData[a0.nodeName.toLowerCase()])){if(a0["on"+a7]&&a0["on"+a7].apply(a0,a2)===false){aY.result=false}}}catch(a5){}if(!aY.isPropagationStopped()&&a8){a.event.trigger(aY,a2,a8,true)}else{if(!aY.isDefaultPrevented()){var a4=aY.target,aZ,a9=a.nodeName(a4,"a")&&a7==="click",a6=a.event.special[a7]||{};if((!a6._default||a6._default.call(a0,aY)===false)&&!a9&&!(a4&&a4.nodeName&&a.noData[a4.nodeName.toLowerCase()])){try{if(a4[a7]){aZ=a4["on"+a7];if(aZ){a4["on"+a7]=null}a.event.triggered=true;a4[a7]()}}catch(a5){}if(aZ){a4["on"+a7]=aZ}a.event.triggered=false}}}},handle:function(aY){var a6,a0,aZ,a1,a7;aY=arguments[0]=a.event.fix(aY||aM.event);aY.currentTarget=this;a6=aY.type.indexOf(".")<0&&!aY.exclusive;if(!a6){aZ=aY.type.split(".");aY.type=aZ.shift();a1=new RegExp("(^|\\.)"+aZ.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}var a7=a.data(this,"events"),a0=a7[aY.type];if(a7&&a0){a0=a0.slice(0);for(var a3=0,a2=a0.length;a3<a2;a3++){var a5=a0[a3];if(a6||a1.test(a5.namespace)){aY.handler=a5.handler;aY.data=a5.data;aY.handleObj=a5;var a4=a5.handler.apply(this,arguments);if(a4!==C){aY.result=a4;if(a4===false){aY.preventDefault();aY.stopPropagation()}}if(aY.isImmediatePropagationStopped()){break}}}}return aY.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a1){if(a1[aI]){return a1}var aZ=a1;a1=a.Event(aZ);for(var a0=this.props.length,a3;a0;){a3=this.props[--a0];a1[a3]=aZ[a3]}if(!a1.target){a1.target=a1.srcElement||ab}if(a1.target.nodeType===3){a1.target=a1.target.parentNode}if(!a1.relatedTarget&&a1.fromElement){a1.relatedTarget=a1.fromElement===a1.target?a1.toElement:a1.fromElement}if(a1.pageX==null&&a1.clientX!=null){var a2=ab.documentElement,aY=ab.body;a1.pageX=a1.clientX+(a2&&a2.scrollLeft||aY&&aY.scrollLeft||0)-(a2&&a2.clientLeft||aY&&aY.clientLeft||0);a1.pageY=a1.clientY+(a2&&a2.scrollTop||aY&&aY.scrollTop||0)-(a2&&a2.clientTop||aY&&aY.clientTop||0)}if(!a1.which&&((a1.charCode||a1.charCode===0)?a1.charCode:a1.keyCode)){a1.which=a1.charCode||a1.keyCode}if(!a1.metaKey&&a1.ctrlKey){a1.metaKey=a1.ctrlKey}if(!a1.which&&a1.button!==C){a1.which=(a1.button&1?1:(a1.button&2?3:(a1.button&4?2:0)))}return a1},guid:100000000,proxy:a.proxy,special:{ready:{setup:a.bindReady,teardown:a.noop},live:{add:function(aY){a.event.add(this,aY.origType,a.extend({},aY,{handler:V}))},remove:function(aZ){var aY=true,a0=aZ.origType.replace(aC,"");a.each(a.data(this,"events").live||[],function(){if(a0===this.origType.replace(aC,"")){aY=false;return false}});if(aY){a.event.remove(this,aZ.origType,V)}}},beforeunload:{setup:function(a0,aZ,aY){if(this.setInterval){this.onbeforeunload=aY}return false},teardown:function(aZ,aY){if(this.onbeforeunload===aY){this.onbeforeunload=null}}}}};var ag=ab.removeEventListener?function(aZ,aY,a0){aZ.removeEventListener(aY,a0,false)}:function(aZ,aY,a0){aZ.detachEvent("on"+aY,a0)};a.Event=function(aY){if(!this.preventDefault){return new a.Event(aY)}if(aY&&aY.type){this.originalEvent=aY;this.type=aY.type}else{this.type=aY}this.timeStamp=aP();this[aI]=true};function aR(){return false}function f(){return true}a.Event.prototype={preventDefault:function(){this.isDefaultPrevented=f;var aY=this.originalEvent;if(!aY){return}if(aY.preventDefault){aY.preventDefault()}aY.returnValue=false},stopPropagation:function(){this.isPropagationStopped=f;var aY=this.originalEvent;if(!aY){return}if(aY.stopPropagation){aY.stopPropagation()}aY.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=f;this.stopPropagation()},isDefaultPrevented:aR,isPropagationStopped:aR,isImmediatePropagationStopped:aR};var Q=function(aZ){var aY=aZ.relatedTarget;try{while(aY&&aY!==this){aY=aY.parentNode}if(aY!==this){aZ.type=aZ.data;a.event.handle.apply(this,arguments)}}catch(a0){}},ay=function(aY){aY.type=aY.data;a.event.handle.apply(this,arguments)};a.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(aZ,aY){a.event.special[aZ]={setup:function(a0){a.event.add(this,aY,a0&&a0.selector?ay:Q,aZ)},teardown:function(a0){a.event.remove(this,aY,a0&&a0.selector?ay:Q)}}});if(!a.support.submitBubbles){a.event.special.submit={setup:function(aZ,aY){if(this.nodeName.toLowerCase()!=="form"){a.event.add(this,"click.specialSubmit",function(a2){var a1=a2.target,a0=a1.type;if((a0==="submit"||a0==="image")&&a(a1).closest("form").length){return aA("submit",this,arguments)}});a.event.add(this,"keypress.specialSubmit",function(a2){var a1=a2.target,a0=a1.type;if((a0==="text"||a0==="password")&&a(a1).closest("form").length&&a2.keyCode===13){return aA("submit",this,arguments)}})}else{return false}},teardown:function(aY){a.event.remove(this,".specialSubmit")}}}if(!a.support.changeBubbles){var aq=/textarea|input|select/i,aS,i=function(aZ){var aY=aZ.type,a0=aZ.value;if(aY==="radio"||aY==="checkbox"){a0=aZ.checked}else{if(aY==="select-multiple"){a0=aZ.selectedIndex>-1?a.map(aZ.options,function(a1){return a1.selected}).join("-"):""}else{if(aZ.nodeName.toLowerCase()==="select"){a0=aZ.selectedIndex}}}return a0},O=function O(a0){var aY=a0.target,aZ,a1;if(!aq.test(aY.nodeName)||aY.readOnly){return}aZ=a.data(aY,"_change_data");a1=i(aY);if(a0.type!=="focusout"||aY.type!=="radio"){a.data(aY,"_change_data",a1)}if(aZ===C||a1===aZ){return}if(aZ!=null||a1){a0.type="change";return a.event.trigger(a0,arguments[1],aY)}};a.event.special.change={filters:{focusout:O,click:function(a0){var aZ=a0.target,aY=aZ.type;if(aY==="radio"||aY==="checkbox"||aZ.nodeName.toLowerCase()==="select"){return O.call(this,a0)}},keydown:function(a0){var aZ=a0.target,aY=aZ.type;if((a0.keyCode===13&&aZ.nodeName.toLowerCase()!=="textarea")||(a0.keyCode===32&&(aY==="checkbox"||aY==="radio"))||aY==="select-multiple"){return O.call(this,a0)}},beforeactivate:function(aZ){var aY=aZ.target;a.data(aY,"_change_data",i(aY))}},setup:function(a0,aZ){if(this.type==="file"){return false}for(var aY in aS){a.event.add(this,aY+".specialChange",aS[aY])}return aq.test(this.nodeName)},teardown:function(aY){a.event.remove(this,".specialChange");return aq.test(this.nodeName)}};aS=a.event.special.change.filters}function aA(aZ,a0,aY){aY[0].type=aZ;return a.event.handle.apply(a0,aY)}if(ab.addEventListener){a.each({focus:"focusin",blur:"focusout"},function(a0,aY){a.event.special[aY]={setup:function(){this.addEventListener(a0,aZ,true)},teardown:function(){this.removeEventListener(a0,aZ,true)}};function aZ(a1){a1=a.event.fix(a1);a1.type=aY;return a.event.handle.call(this,a1)}})}a.each(["bind","one"],function(aZ,aY){a.fn[aY]=function(a5,a6,a4){if(typeof a5==="object"){for(var a2 in a5){this[aY](a2,a6,a5[a2],a4)}return this}if(a.isFunction(a6)){a4=a6;a6=C}var a3=aY==="one"?a.proxy(a4,function(a7){a(this).unbind(a7,a3);return a4.apply(this,arguments)}):a4;if(a5==="unload"&&aY!=="one"){this.one(a5,a6,a4)}else{for(var a1=0,a0=this.length;a1<a0;a1++){a.event.add(this[a1],a5,a3,a6)}}return this}});a.fn.extend({unbind:function(a2,a1){if(typeof a2==="object"&&!a2.preventDefault){for(var a0 in a2){this.unbind(a0,a2[a0])}}else{for(var aZ=0,aY=this.length;aZ<aY;aZ++){a.event.remove(this[aZ],a2,a1)}}return this},delegate:function(aY,aZ,a1,a0){return this.live(aZ,a1,a0,aY)},undelegate:function(aY,aZ,a0){if(arguments.length===0){return this.unbind("live")}else{return this.die(aZ,null,a0,aY)}},trigger:function(aY,aZ){return this.each(function(){a.event.trigger(aY,aZ,this)})},triggerHandler:function(aY,a0){if(this[0]){var aZ=a.Event(aY);aZ.preventDefault();aZ.stopPropagation();a.event.trigger(aZ,a0,this[0]);return aZ.result}},toggle:function(a0){var aY=arguments,aZ=1;while(aZ<aY.length){a.proxy(a0,aY[aZ++])}return this.click(a.proxy(a0,function(a1){var a2=(a.data(this,"lastToggle"+a0.guid)||0)%aZ;a.data(this,"lastToggle"+a0.guid,a2+1);a1.preventDefault();return aY[a2].apply(this,arguments)||false}))},hover:function(aY,aZ){return this.mouseenter(aY).mouseleave(aZ||aY)}});var aw={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};a.each(["live","die"],function(aZ,aY){a.fn[aY]=function(a7,a4,a9,a2){var a8,a5=0,a6,a1,ba,a3=a2||this.selector,a0=a2?this:a(this.context);if(a.isFunction(a4)){a9=a4;a4=C}a7=(a7||"").split(" ");while((a8=a7[a5++])!=null){a6=aC.exec(a8);a1="";if(a6){a1=a6[0];a8=a8.replace(aC,"")}if(a8==="hover"){a7.push("mouseenter"+a1,"mouseleave"+a1);continue}ba=a8;if(a8==="focus"||a8==="blur"){a7.push(aw[a8]+a1);a8=a8+a1}else{a8=(aw[a8]||a8)+a1}if(aY==="live"){a0.each(function(){a.event.add(this,m(a8,a3),{data:a4,selector:a3,handler:a9,origType:a8,origHandler:a9,preType:ba})})}else{a0.unbind(m(a8,a3),a9)}}return this}});function V(aY){var a8,aZ=[],bb=[],a7=arguments,ba,a6,a9,a1,a3,a5,a2,a4,bc=a.data(this,"events");if(aY.liveFired===this||!bc||!bc.live||aY.button&&aY.type==="click"){return}aY.liveFired=this;var a0=bc.live.slice(0);for(a3=0;a3<a0.length;a3++){a9=a0[a3];if(a9.origType.replace(aC,"")===aY.type){bb.push(a9.selector)}else{a0.splice(a3--,1)}}a6=a(aY.target).closest(bb,aY.currentTarget);for(a5=0,a2=a6.length;a5<a2;a5++){for(a3=0;a3<a0.length;a3++){a9=a0[a3];if(a6[a5].selector===a9.selector){a1=a6[a5].elem;ba=null;if(a9.preType==="mouseenter"||a9.preType==="mouseleave"){ba=a(aY.relatedTarget).closest(a9.selector)[0]}if(!ba||ba!==a1){aZ.push({elem:a1,handleObj:a9})}}}}for(a5=0,a2=aZ.length;a5<a2;a5++){a6=aZ[a5];aY.currentTarget=a6.elem;aY.data=a6.handleObj.data;aY.handleObj=a6.handleObj;if(a6.handleObj.origHandler.apply(a6.elem,a7)===false){a8=false;break}}return a8}function m(aZ,aY){return"live."+(aZ&&aZ!=="*"?aZ+".":"")+aY.replace(/\./g,"`").replace(/ /g,"&")}a.each(("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error").split(" "),function(aZ,aY){a.fn[aY]=function(a0){return a0?this.bind(aY,a0):this.trigger(aY)};if(a.attrFn){a.attrFn[aY]=true}});if(aM.attachEvent&&!aM.addEventListener){aM.attachEvent("onunload",function(){for(var aZ in a.cache){if(a.cache[aZ].handle){try{a.event.remove(a.cache[aZ].handle.elem)}catch(aY){}}}});
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
}(function(){var a9=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,ba=0,bc=Object.prototype.toString,a4=false,a3=true;[0,0].sort(function(){a3=false;return 0});var a0=function(bl,bg,bo,bp){bo=bo||[];var br=bg=bg||ab;if(bg.nodeType!==1&&bg.nodeType!==9){return[]}if(!bl||typeof bl!=="string"){return bo}var bm=[],bi,bt,bw,bh,bk=true,bj=a1(bg),bq=bl;while((a9.exec(""),bi=a9.exec(bq))!==null){bq=bi[3];bm.push(bi[1]);if(bi[2]){bh=bi[3];break}}if(bm.length>1&&a5.exec(bl)){if(bm.length===2&&a6.relative[bm[0]]){bt=bd(bm[0]+bm[1],bg)}else{bt=a6.relative[bm[0]]?[bg]:a0(bm.shift(),bg);while(bm.length){bl=bm.shift();if(a6.relative[bl]){bl+=bm.shift()}bt=bd(bl,bt)}}}else{if(!bp&&bm.length>1&&bg.nodeType===9&&!bj&&a6.match.ID.test(bm[0])&&!a6.match.ID.test(bm[bm.length-1])){var bs=a0.find(bm.shift(),bg,bj);bg=bs.expr?a0.filter(bs.expr,bs.set)[0]:bs.set[0]}if(bg){var bs=bp?{expr:bm.pop(),set:a8(bp)}:a0.find(bm.pop(),bm.length===1&&(bm[0]==="~"||bm[0]==="+")&&bg.parentNode?bg.parentNode:bg,bj);bt=bs.expr?a0.filter(bs.expr,bs.set):bs.set;if(bm.length>0){bw=a8(bt)}else{bk=false}while(bm.length){var bv=bm.pop(),bu=bv;if(!a6.relative[bv]){bv=""}else{bu=bm.pop()}if(bu==null){bu=bg}a6.relative[bv](bw,bu,bj)}}else{bw=bm=[]}}if(!bw){bw=bt}if(!bw){a0.error(bv||bl)}if(bc.call(bw)==="[object Array]"){if(!bk){bo.push.apply(bo,bw)}else{if(bg&&bg.nodeType===1){for(var bn=0;bw[bn]!=null;bn++){if(bw[bn]&&(bw[bn]===true||bw[bn].nodeType===1&&a7(bg,bw[bn]))){bo.push(bt[bn])}}}else{for(var bn=0;bw[bn]!=null;bn++){if(bw[bn]&&bw[bn].nodeType===1){bo.push(bt[bn])}}}}}else{a8(bw,bo)}if(bh){a0(bh,br,bo,bp);a0.uniqueSort(bo)}return bo};a0.uniqueSort=function(bh){if(bb){a4=a3;bh.sort(bb);if(a4){for(var bg=1;bg<bh.length;bg++){if(bh[bg]===bh[bg-1]){bh.splice(bg--,1)}}}}return bh};a0.matches=function(bg,bh){return a0(bg,null,null,bh)};a0.find=function(bn,bg,bo){var bm,bk;if(!bn){return[]}for(var bj=0,bi=a6.order.length;bj<bi;bj++){var bl=a6.order[bj],bk;if((bk=a6.leftMatch[bl].exec(bn))){var bh=bk[1];bk.splice(1,1);if(bh.substr(bh.length-1)!=="\\"){bk[1]=(bk[1]||"").replace(/\\/g,"");bm=a6.find[bl](bk,bg,bo);if(bm!=null){bn=bn.replace(a6.match[bl],"");break}}}}if(!bm){bm=bg.getElementsByTagName("*")}return{set:bm,expr:bn}};a0.filter=function(br,bq,bu,bk){var bi=br,bw=[],bo=bq,bm,bg,bn=bq&&bq[0]&&a1(bq[0]);while(br&&bq.length){for(var bp in a6.filter){if((bm=a6.leftMatch[bp].exec(br))!=null&&bm[2]){var bh=a6.filter[bp],bv,bt,bj=bm[1];bg=false;bm.splice(1,1);if(bj.substr(bj.length-1)==="\\"){continue}if(bo===bw){bw=[]}if(a6.preFilter[bp]){bm=a6.preFilter[bp](bm,bo,bu,bw,bk,bn);if(!bm){bg=bv=true}else{if(bm===true){continue}}}if(bm){for(var bl=0;(bt=bo[bl])!=null;bl++){if(bt){bv=bh(bt,bm,bl,bo);var bs=bk^!!bv;if(bu&&bv!=null){if(bs){bg=true}else{bo[bl]=false}}else{if(bs){bw.push(bt);bg=true}}}}}if(bv!==C){if(!bu){bo=bw}br=br.replace(a6.match[bp],"");if(!bg){return[]}break}}}if(br===bi){if(bg==null){a0.error(br)}else{break}}bi=br}return bo};a0.error=function(bg){throw"Syntax error, unrecognized expression: "+bg};var a6=a0.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(bg){return bg.getAttribute("href")}},relative:{"+":function(bm,bh){var bj=typeof bh==="string",bl=bj&&!/\W/.test(bh),bn=bj&&!bl;if(bl){bh=bh.toLowerCase()}for(var bi=0,bg=bm.length,bk;bi<bg;bi++){if((bk=bm[bi])){while((bk=bk.previousSibling)&&bk.nodeType!==1){}bm[bi]=bn||bk&&bk.nodeName.toLowerCase()===bh?bk||false:bk===bh}}if(bn){a0.filter(bh,bm,true)}},">":function(bm,bh){var bk=typeof bh==="string";if(bk&&!/\W/.test(bh)){bh=bh.toLowerCase();for(var bi=0,bg=bm.length;bi<bg;bi++){var bl=bm[bi];if(bl){var bj=bl.parentNode;bm[bi]=bj.nodeName.toLowerCase()===bh?bj:false}}}else{for(var bi=0,bg=bm.length;bi<bg;bi++){var bl=bm[bi];if(bl){bm[bi]=bk?bl.parentNode:bl.parentNode===bh}}if(bk){a0.filter(bh,bm,true)}}},"":function(bj,bh,bl){var bi=ba++,bg=be;if(typeof bh==="string"&&!/\W/.test(bh)){var bk=bh=bh.toLowerCase();bg=aY}bg("parentNode",bh,bi,bj,bk,bl)},"~":function(bj,bh,bl){var bi=ba++,bg=be;if(typeof bh==="string"&&!/\W/.test(bh)){var bk=bh=bh.toLowerCase();bg=aY}bg("previousSibling",bh,bi,bj,bk,bl)}},find:{ID:function(bh,bi,bj){if(typeof bi.getElementById!=="undefined"&&!bj){var bg=bi.getElementById(bh[1]);return bg?[bg]:[]}},NAME:function(bi,bl){if(typeof bl.getElementsByName!=="undefined"){var bh=[],bk=bl.getElementsByName(bi[1]);for(var bj=0,bg=bk.length;bj<bg;bj++){if(bk[bj].getAttribute("name")===bi[1]){bh.push(bk[bj])}}return bh.length===0?null:bh}},TAG:function(bg,bh){return bh.getElementsByTagName(bg[1])}},preFilter:{CLASS:function(bj,bh,bi,bg,bm,bn){bj=" "+bj[1].replace(/\\/g,"")+" ";if(bn){return bj}for(var bk=0,bl;(bl=bh[bk])!=null;bk++){if(bl){if(bm^(bl.className&&(" "+bl.className+" ").replace(/[\t\n]/g," ").indexOf(bj)>=0)){if(!bi){bg.push(bl)}}else{if(bi){bh[bk]=false}}}}return false},ID:function(bg){return bg[1].replace(/\\/g,"")},TAG:function(bh,bg){return bh[1].toLowerCase()},CHILD:function(bg){if(bg[1]==="nth"){var bh=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(bg[2]==="even"&&"2n"||bg[2]==="odd"&&"2n+1"||!/\D/.test(bg[2])&&"0n+"+bg[2]||bg[2]);bg[2]=(bh[1]+(bh[2]||1))-0;bg[3]=bh[3]-0}bg[0]=ba++;return bg},ATTR:function(bk,bh,bi,bg,bl,bm){var bj=bk[1].replace(/\\/g,"");if(!bm&&a6.attrMap[bj]){bk[1]=a6.attrMap[bj]}if(bk[2]==="~="){bk[4]=" "+bk[4]+" "}return bk},PSEUDO:function(bk,bh,bi,bg,bl){if(bk[1]==="not"){if((a9.exec(bk[3])||"").length>1||/^\w/.test(bk[3])){bk[3]=a0(bk[3],null,null,bh)}else{var bj=a0.filter(bk[3],bh,bi,true^bl);if(!bi){bg.push.apply(bg,bj)}return false}}else{if(a6.match.POS.test(bk[0])||a6.match.CHILD.test(bk[0])){return true}}return bk},POS:function(bg){bg.unshift(true);return bg}},filters:{enabled:function(bg){return bg.disabled===false&&bg.type!=="hidden"},disabled:function(bg){return bg.disabled===true},checked:function(bg){return bg.checked===true},selected:function(bg){bg.parentNode.selectedIndex;return bg.selected===true},parent:function(bg){return !!bg.firstChild},empty:function(bg){return !bg.firstChild},has:function(bi,bh,bg){return !!a0(bg[3],bi).length},header:function(bg){return/h\d/i.test(bg.nodeName)},text:function(bg){return"text"===bg.type},radio:function(bg){return"radio"===bg.type},checkbox:function(bg){return"checkbox"===bg.type},file:function(bg){return"file"===bg.type},password:function(bg){return"password"===bg.type},submit:function(bg){return"submit"===bg.type},image:function(bg){return"image"===bg.type},reset:function(bg){return"reset"===bg.type},button:function(bg){return"button"===bg.type||bg.nodeName.toLowerCase()==="button"},input:function(bg){return/input|select|textarea|button/i.test(bg.nodeName)}},setFilters:{first:function(bh,bg){return bg===0},last:function(bi,bh,bg,bj){return bh===bj.length-1},even:function(bh,bg){return bg%2===0},odd:function(bh,bg){return bg%2===1},lt:function(bi,bh,bg){return bh<bg[3]-0},gt:function(bi,bh,bg){return bh>bg[3]-0},nth:function(bi,bh,bg){return bg[3]-0===bh},eq:function(bi,bh,bg){return bg[3]-0===bh}},filter:{PSEUDO:function(bm,bi,bj,bn){var bh=bi[1],bk=a6.filters[bh];if(bk){return bk(bm,bj,bi,bn)}else{if(bh==="contains"){return(bm.textContent||bm.innerText||aZ([bm])||"").indexOf(bi[3])>=0}else{if(bh==="not"){var bl=bi[3];for(var bj=0,bg=bl.length;bj<bg;bj++){if(bl[bj]===bm){return false}}return true}else{a0.error("Syntax error, unrecognized expression: "+bh)}}}},CHILD:function(bg,bj){var bm=bj[1],bh=bg;switch(bm){case"only":case"first":while((bh=bh.previousSibling)){if(bh.nodeType===1){return false}}if(bm==="first"){return true}bh=bg;case"last":while((bh=bh.nextSibling)){if(bh.nodeType===1){return false}}return true;case"nth":var bi=bj[2],bp=bj[3];if(bi===1&&bp===0){return true}var bl=bj[0],bo=bg.parentNode;if(bo&&(bo.sizcache!==bl||!bg.nodeIndex)){var bk=0;for(bh=bo.firstChild;bh;bh=bh.nextSibling){if(bh.nodeType===1){bh.nodeIndex=++bk}}bo.sizcache=bl}var bn=bg.nodeIndex-bp;if(bi===0){return bn===0}else{return(bn%bi===0&&bn/bi>=0)}}},ID:function(bh,bg){return bh.nodeType===1&&bh.getAttribute("id")===bg},TAG:function(bh,bg){return(bg==="*"&&bh.nodeType===1)||bh.nodeName.toLowerCase()===bg},CLASS:function(bh,bg){return(" "+(bh.className||bh.getAttribute("class"))+" ").indexOf(bg)>-1},ATTR:function(bl,bj){var bi=bj[1],bg=a6.attrHandle[bi]?a6.attrHandle[bi](bl):bl[bi]!=null?bl[bi]:bl.getAttribute(bi),bm=bg+"",bk=bj[2],bh=bj[4];return bg==null?bk==="!=":bk==="="?bm===bh:bk==="*="?bm.indexOf(bh)>=0:bk==="~="?(" "+bm+" ").indexOf(bh)>=0:!bh?bm&&bg!==false:bk==="!="?bm!==bh:bk==="^="?bm.indexOf(bh)===0:bk==="$="?bm.substr(bm.length-bh.length)===bh:bk==="|="?bm===bh||bm.substr(0,bh.length+1)===bh+"-":false},POS:function(bk,bh,bi,bl){var bg=bh[2],bj=a6.setFilters[bg];if(bj){return bj(bk,bi,bh,bl)}}}};var a5=a6.match.POS;for(var a2 in a6.match){a6.match[a2]=new RegExp(a6.match[a2].source+/(?![^\[]*\])(?![^\(]*\))/.source);a6.leftMatch[a2]=new RegExp(/(^(?:.|\r|\n)*?)/.source+a6.match[a2].source.replace(/\\(\d+)/g,function(bh,bg){return"\\"+(bg-0+1)}))}var a8=function(bh,bg){bh=Array.prototype.slice.call(bh,0);if(bg){bg.push.apply(bg,bh);return bg}return bh};try{Array.prototype.slice.call(ab.documentElement.childNodes,0)[0].nodeType}catch(bf){a8=function(bk,bj){var bh=bj||[];if(bc.call(bk)==="[object Array]"){Array.prototype.push.apply(bh,bk)}else{if(typeof bk.length==="number"){for(var bi=0,bg=bk.length;bi<bg;bi++){bh.push(bk[bi])}}else{for(var bi=0;bk[bi];bi++){bh.push(bk[bi])}}}return bh}}var bb;if(ab.documentElement.compareDocumentPosition){bb=function(bh,bg){if(!bh.compareDocumentPosition||!bg.compareDocumentPosition){if(bh==bg){a4=true}return bh.compareDocumentPosition?-1:1}var bi=bh.compareDocumentPosition(bg)&4?-1:bh===bg?0:1;if(bi===0){a4=true}return bi}}else{if("sourceIndex" in ab.documentElement){bb=function(bh,bg){if(!bh.sourceIndex||!bg.sourceIndex){if(bh==bg){a4=true}return bh.sourceIndex?-1:1}var bi=bh.sourceIndex-bg.sourceIndex;if(bi===0){a4=true}return bi}}else{if(ab.createRange){bb=function(bj,bh){if(!bj.ownerDocument||!bh.ownerDocument){if(bj==bh){a4=true}return bj.ownerDocument?-1:1}var bi=bj.ownerDocument.createRange(),bg=bh.ownerDocument.createRange();bi.setStart(bj,0);bi.setEnd(bj,0);bg.setStart(bh,0);bg.setEnd(bh,0);var bk=bi.compareBoundaryPoints(Range.START_TO_END,bg);if(bk===0){a4=true}return bk}}}}function aZ(bg){var bh="",bj;for(var bi=0;bg[bi];bi++){bj=bg[bi];if(bj.nodeType===3||bj.nodeType===4){bh+=bj.nodeValue}else{if(bj.nodeType!==8){bh+=aZ(bj.childNodes)}}}return bh}(function(){var bh=ab.createElement("div"),bi="script"+(new Date).getTime();bh.innerHTML="<a name='"+bi+"'/>";var bg=ab.documentElement;bg.insertBefore(bh,bg.firstChild);if(ab.getElementById(bi)){a6.find.ID=function(bk,bl,bm){if(typeof bl.getElementById!=="undefined"&&!bm){var bj=bl.getElementById(bk[1]);return bj?bj.id===bk[1]||typeof bj.getAttributeNode!=="undefined"&&bj.getAttributeNode("id").nodeValue===bk[1]?[bj]:C:[]}};a6.filter.ID=function(bl,bj){var bk=typeof bl.getAttributeNode!=="undefined"&&bl.getAttributeNode("id");return bl.nodeType===1&&bk&&bk.nodeValue===bj}}bg.removeChild(bh);bg=bh=null})();(function(){var bg=ab.createElement("div");bg.appendChild(ab.createComment(""));if(bg.getElementsByTagName("*").length>0){a6.find.TAG=function(bh,bl){var bk=bl.getElementsByTagName(bh[1]);if(bh[1]==="*"){var bj=[];for(var bi=0;bk[bi];bi++){if(bk[bi].nodeType===1){bj.push(bk[bi])}}bk=bj}return bk}}bg.innerHTML="<a href='#'></a>";if(bg.firstChild&&typeof bg.firstChild.getAttribute!=="undefined"&&bg.firstChild.getAttribute("href")!=="#"){a6.attrHandle.href=function(bh){return bh.getAttribute("href",2)}}bg=null})();if(ab.querySelectorAll){(function(){var bg=a0,bi=ab.createElement("div");bi.innerHTML="<p class='TEST'></p>";if(bi.querySelectorAll&&bi.querySelectorAll(".TEST").length===0){return}a0=function(bm,bl,bj,bk){bl=bl||ab;if(!bk&&bl.nodeType===9&&!a1(bl)){try{return a8(bl.querySelectorAll(bm),bj)}catch(bn){}}return bg(bm,bl,bj,bk)};for(var bh in bg){a0[bh]=bg[bh]}bi=null})()}(function(){var bg=ab.createElement("div");bg.innerHTML="<div class='test e'></div><div class='test'></div>";if(!bg.getElementsByClassName||bg.getElementsByClassName("e").length===0){return}bg.lastChild.className="e";if(bg.getElementsByClassName("e").length===1){return}a6.order.splice(1,0,"CLASS");a6.find.CLASS=function(bh,bi,bj){if(typeof bi.getElementsByClassName!=="undefined"&&!bj){return bi.getElementsByClassName(bh[1])}};bg=null})();function aY(bh,bm,bl,bp,bn,bo){for(var bj=0,bi=bp.length;bj<bi;bj++){var bg=bp[bj];if(bg){bg=bg[bh];var bk=false;while(bg){if(bg.sizcache===bl){bk=bp[bg.sizset];break}if(bg.nodeType===1&&!bo){bg.sizcache=bl;bg.sizset=bj}if(bg.nodeName.toLowerCase()===bm){bk=bg;break}bg=bg[bh]}bp[bj]=bk}}}function be(bh,bm,bl,bp,bn,bo){for(var bj=0,bi=bp.length;bj<bi;bj++){var bg=bp[bj];if(bg){bg=bg[bh];var bk=false;while(bg){if(bg.sizcache===bl){bk=bp[bg.sizset];break}if(bg.nodeType===1){if(!bo){bg.sizcache=bl;bg.sizset=bj}if(typeof bm!=="string"){if(bg===bm){bk=true;break}}else{if(a0.filter(bm,[bg]).length>0){bk=bg;break}}}bg=bg[bh]}bp[bj]=bk}}}var a7=ab.compareDocumentPosition?function(bh,bg){return !!(bh.compareDocumentPosition(bg)&16)}:function(bh,bg){return bh!==bg&&(bh.contains?bh.contains(bg):true)};var a1=function(bg){var bh=(bg?bg.ownerDocument||bg:0).documentElement;return bh?bh.nodeName!=="HTML":false};var bd=function(bg,bn){var bj=[],bk="",bl,bi=bn.nodeType?[bn]:bn;while((bl=a6.match.PSEUDO.exec(bg))){bk+=bl[0];bg=bg.replace(a6.match.PSEUDO,"")}bg=a6.relative[bg]?bg+"*":bg;for(var bm=0,bh=bi.length;bm<bh;bm++){a0(bg,bi[bm],bj)}return a0.filter(bk,bj)};a.find=a0;a.expr=a0.selectors;a.expr[":"]=a.expr.filters;a.unique=a0.uniqueSort;a.text=aZ;a.isXMLDoc=a1;a.contains=a7;return;aM.Sizzle=a0})();var N=/Until$/,Y=/^(?:parents|prevUntil|prevAll)/,aL=/,/,F=Array.prototype.slice;var ai=function(a1,a0,aY){if(a.isFunction(a0)){return a.grep(a1,function(a3,a2){return !!a0.call(a3,a2,a3)===aY})}else{if(a0.nodeType){return a.grep(a1,function(a3,a2){return(a3===a0)===aY})}else{if(typeof a0==="string"){var aZ=a.grep(a1,function(a2){return a2.nodeType===1});if(aW.test(a0)){return a.filter(a0,aZ,!aY)}else{a0=a.filter(a0,aZ)}}}}return a.grep(a1,function(a3,a2){return(a.inArray(a3,a0)>=0)===aY})};a.fn.extend({find:function(aY){var a0=this.pushStack("","find",aY),a3=0;for(var a1=0,aZ=this.length;a1<aZ;a1++){a3=a0.length;a.find(aY,this[a1],a0);if(a1>0){for(var a4=a3;a4<a0.length;a4++){for(var a2=0;a2<a3;a2++){if(a0[a2]===a0[a4]){a0.splice(a4--,1);break}}}}}return a0},has:function(aZ){var aY=a(aZ);return this.filter(function(){for(var a1=0,a0=aY.length;a1<a0;a1++){if(a.contains(this,aY[a1])){return true}}})},not:function(aY){return this.pushStack(ai(this,aY,false),"not",aY)},filter:function(aY){return this.pushStack(ai(this,aY,true),"filter",aY)},is:function(aY){return !!aY&&a.filter(aY,this).length>0},closest:function(a7,aY){if(a.isArray(a7)){var a4=[],a6=this[0],a3,a2={},a0;if(a6&&a7.length){for(var a1=0,aZ=a7.length;a1<aZ;a1++){a0=a7[a1];if(!a2[a0]){a2[a0]=a.expr.match.POS.test(a0)?a(a0,aY||this.context):a0}}while(a6&&a6.ownerDocument&&a6!==aY){for(a0 in a2){a3=a2[a0];if(a3.jquery?a3.index(a6)>-1:a(a6).is(a3)){a4.push({selector:a0,elem:a6});delete a2[a0]}}a6=a6.parentNode}}return a4}var a5=a.expr.match.POS.test(a7)?a(a7,aY||this.context):null;return this.map(function(a8,a9){while(a9&&a9.ownerDocument&&a9!==aY){if(a5?a5.index(a9)>-1:a(a9).is(a7)){return a9}a9=a9.parentNode}return null})},index:function(aY){if(!aY||typeof aY==="string"){return a.inArray(this[0],aY?a(aY):this.parent().children())}return a.inArray(aY.jquery?aY[0]:aY,this)},add:function(aY,aZ){var a1=typeof aY==="string"?a(aY,aZ||this.context):a.makeArray(aY),a0=a.merge(this.get(),a1);return this.pushStack(y(a1[0])||y(a0[0])?a0:a.unique(a0))},andSelf:function(){return this.add(this.prevObject)}});function y(aY){return !aY||!aY.parentNode||aY.parentNode.nodeType===11}a.each({parent:function(aZ){var aY=aZ.parentNode;return aY&&aY.nodeType!==11?aY:null},parents:function(aY){return a.dir(aY,"parentNode")},parentsUntil:function(aZ,aY,a0){return a.dir(aZ,"parentNode",a0)},next:function(aY){return a.nth(aY,2,"nextSibling")},prev:function(aY){return a.nth(aY,2,"previousSibling")},nextAll:function(aY){return a.dir(aY,"nextSibling")},prevAll:function(aY){return a.dir(aY,"previousSibling")},nextUntil:function(aZ,aY,a0){return a.dir(aZ,"nextSibling",a0)},prevUntil:function(aZ,aY,a0){return a.dir(aZ,"previousSibling",a0)},siblings:function(aY){return a.sibling(aY.parentNode.firstChild,aY)},children:function(aY){return a.sibling(aY.firstChild)},contents:function(aY){return a.nodeName(aY,"iframe")?aY.contentDocument||aY.contentWindow.document:a.makeArray(aY.childNodes)}},function(aY,aZ){a.fn[aY]=function(a2,a0){var a1=a.map(this,aZ,a2);if(!N.test(aY)){a0=a2}if(a0&&typeof a0==="string"){a1=a.filter(a0,a1)}a1=this.length>1?a.unique(a1):a1;if((this.length>1||aL.test(a0))&&Y.test(aY)){a1=a1.reverse()}return this.pushStack(a1,aY,F.call(arguments).join(","))}});a.extend({filter:function(a0,aY,aZ){if(aZ){a0=":not("+a0+")"}return a.find.matches(a0,aY)},dir:function(a0,aZ,a2){var aY=[],a1=a0[aZ];while(a1&&a1.nodeType!==9&&(a2===C||a1.nodeType!==1||!a(a1).is(a2))){if(a1.nodeType===1){aY.push(a1)}a1=a1[aZ]}return aY},nth:function(a2,aY,a0,a1){aY=aY||1;var aZ=0;for(;a2;a2=a2[a0]){if(a2.nodeType===1&&++aZ===aY){break}}return a2},sibling:function(a0,aZ){var aY=[];for(;a0;a0=a0.nextSibling){if(a0.nodeType===1&&a0!==aZ){aY.push(a0)}}return aY}});var T=/ jQuery\d+="(?:\d+|null)"/g,Z=/^\s+/,H=/(<([\w:]+)[^>]*?)\/>/g,al=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,c=/<([\w:]+)/,t=/<tbody/i,L=/<|&#?\w+;/,E=/<script|<object|<embed|<option|<style/i,l=/checked\s*(?:[^=]|=\s*.checked.)/i,p=function(aZ,a0,aY){return al.test(aY)?aZ:a0+"></"+aY+">"},ac={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};ac.optgroup=ac.option;ac.tbody=ac.tfoot=ac.colgroup=ac.caption=ac.thead;ac.th=ac.td;if(!a.support.htmlSerialize){ac._default=[1,"div<div>","</div>"]}a.fn.extend({text:function(aY){if(a.isFunction(aY)){return this.each(function(a0){var aZ=a(this);aZ.text(aY.call(this,a0,aZ.text()))})}if(typeof aY!=="object"&&aY!==C){return this.empty().append((this[0]&&this[0].ownerDocument||ab).createTextNode(aY))}return a.text(this)},wrapAll:function(aY){if(a.isFunction(aY)){return this.each(function(a0){a(this).wrapAll(aY.call(this,a0))})}if(this[0]){var aZ=a(aY,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){aZ.insertBefore(this[0])}aZ.map(function(){var a0=this;while(a0.firstChild&&a0.firstChild.nodeType===1){a0=a0.firstChild}return a0}).append(this)}return this},wrapInner:function(aY){if(a.isFunction(aY)){return this.each(function(aZ){a(this).wrapInner(aY.call(this,aZ))})}return this.each(function(){var aZ=a(this),a0=aZ.contents();if(a0.length){a0.wrapAll(aY)}else{aZ.append(aY)}})},wrap:function(aY){return this.each(function(){a(this).wrapAll(aY)})},unwrap:function(){return this.parent().each(function(){if(!a.nodeName(this,"body")){a(this).replaceWith(this.childNodes)}}).end()},append:function(){return this.domManip(arguments,true,function(aY){if(this.nodeType===1){this.appendChild(aY)}})},prepend:function(){return this.domManip(arguments,true,function(aY){if(this.nodeType===1){this.insertBefore(aY,this.firstChild)}})},before:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(aZ){this.parentNode.insertBefore(aZ,this)})}else{if(arguments.length){var aY=a(arguments[0]);aY.push.apply(aY,this.toArray());return this.pushStack(aY,"before",arguments)}}},after:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(aZ){this.parentNode.insertBefore(aZ,this.nextSibling)})}else{if(arguments.length){var aY=this.pushStack(this,"after",arguments);aY.push.apply(aY,a(arguments[0]).toArray());return aY}}},remove:function(aY,a1){for(var aZ=0,a0;(a0=this[aZ])!=null;aZ++){if(!aY||a.filter(aY,[a0]).length){if(!a1&&a0.nodeType===1){a.cleanData(a0.getElementsByTagName("*"));a.cleanData([a0])}if(a0.parentNode){a0.parentNode.removeChild(a0)}}}return this},empty:function(){for(var aY=0,aZ;(aZ=this[aY])!=null;aY++){if(aZ.nodeType===1){a.cleanData(aZ.getElementsByTagName("*"))}while(aZ.firstChild){aZ.removeChild(aZ.firstChild)}}return this},clone:function(aZ){var aY=this.map(function(){if(!a.support.noCloneEvent&&!a.isXMLDoc(this)){var a1=this.outerHTML,a0=this.ownerDocument;if(!a1){var a2=a0.createElement("div");a2.appendChild(this.cloneNode(true));a1=a2.innerHTML}return a.clean([a1.replace(T,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(Z,"")],a0)[0]}else{return this.cloneNode(true)}});if(aZ===true){q(this,aY);q(this.find("*"),aY.find("*"))}return aY},html:function(a0){if(a0===C){return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(T,""):null}else{if(typeof a0==="string"&&!E.test(a0)&&(a.support.leadingWhitespace||!Z.test(a0))&&!ac[(c.exec(a0)||["",""])[1].toLowerCase()]){a0=a0.replace(H,p);try{for(var aZ=0,aY=this.length;aZ<aY;aZ++){if(this[aZ].nodeType===1){a.cleanData(this[aZ].getElementsByTagName("*"));this[aZ].innerHTML=a0}}}catch(a1){this.empty().append(a0)}}else{if(a.isFunction(a0)){this.each(function(a4){var a3=a(this),a2=a3.html();a3.empty().append(function(){return a0.call(this,a4,a2)})})}else{this.empty().append(a0)}}}return this},replaceWith:function(aY){if(this[0]&&this[0].parentNode){if(a.isFunction(aY)){return this.each(function(a1){var a0=a(this),aZ=a0.html();a0.replaceWith(aY.call(this,a1,aZ))})}if(typeof aY!=="string"){aY=a(aY).detach()}return this.each(function(){var a0=this.nextSibling,aZ=this.parentNode;a(this).remove();if(a0){a(a0).before(aY)}else{a(aZ).append(aY)}})}else{return this.pushStack(a(a.isFunction(aY)?aY():aY),"replaceWith",aY)}},detach:function(aY){return this.remove(aY,true)},domManip:function(a4,a9,a8){var a1,a2,a7=a4[0],aZ=[],a3,a6;if(!a.support.checkClone&&arguments.length===3&&typeof a7==="string"&&l.test(a7)){return this.each(function(){a(this).domManip(a4,a9,a8,true)})}if(a.isFunction(a7)){return this.each(function(bb){var ba=a(this);a4[0]=a7.call(this,bb,a9?ba.html():C);ba.domManip(a4,a9,a8)})}if(this[0]){a6=a7&&a7.parentNode;if(a.support.parentNode&&a6&&a6.nodeType===11&&a6.childNodes.length===this.length){a1={fragment:a6}}else{a1=J(a4,this,aZ)}a3=a1.fragment;if(a3.childNodes.length===1){a2=a3=a3.firstChild}else{a2=a3.firstChild}if(a2){a9=a9&&a.nodeName(a2,"tr");for(var a0=0,aY=this.length;a0<aY;a0++){a8.call(a9?a5(this[a0],a2):this[a0],a0>0||a1.cacheable||this.length>1?a3.cloneNode(true):a3)}}if(aZ.length){a.each(aZ,aV)}}return this;function a5(ba,bb){return a.nodeName(ba,"table")?(ba.getElementsByTagName("tbody")[0]||ba.appendChild(ba.ownerDocument.createElement("tbody"))):ba}}});function q(a0,aY){var aZ=0;aY.each(function(){if(this.nodeName!==(a0[aZ]&&a0[aZ].nodeName)){return}var a5=a.data(a0[aZ++]),a4=a.data(this,a5),a1=a5&&a5.events;if(a1){delete a4.handle;a4.events={};for(var a3 in a1){for(var a2 in a1[a3]){a.event.add(this,a3,a1[a3][a2],a1[a3][a2].data)}}}})}function J(a3,a1,aZ){var a2,aY,a0,a4=(a1&&a1[0]?a1[0].ownerDocument||a1[0]:ab);if(a3.length===1&&typeof a3[0]==="string"&&a3[0].length<512&&a4===ab&&!E.test(a3[0])&&(a.support.checkClone||!l.test(a3[0]))){aY=true;a0=a.fragments[a3[0]];if(a0){if(a0!==1){a2=a0}}}if(!a2){a2=a4.createDocumentFragment();a.clean(a3,a4,a2,aZ)}if(aY){a.fragments[a3[0]]=a0?a2:1}return{fragment:a2,cacheable:aY}}a.fragments={};a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(aY,aZ){a.fn[aY]=function(a0){var a3=[],a6=a(a0),a5=this.length===1&&this[0].parentNode;if(a5&&a5.nodeType===11&&a5.childNodes.length===1&&a6.length===1){a6[aZ](this[0]);return this}else{for(var a4=0,a1=a6.length;a4<a1;a4++){var a2=(a4>0?this.clone(true):this).get();a.fn[aZ].apply(a(a6[a4]),a2);a3=a3.concat(a2)}return this.pushStack(a3,aY,a6.selector)}}});a.extend({clean:function(a0,a2,a9,a4){a2=a2||ab;if(typeof a2.createElement==="undefined"){a2=a2.ownerDocument||a2[0]&&a2[0].ownerDocument||ab}var ba=[];for(var a8=0,a3;(a3=a0[a8])!=null;a8++){if(typeof a3==="number"){a3+=""}if(!a3){continue}if(typeof a3==="string"&&!L.test(a3)){a3=a2.createTextNode(a3)}else{if(typeof a3==="string"){a3=a3.replace(H,p);var bb=(c.exec(a3)||["",""])[1].toLowerCase(),a1=ac[bb]||ac._default,a7=a1[0],aZ=a2.createElement("div");aZ.innerHTML=a1[1]+a3+a1[2];while(a7--){aZ=aZ.lastChild}if(!a.support.tbody){var aY=t.test(a3),a6=bb==="table"&&!aY?aZ.firstChild&&aZ.firstChild.childNodes:a1[1]==="<table>"&&!aY?aZ.childNodes:[];for(var a5=a6.length-1;a5>=0;--a5){if(a.nodeName(a6[a5],"tbody")&&!a6[a5].childNodes.length){a6[a5].parentNode.removeChild(a6[a5])}}}if(!a.support.leadingWhitespace&&Z.test(a3)){aZ.insertBefore(a2.createTextNode(Z.exec(a3)[0]),aZ.firstChild)}a3=aZ.childNodes}}if(a3.nodeType){ba.push(a3)}else{ba=a.merge(ba,a3)}}if(a9){for(var a8=0;ba[a8];a8++){if(a4&&a.nodeName(ba[a8],"script")&&(!ba[a8].type||ba[a8].type.toLowerCase()==="text/javascript")){a4.push(ba[a8].parentNode?ba[a8].parentNode.removeChild(ba[a8]):ba[a8])}else{if(ba[a8].nodeType===1){ba.splice.apply(ba,[a8+1,0].concat(a.makeArray(ba[a8].getElementsByTagName("script"))))}a9.appendChild(ba[a8])}}}return ba},cleanData:function(aZ){var a2,a0,aY=a.cache,a5=a.event.special,a4=a.support.deleteExpando;for(var a3=0,a1;(a1=aZ[a3])!=null;a3++){a0=a1[a.expando];if(a0){a2=aY[a0];if(a2.events){for(var a6 in a2.events){if(a5[a6]){a.event.remove(a1,a6)}else{ag(a1,a6,a2.handle)}}}if(a4){delete a1[a.expando]}else{if(a1.removeAttribute){a1.removeAttribute(a.expando)}}delete aY[a0]}}}});var ar=/z-?index|font-?weight|opacity|zoom|line-?height/i,U=/alpha\([^)]*\)/,aa=/opacity=([^)]*)/,ah=/float/i,az=/-([a-z])/ig,v=/([A-Z])/g,aO=/^-?\d+(?:px)?$/i,aU=/^-?\d/,aK={position:"absolute",visibility:"hidden",display:"block"},W=["Left","Right"],aE=["Top","Bottom"],ak=ab.defaultView&&ab.defaultView.getComputedStyle,aN=a.support.cssFloat?"cssFloat":"styleFloat",k=function(aY,aZ){return aZ.toUpperCase()};a.fn.css=function(aY,aZ){return an(this,aY,aZ,true,function(a1,a0,a2){if(a2===C){return a.curCSS(a1,a0)}if(typeof a2==="number"&&!ar.test(a0)){a2+="px"}a.style(a1,a0,a2)})};a.extend({style:function(a2,aZ,a3){if(!a2||a2.nodeType===3||a2.nodeType===8){return C}if((aZ==="width"||aZ==="height")&&parseFloat(a3)<0){a3=C}var a1=a2.style||a2,a4=a3!==C;if(!a.support.opacity&&aZ==="opacity"){if(a4){a1.zoom=1;var aY=parseInt(a3,10)+""==="NaN"?"":"alpha(opacity="+a3*100+")";var a0=a1.filter||a.curCSS(a2,"filter")||"";a1.filter=U.test(a0)?a0.replace(U,aY):aY}return a1.filter&&a1.filter.indexOf("opacity=")>=0?(parseFloat(aa.exec(a1.filter)[1])/100)+"":""}if(ah.test(aZ)){aZ=aN}aZ=aZ.replace(az,k);if(a4){a1[aZ]=a3}return a1[aZ]},css:function(a1,aZ,a3,aY){if(aZ==="width"||aZ==="height"){var a5,a0=aK,a4=aZ==="width"?W:aE;function a2(){a5=aZ==="width"?a1.offsetWidth:a1.offsetHeight;if(aY==="border"){return}a.each(a4,function(){if(!aY){a5-=parseFloat(a.curCSS(a1,"padding"+this,true))||0}if(aY==="margin"){a5+=parseFloat(a.curCSS(a1,"margin"+this,true))||0}else{a5-=parseFloat(a.curCSS(a1,"border"+this+"Width",true))||0}})}if(a1.offsetWidth!==0){a2()}else{a.swap(a1,a0,a2)}return Math.max(0,Math.round(a5))}return a.curCSS(a1,aZ,a3)},curCSS:function(a4,aZ,a0){var a7,aY=a4.style,a1;if(!a.support.opacity&&aZ==="opacity"&&a4.currentStyle){a7=aa.test(a4.currentStyle.filter||"")?(parseFloat(RegExp.$1)/100)+"":"";return a7===""?"1":a7}if(ah.test(aZ)){aZ=aN}if(!a0&&aY&&aY[aZ]){a7=aY[aZ]}else{if(ak){if(ah.test(aZ)){aZ="float"}aZ=aZ.replace(v,"-$1").toLowerCase();var a6=a4.ownerDocument.defaultView;if(!a6){return null}var a8=a6.getComputedStyle(a4,null);if(a8){a7=a8.getPropertyValue(aZ)}if(aZ==="opacity"&&a7===""){a7="1"}}else{if(a4.currentStyle){var a3=aZ.replace(az,k);a7=a4.currentStyle[aZ]||a4.currentStyle[a3];if(!aO.test(a7)&&aU.test(a7)){var a2=aY.left,a5=a4.runtimeStyle.left;a4.runtimeStyle.left=a4.currentStyle.left;aY.left=a3==="fontSize"?"1em":(a7||0);a7=aY.pixelLeft+"px";aY.left=a2;a4.runtimeStyle.left=a5}}}}return a7},swap:function(a1,a0,a2){var aY={};for(var aZ in a0){aY[aZ]=a1.style[aZ];a1.style[aZ]=a0[aZ]}a2.call(a1);for(var aZ in a0){a1.style[aZ]=aY[aZ]}}});if(a.expr&&a.expr.filters){a.expr.filters.hidden=function(a1){var aZ=a1.offsetWidth,aY=a1.offsetHeight,a0=a1.nodeName.toLowerCase()==="tr";return aZ===0&&aY===0&&!a0?true:aZ>0&&aY>0&&!a0?false:a.curCSS(a1,"display")==="none"};a.expr.filters.visible=function(aY){return !a.expr.filters.hidden(aY)}}var af=aP(),aJ=/<script(.|\s)*?\/script>/gi,o=/select|textarea/i,aB=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,r=/=\?(&|$)/,D=/\?/,aX=/(\?|&)_=.*?(&|$)/,B=/^(\w+:)?\/\/([^\/?#]+)/,h=/%20/g,w=a.fn.load;a.fn.extend({load:function(a0,a3,a4){if(typeof a0!=="string"){return w.call(this,a0)}else{if(!this.length){return this}}var a2=a0.indexOf(" ");if(a2>=0){var aY=a0.slice(a2,a0.length);a0=a0.slice(0,a2)}var a1="GET";if(a3){if(a.isFunction(a3)){a4=a3;a3=null}else{if(typeof a3==="object"){a3=a.param(a3,a.ajaxSettings.traditional);a1="POST"}}}var aZ=this;a.ajax({url:a0,type:a1,dataType:"html",data:a3,complete:function(a6,a5){if(a5==="success"||a5==="notmodified"){aZ.html(aY?a("<div />").append(a6.responseText.replace(aJ,"")).find(aY):a6.responseText)}if(a4){aZ.each(a4,[a6.responseText,a5,a6])}}});return this},serialize:function(){return a.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?a.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||o.test(this.nodeName)||aB.test(this.type))}).map(function(aY,aZ){var a0=a(this).val();return a0==null?null:a.isArray(a0)?a.map(a0,function(a2,a1){return{name:aZ.name,value:a2}}):{name:aZ.name,value:a0}}).get()}});a.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(aY,aZ){a.fn[aZ]=function(a0){return this.bind(aZ,a0)}});a.extend({get:function(aY,a0,a1,aZ){if(a.isFunction(a0)){aZ=aZ||a1;a1=a0;a0=null}return a.ajax({type:"GET",url:aY,data:a0,success:a1,dataType:aZ})},getScript:function(aY,aZ){return a.get(aY,null,aZ,"script")},getJSON:function(aY,aZ,a0){return a.get(aY,aZ,a0,"json")},post:function(aY,a0,a1,aZ){if(a.isFunction(a0)){aZ=aZ||a1;a1=a0;a0={}}return a.ajax({type:"POST",url:aY,data:a0,success:a1,dataType:aZ})},ajaxSetup:function(aY){a.extend(a.ajaxSettings,aY)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:aM.XMLHttpRequest&&(aM.location.protocol!=="file:"||!aM.ActiveXObject)?function(){return new aM.XMLHttpRequest()}:function(){try{return new aM.ActiveXObject("Microsoft.XMLHTTP")}catch(aY){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(bd){var a8=a.extend(true,{},a.ajaxSettings,bd);var bi,bc,bh,bj=bd&&bd.context||a8,a0=a8.type.toUpperCase();if(a8.data&&a8.processData&&typeof a8.data!=="string"){a8.data=a.param(a8.data,a8.traditional)}if(a8.dataType==="jsonp"){if(a0==="GET"){if(!r.test(a8.url)){a8.url+=(D.test(a8.url)?"&":"?")+(a8.jsonp||"callback")+"=?"}}else{if(!a8.data||!r.test(a8.data)){a8.data=(a8.data?a8.data+"&":"")+(a8.jsonp||"callback")+"=?"}}a8.dataType="json"}if(a8.dataType==="json"&&(a8.data&&r.test(a8.data)||r.test(a8.url))){bi=a8.jsonpCallback||("jsonp"+af++);if(a8.data){a8.data=(a8.data+"").replace(r,"="+bi+"$1")}a8.url=a8.url.replace(r,"="+bi+"$1");a8.dataType="script";aM[bi]=aM[bi]||function(bk){bh=bk;a3();a6();aM[bi]=C;try{delete aM[bi]}catch(bl){}if(a1){a1.removeChild(bf)}}}if(a8.dataType==="script"&&a8.cache===null){a8.cache=false}if(a8.cache===false&&a0==="GET"){var aY=aP();var bg=a8.url.replace(aX,"$1_="+aY+"$2");a8.url=bg+((bg===a8.url)?(D.test(a8.url)?"&":"?")+"_="+aY:"")}if(a8.data&&a0==="GET"){a8.url+=(D.test(a8.url)?"&":"?")+a8.data}if(a8.global&&!a.active++){a.event.trigger("ajaxStart")}var bb=B.exec(a8.url),a2=bb&&(bb[1]&&bb[1]!==location.protocol||bb[2]!==location.host);if(a8.dataType==="script"&&a0==="GET"&&a2){var a1=ab.getElementsByTagName("head")[0]||ab.documentElement;var bf=ab.createElement("script");bf.src=a8.url;if(a8.scriptCharset){bf.charset=a8.scriptCharset}if(!bi){var ba=false;bf.onload=bf.onreadystatechange=function(){if(!ba&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){ba=true;a3();a6();bf.onload=bf.onreadystatechange=null;if(a1&&bf.parentNode){a1.removeChild(bf)}}}}a1.insertBefore(bf,a1.firstChild);return C}var a5=false;var a4=a8.xhr();if(!a4){return}if(a8.username){a4.open(a0,a8.url,a8.async,a8.username,a8.password)}else{a4.open(a0,a8.url,a8.async)}try{if(a8.data||bd&&bd.contentType){a4.setRequestHeader("Content-Type",a8.contentType)}if(a8.ifModified){if(a.lastModified[a8.url]){a4.setRequestHeader("If-Modified-Since",a.lastModified[a8.url])}if(a.etag[a8.url]){a4.setRequestHeader("If-None-Match",a.etag[a8.url])}}if(!a2){a4.setRequestHeader("X-Requested-With","XMLHttpRequest")}a4.setRequestHeader("Accept",a8.dataType&&a8.accepts[a8.dataType]?a8.accepts[a8.dataType]+", */*":a8.accepts._default)}catch(be){}if(a8.beforeSend&&a8.beforeSend.call(bj,a4,a8)===false){if(a8.global&&!--a.active){a.event.trigger("ajaxStop")}a4.abort();return false}if(a8.global){a9("ajaxSend",[a4,a8])}var a7=a4.onreadystatechange=function(bk){if(!a4||a4.readyState===0||bk==="abort"){if(!a5){a6()}a5=true;if(a4){a4.onreadystatechange=a.noop}}else{if(!a5&&a4&&(a4.readyState===4||bk==="timeout")){a5=true;a4.onreadystatechange=a.noop;bc=bk==="timeout"?"timeout":!a.httpSuccess(a4)?"error":a8.ifModified&&a.httpNotModified(a4,a8.url)?"notmodified":"success";var bm;if(bc==="success"){try{bh=a.httpData(a4,a8.dataType,a8)}catch(bl){bc="parsererror";bm=bl}}if(bc==="success"||bc==="notmodified"){if(!bi){a3()}}else{a.handleError(a8,a4,bc,bm)}a6();if(bk==="timeout"){a4.abort()}if(a8.async){a4=null}}}};try{var aZ=a4.abort;a4.abort=function(){if(a4){aZ.call(a4)}a7("abort")}}catch(be){}if(a8.async&&a8.timeout>0){setTimeout(function(){if(a4&&!a5){a7("timeout")}},a8.timeout)}try{a4.send(a0==="POST"||a0==="PUT"||a0==="DELETE"?a8.data:null)}catch(be){a.handleError(a8,a4,null,be);a6()}if(!a8.async){a7()}function a3(){if(a8.success){a8.success.call(bj,bh,bc,a4)}if(a8.global){a9("ajaxSuccess",[a4,a8])}}function a6(){if(a8.complete){a8.complete.call(bj,a4,bc)}if(a8.global){a9("ajaxComplete",[a4,a8])}if(a8.global&&!--a.active){a.event.trigger("ajaxStop")}}function a9(bl,bk){(a8.context?a(a8.context):a.event).trigger(bl,bk)}return a4},handleError:function(aZ,a1,aY,a0){if(aZ.error){aZ.error.call(aZ.context||aZ,a1,aY,a0)}if(aZ.global){(aZ.context?a(aZ.context):a.event).trigger("ajaxError",[a1,aZ,a0])}},active:0,httpSuccess:function(aZ){try{return !aZ.status&&location.protocol==="file:"||(aZ.status>=200&&aZ.status<300)||aZ.status===304||aZ.status===1223||aZ.status===0}catch(aY){}return false},httpNotModified:function(a1,aY){var a0=a1.getResponseHeader("Last-Modified"),aZ=a1.getResponseHeader("Etag");if(a0){a.lastModified[aY]=a0}if(aZ){a.etag[aY]=aZ}return a1.status===304||a1.status===0},httpData:function(a3,a1,a0){var aZ=a3.getResponseHeader("content-type")||"",aY=a1==="xml"||!a1&&aZ.indexOf("xml")>=0,a2=aY?a3.responseXML:a3.responseText;if(aY&&a2.documentElement.nodeName==="parsererror"){a.error("parsererror")}if(a0&&a0.dataFilter){a2=a0.dataFilter(a2,a1)}if(typeof a2==="string"){if(a1==="json"||!a1&&aZ.indexOf("json")>=0){a2=a.parseJSON(a2)}else{if(a1==="script"||!a1&&aZ.indexOf("javascript")>=0){a.globalEval(a2)}}}return a2},param:function(aY,a1){var aZ=[];if(a1===C){a1=a.ajaxSettings.traditional}if(a.isArray(aY)||aY.jquery){a.each(aY,function(){a3(this.name,this.value)})}else{for(var a2 in aY){a0(a2,aY[a2])}}return aZ.join("&").replace(h,"+");function a0(a4,a5){if(a.isArray(a5)){a.each(a5,function(a7,a6){if(a1||/\[\]$/.test(a4)){a3(a4,a6)}else{a0(a4+"["+(typeof a6==="object"||a.isArray(a6)?a7:"")+"]",a6)}})}else{if(!a1&&a5!=null&&typeof a5==="object"){a.each(a5,function(a7,a6){a0(a4+"["+a7+"]",a6)})}else{a3(a4,a5)}}}function a3(a4,a5){a5=a.isFunction(a5)?a5():a5;aZ[aZ.length]=encodeURIComponent(a4)+"="+encodeURIComponent(a5)}}});var G={},ae=/toggle|show|hide/,au=/^([+-]=)?([\d+-.]+)(.*)$/,aF,aj=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];a.fn.extend({show:function(aZ,a7){if(aZ||aZ===0){return this.animate(aD("show",3),aZ,a7)}else{for(var a4=0,a1=this.length;a4<a1;a4++){var aY=a.data(this[a4],"olddisplay");this[a4].style.display=aY||"";if(a.css(this[a4],"display")==="none"){var a6=this[a4].nodeName,a5;if(G[a6]){a5=G[a6]}else{var a0=a("<"+a6+" />").appendTo("body");a5=a0.css("display");if(a5==="none"){a5="block"}a0.remove();G[a6]=a5}a.data(this[a4],"olddisplay",a5)}}for(var a3=0,a2=this.length;a3<a2;a3++){this[a3].style.display=a.data(this[a3],"olddisplay")||""}return this}},hide:function(a3,a4){if(a3||a3===0){return this.animate(aD("hide",3),a3,a4)}else{for(var a2=0,aZ=this.length;a2<aZ;a2++){var aY=a.data(this[a2],"olddisplay");if(!aY&&aY!=="none"){a.data(this[a2],"olddisplay",a.css(this[a2],"display"))}}for(var a1=0,a0=this.length;a1<a0;a1++){this[a1].style.display="none"}return this}},_toggle:a.fn.toggle,toggle:function(a0,aZ){var aY=typeof a0==="boolean";if(a.isFunction(a0)&&a.isFunction(aZ)){this._toggle.apply(this,arguments)}else{if(a0==null||aY){this.each(function(){var a1=aY?a0:a(this).is(":hidden");a(this)[a1?"show":"hide"]()})}else{this.animate(aD("toggle",3),a0,aZ)}}return this},fadeTo:function(aY,a0,aZ){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:a0},aY,aZ)},animate:function(a2,aZ,a1,a0){var aY=a.speed(aZ,a1,a0);if(a.isEmptyObject(a2)){return this.each(aY.complete)}return this[aY.queue===false?"each":"queue"](function(){var a5=a.extend({},aY),a7,a6=this.nodeType===1&&a(this).is(":hidden"),a3=this;for(a7 in a2){var a4=a7.replace(az,k);if(a7!==a4){a2[a4]=a2[a7];delete a2[a7];a7=a4}if(a2[a7]==="hide"&&a6||a2[a7]==="show"&&!a6){return a5.complete.call(this)}if((a7==="height"||a7==="width")&&this.style){a5.display=a.css(this,"display");a5.overflow=this.style.overflow}if(a.isArray(a2[a7])){(a5.specialEasing=a5.specialEasing||{})[a7]=a2[a7][1];a2[a7]=a2[a7][0]}}if(a5.overflow!=null){this.style.overflow="hidden"}a5.curAnim=a.extend({},a2);a.each(a2,function(a9,bd){var bc=new a.fx(a3,a5,a9);if(ae.test(bd)){bc[bd==="toggle"?a6?"show":"hide":bd](a2)}else{var bb=au.exec(bd),be=bc.cur(true)||0;if(bb){var a8=parseFloat(bb[2]),ba=bb[3]||"px";if(ba!=="px"){a3.style[a9]=(a8||1)+ba;be=((a8||1)/bc.cur(true))*be;a3.style[a9]=be+ba}if(bb[1]){a8=((bb[1]==="-="?-1:1)*a8)+be}bc.custom(be,a8,ba)}else{bc.custom(be,bd,"")}}});return true})},stop:function(aZ,aY){var a0=a.timers;if(aZ){this.queue([])}this.each(function(){for(var a1=a0.length-1;a1>=0;a1--){if(a0[a1].elem===this){if(aY){a0[a1](true)}a0.splice(a1,1)}}});if(!aY){this.dequeue()}return this}});a.each({slideDown:aD("show",1),slideUp:aD("hide",1),slideToggle:aD("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(aY,aZ){a.fn[aY]=function(a0,a1){return this.animate(aZ,a0,a1)}});a.extend({speed:function(a0,a1,aZ){var aY=a0&&typeof a0==="object"?a0:{complete:aZ||!aZ&&a1||a.isFunction(a0)&&a0,duration:a0,easing:aZ&&a1||a1&&!a.isFunction(a1)&&a1};aY.duration=a.fx.off?0:typeof aY.duration==="number"?aY.duration:a.fx.speeds[aY.duration]||a.fx.speeds._default;aY.old=aY.complete;aY.complete=function(){if(aY.queue!==false){a(this).dequeue()}if(a.isFunction(aY.old)){aY.old.call(this)}};return aY},easing:{linear:function(a0,a1,aY,aZ){return aY+aZ*a0},swing:function(a0,a1,aY,aZ){return((-Math.cos(a0*Math.PI)/2)+0.5)*aZ+aY}},timers:[],fx:function(aZ,aY,a0){this.options=aY;this.elem=aZ;this.prop=a0;if(!aY.orig){aY.orig={}}}});a.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(a.fx.step[this.prop]||a.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(aZ){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var aY=parseFloat(a.css(this.elem,this.prop,aZ));return aY&&aY>-10000?aY:parseFloat(a.curCSS(this.elem,this.prop))||0},custom:function(a2,a1,a0){this.startTime=aP();this.start=a2;this.end=a1;this.unit=a0||this.unit||"px";this.now=this.start;this.pos=this.state=0;var aY=this;function aZ(a3){return aY.step(a3)}aZ.elem=this.elem;if(aZ()&&a.timers.push(aZ)&&!aF){aF=setInterval(a.fx.tick,13)}},show:function(){this.options.orig[this.prop]=a.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());a(this.elem).show()},hide:function(){this.options.orig[this.prop]=a.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a1){var a6=aP(),a2=true;if(a1||a6>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var a3 in this.options.curAnim){if(this.options.curAnim[a3]!==true){a2=false}}if(a2){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;var a0=a.data(this.elem,"olddisplay");this.elem.style.display=a0?a0:this.options.display;if(a.css(this.elem,"display")==="none"){this.elem.style.display="block"}}if(this.options.hide){a(this.elem).hide()}if(this.options.hide||this.options.show){for(var aY in this.options.curAnim){a.style(this.elem,aY,this.options.orig[aY])}}this.options.complete.call(this.elem)}return false}else{var aZ=a6-this.startTime;this.state=aZ/this.options.duration;var a4=this.options.specialEasing&&this.options.specialEasing[this.prop];var a5=this.options.easing||(a.easing.swing?"swing":"linear");this.pos=a.easing[a4||a5](this.state,aZ,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};a.extend(a.fx,{tick:function(){var aZ=a.timers;for(var aY=0;aY<aZ.length;aY++){if(!aZ[aY]()){aZ.splice(aY--,1)}}if(!aZ.length){a.fx.stop()}},stop:function(){clearInterval(aF);aF=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(aY){a.style(aY.elem,"opacity",aY.now)},_default:function(aY){if(aY.elem.style&&aY.elem.style[aY.prop]!=null){aY.elem.style[aY.prop]=(aY.prop==="width"||aY.prop==="height"?Math.max(0,aY.now):aY.now)+aY.unit}else{aY.elem[aY.prop]=aY.now}}}});if(a.expr&&a.expr.filters){a.expr.filters.animated=function(aY){return a.grep(a.timers,function(aZ){return aY===aZ.elem}).length}}function aD(aZ,aY){var a0={};a.each(aj.concat.apply([],aj.slice(0,aY)),function(){a0[this]=aZ});return a0}if("getBoundingClientRect" in ab.documentElement){a.fn.offset=function(a7){var a0=this[0];if(a7){return this.each(function(a8){a.offset.setOffset(this,a7,a8)})}if(!a0||!a0.ownerDocument){return null}if(a0===a0.ownerDocument.body){return a.offset.bodyOffset(a0)}var a2=a0.getBoundingClientRect(),a6=a0.ownerDocument,a3=a6.body,aY=a6.documentElement,a1=aY.clientTop||a3.clientTop||0,a4=aY.clientLeft||a3.clientLeft||0,a5=a2.top+(self.pageYOffset||a.support.boxModel&&aY.scrollTop||a3.scrollTop)-a1,aZ=a2.left+(self.pageXOffset||a.support.boxModel&&aY.scrollLeft||a3.scrollLeft)-a4;return{top:a5,left:aZ}}}else{a.fn.offset=function(a9){var a3=this[0];if(a9){return this.each(function(ba){a.offset.setOffset(this,a9,ba)})}if(!a3||!a3.ownerDocument){return null}if(a3===a3.ownerDocument.body){return a.offset.bodyOffset(a3)}a.offset.initialize();var a0=a3.offsetParent,aZ=a3,a8=a3.ownerDocument,a6,a1=a8.documentElement,a4=a8.body,a5=a8.defaultView,aY=a5?a5.getComputedStyle(a3,null):a3.currentStyle,a7=a3.offsetTop,a2=a3.offsetLeft;while((a3=a3.parentNode)&&a3!==a4&&a3!==a1){if(a.offset.supportsFixedPosition&&aY.position==="fixed"){break}a6=a5?a5.getComputedStyle(a3,null):a3.currentStyle;a7-=a3.scrollTop;a2-=a3.scrollLeft;if(a3===a0){a7+=a3.offsetTop;a2+=a3.offsetLeft;if(a.offset.doesNotAddBorder&&!(a.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(a3.nodeName))){a7+=parseFloat(a6.borderTopWidth)||0;a2+=parseFloat(a6.borderLeftWidth)||0}aZ=a0,a0=a3.offsetParent}if(a.offset.subtractsBorderForOverflowNotVisible&&a6.overflow!=="visible"){a7+=parseFloat(a6.borderTopWidth)||0;a2+=parseFloat(a6.borderLeftWidth)||0}aY=a6}if(aY.position==="relative"||aY.position==="static"){a7+=a4.offsetTop;a2+=a4.offsetLeft}if(a.offset.supportsFixedPosition&&aY.position==="fixed"){a7+=Math.max(a1.scrollTop,a4.scrollTop);a2+=Math.max(a1.scrollLeft,a4.scrollLeft)}return{top:a7,left:a2}}}a.offset={initialize:function(){var aY=ab.body,aZ=ab.createElement("div"),a2,a4,a3,a5,a0=parseFloat(a.curCSS(aY,"marginTop",true))||0,a1="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.extend(aZ.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});aZ.innerHTML=a1;aY.insertBefore(aZ,aY.firstChild);a2=aZ.firstChild;a4=a2.firstChild;a5=a2.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(a4.offsetTop!==5);this.doesAddBorderForTableAndCells=(a5.offsetTop===5);a4.style.position="fixed",a4.style.top="20px";this.supportsFixedPosition=(a4.offsetTop===20||a4.offsetTop===15);a4.style.position=a4.style.top="";a2.style.overflow="hidden",a2.style.position="relative";this.subtractsBorderForOverflowNotVisible=(a4.offsetTop===-5);this.doesNotIncludeMarginInBodyOffset=(aY.offsetTop!==a0);aY.removeChild(aZ);aY=aZ=a2=a4=a3=a5=null;a.offset.initialize=a.noop},bodyOffset:function(aY){var a0=aY.offsetTop,aZ=aY.offsetLeft;a.offset.initialize();if(a.offset.doesNotIncludeMarginInBodyOffset){a0+=parseFloat(a.curCSS(aY,"marginTop",true))||0;aZ+=parseFloat(a.curCSS(aY,"marginLeft",true))||0}return{top:a0,left:aZ}},setOffset:function(a3,aZ,a0){if(/static/.test(a.curCSS(a3,"position"))){a3.style.position="relative"}var a2=a(a3),a5=a2.offset(),aY=parseInt(a.curCSS(a3,"top",true),10)||0,a4=parseInt(a.curCSS(a3,"left",true),10)||0;if(a.isFunction(aZ)){aZ=aZ.call(a3,a0,a5)}var a1={top:(aZ.top-a5.top)+aY,left:(aZ.left-a5.left)+a4};if("using" in aZ){aZ.using.call(a3,a1)}else{a2.css(a1)}}};a.fn.extend({position:function(){if(!this[0]){return null}var a0=this[0],aZ=this.offsetParent(),a1=this.offset(),aY=/^body|html$/i.test(aZ[0].nodeName)?{top:0,left:0}:aZ.offset();a1.top-=parseFloat(a.curCSS(a0,"marginTop",true))||0;a1.left-=parseFloat(a.curCSS(a0,"marginLeft",true))||0;aY.top+=parseFloat(a.curCSS(aZ[0],"borderTopWidth",true))||0;aY.left+=parseFloat(a.curCSS(aZ[0],"borderLeftWidth",true))||0;return{top:a1.top-aY.top,left:a1.left-aY.left}},offsetParent:function(){return this.map(function(){var aY=this.offsetParent||ab.body;while(aY&&(!/^body|html$/i.test(aY.nodeName)&&a.css(aY,"position")==="static")){aY=aY.offsetParent}return aY})}});a.each(["Left","Top"],function(aZ,aY){var a0="scroll"+aY;a.fn[a0]=function(a3){var a1=this[0],a2;if(!a1){return null}if(a3!==C){return this.each(function(){a2=am(this);if(a2){a2.scrollTo(!aZ?a3:a(a2).scrollLeft(),aZ?a3:a(a2).scrollTop())}else{this[a0]=a3}})}else{a2=am(a1);return a2?("pageXOffset" in a2)?a2[aZ?"pageYOffset":"pageXOffset"]:a.support.boxModel&&a2.document.documentElement[a0]||a2.document.body[a0]:a1[a0]}}});function am(aY){return("scrollTo" in aY&&aY.document)?aY:aY.nodeType===9?aY.defaultView||aY.parentWindow:false}a.each(["Height","Width"],function(aZ,aY){var a0=aY.toLowerCase();a.fn["inner"+aY]=function(){return this[0]?a.css(this[0],a0,false,"padding"):null};a.fn["outer"+aY]=function(a1){return this[0]?a.css(this[0],a0,false,a1?"margin":"border"):null};a.fn[a0]=function(a1){var a2=this[0];if(!a2){return a1==null?null:this}if(a.isFunction(a1)){return this.each(function(a4){var a3=a(this);a3[a0](a1.call(this,a4,a3[a0]()))})}return("scrollTo" in a2&&a2.document)?a2.document.compatMode==="CSS1Compat"&&a2.document.documentElement["client"+aY]||a2.document.body["client"+aY]:(a2.nodeType===9)?Math.max(a2.documentElement["client"+aY],a2.body["scroll"+aY],a2.documentElement["scroll"+aY],a2.body["offset"+aY],a2.documentElement["offset"+aY]):a1===C?a.css(a2,a0):this.css(a0,typeof a1==="string"?a1:a1+"px")}});aM.jQuery=aM.$=a})(window);(function(bL,r,a8){var bZ=bL.jQuery.noConflict(true);if(typeof r.getAttribute==q){r.getAttribute=function(){}}var al=function(cM){return b9(cM)?cM.toLowerCase():cM};var bx=function(cM){return b9(cM)?cM.toUpperCase():cM};var aA=function(cM){return b9(cM)?cM.replace(/[A-Z]/g,function(cN){return H(cN.charCodeAt(0)|32)}):cM};var b5=function(cM){return b9(cM)?cM.replace(/[a-z]/g,function(cN){return H(cN.charCodeAt(0)&~32)}):cM};if("i"!=="I".toLowerCase()){al=aA;bx=b5}function H(cM){return String.fromCharCode(cM)}var cI=undefined,a1=null,bo="$element",S="angular",aY="array",b0="boolean",bq="console",a5="date",aG="display",ct="element",bp="function",ah="length",Z="name",b="none",cv="noop",v="null",b8="number",aK="object",Q="string",q="undefined",a="ng-exception",k="ng-validation-error",o="noop",bf=-99999,am=-1000,b7=99999,aH={FIRST:bf,LAST:b7,WATCH:am},co=bL.jQuery||bL["$"],b1=bL._,ar=parseInt((/msie (\d+)/.exec(al(navigator.userAgent))||[])[1],10),cb=co||cB,ac=Array.prototype.slice,B=Array.prototype.push,cw=bL[bq]?bu(bL[bq],bL[bq]["error"]||j):j,ax=bL[S]||(bL[S]={}),ae=be(ax,"markup"),s=be(ax,"attrMarkup"),aa=be(ax,"directive"),A=be(ax,"widget",al),aF=be(ax,"validator"),cl=be(ax,"filter"),l=be(ax,"formatter"),bi=be(ax,"service"),a7=be(ax,"callbacks"),at,ab=/^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/;function aN(cP,cO,cN){var cM;if(cP){if(D(cP)){for(cM in cP){if(cM!="prototype"&&cM!=ah&&cM!=Z&&cP.hasOwnProperty(cM)){cO.call(cN,cP[cM],cM)}}}else{if(cP.forEach){cP.forEach(cO,cN)}else{if(cH(cP)&&aP(cP.length)){for(cM=0;cM<cP.length;cM++){cO.call(cN,cP[cM],cM)}}else{for(cM in cP){cO.call(cN,cP[cM],cM)}}}}}return cP}function aq(cR,cP,cO){var cQ=[];for(var cN in cR){cQ.push(cN)}cQ.sort();for(var cM=0;cM<cQ.length;cM++){cP.call(cO,cR[cQ[cM]],cQ[cM])}return cQ}function bY(cM){aN(arguments,function(cN){if(cN!==cM){aN(cN,function(cP,cO){cM[cO]=cP})}});return cM}function bW(cN,cM){return bY(new (bY(function(){},{prototype:cN}))(),cM)}function j(){}function aB(cM){return cM}function ci(cM){return function(){return cM}}function be(cO,cN,cM){var cP;return cO[cN]||(cP=cO[cN]=function(cQ,cR,cS){cQ=(cM||aB)(cQ);if(cm(cR)){cP[cQ]=bY(cR,cS||{})}return cP[cQ]})}function cB(cM){if(cM){if(b9(cM)){var cN=r.createElement("div");cN.innerHTML=cM;cM=new bk(cN.childNodes)}else{if(!(cM instanceof bk)&&by(cM)){cM=new bk(cM)}}}return cM}function br(cM){return typeof cM==q}function cm(cM){return typeof cM!=q}function cH(cM){return cM!=a1&&typeof cM==aK}function b9(cM){return typeof cM==Q}function aP(cM){return typeof cM==b8}function a3(cM){return cM instanceof Array}function D(cM){return typeof cM==bp}function t(cM){return at(cM)=="#text"}function au(cM){return b9(cM)?cM.replace(/^\s*/,"").replace(/\s*$/,""):cM}function by(cM){return cM&&(cM.nodeName||cM instanceof bk||(co&&cM instanceof co))}function aR(cN,cO){this.html=cN;this.get=al(cO)=="unsafe"?ci(cN):function cM(){var cP=[];aM(cN,a0(cP));return cP.join("")}}if(ar){at=function(cM){cM=cM.nodeName?cM:cM[0];return(cM.scopeName&&cM.scopeName!="HTML")?bx(cM.scopeName+":"+cM.nodeName):cM.nodeName}}else{at=function(cM){return cM.nodeName?cM.nodeName:cM[0].nodeName}}function z(cM){return cb(cM[0].cloneNode(true))}function aL(cN){var cP=cN[0].getBoundingClientRect(),cO=(cP.width||(cP.right||0-cP.left||0)),cM=(cP.height||(cP.bottom||0-cP.top||0));return cO>0&&cM>0}function aD(cP,cO,cN){var cM=[];aN(cP,function(cS,cQ,cR){cM.push(cO.call(cN,cS,cQ,cR))});return cM}function av(cN){var cM=0;if(cN){if(aP(cN.length)){return cN.length}else{if(cH(cN)){for(key in cN){cM++}}}}return cM}function u(cO,cN){for(var cM=0;cM<cO.length;cM++){if(cN===cO[cM]){return true}}return false}function cE(cO,cN){for(var cM=0;cM<cO.length;cM++){if(cN===cO[cM]){return cM}}return -1}function bV(cM){if(cM){switch(cM.nodeName){case"OPTION":case"PRE":case"TITLE":return true}}return false}function bl(cP,cM){if(!cM){cM=cP;if(cP){if(a3(cP)){cM=bl(cP,[])}else{if(cP instanceof Date){cM=new Date(cP.getTime())}else{if(cH(cP)){cM=bl(cP,{})}}}}}else{if(a3(cP)){while(cM.length){cM.pop()}for(var cO=0;cO<cP.length;cO++){cM.push(bl(cP[cO]))}}else{aN(cM,function(cR,cQ){delete cM[cQ]});for(var cN in cP){cM[cN]=bl(cP[cN])}}}return cM}function p(cS,cR){if(cS==cR){return true}var cQ=typeof cS,cO=typeof cR,cP,cN,cM;if(cQ==cO&&cQ=="object"){if(cS instanceof Array){if((cP=cS.length)==cR.length){for(cN=0;cN<cP;cN++){if(!p(cS[cN],cR[cN])){return false}}return true}}else{cM={};for(cN in cS){if(cN.charAt(0)!=="$"&&!D(cS[cN])&&!p(cS[cN],cR[cN])){return false}cM[cN]=true}for(cN in cR){if(!cM[cN]&&cN.charAt(0)!=="$"&&!D(cR[cN])){return false}}return true}}return false}function V(cN,cM){if(bV(cN)){if(ar){cN.innerText=cM}else{cN.textContent=cM}}else{cN.innerHTML=cM}}function bB(cN){var cM=cN&&cN[0]&&cN[0].nodeName;return cM&&cM.charAt(0)!="#"&&!u(["TR","COL","COLGROUP","TBODY","THEAD","TFOOT"],cM)}function bR(cN,cO,cM){while(!bB(cN)){cN=cN.parent()||cb(r.body)}if(cN[0]["$NG_ERROR"]!==cM){cN[0]["$NG_ERROR"]=cM;if(cM){cN.addClass(cO);cN.attr(cO,cM)}else{cN.removeClass(cO);cN.removeAttr(cO)}}}function a6(cO,cN,cM){return cO.concat(ac.call(cN,cM,cN.length))}function bu(cN,cO){var cM=arguments.length>2?ac.call(arguments,2,arguments.length):[];if(typeof cO==bp){return cM.length?function(){return arguments.length?cO.apply(cN,cM.concat(ac.call(arguments,0,arguments.length))):cO.apply(cN,cM)}:function(){return arguments.length?cO.apply(cN,arguments):cO.call(cN)}}else{return cO}}function cg(cN){if(cN&&cN.length!==0){var cM=al(""+cN);cN=!(cM=="f"||cM=="0"||cM=="false"||cM=="no"||cM=="n"||cM=="[]")}else{cN=false}return cN}function bc(cP,cQ){for(var cM in cP){var cO=cQ[cM];var cN=typeof cO;if(cN==q){cQ[cM]=R(cd(cP[cM]))}else{if(cN=="object"&&cO.constructor!=G&&cM.substring(0,1)!="$"){bc(cP[cM],cO)}}}}function aX(cO,cN){var cP=new a4(ae,s,aa,A),cM=cb(cO);return cP.compile(cM)(cM,cN)}function af(cP){var cO={},cM,cN;aN((cP||"").split("&"),function(cQ){if(cQ){cM=cQ.split("=");cN=unescape(cM[0]);cO[cN]=cm(cM[1])?unescape(cM[1]):true}});return cO}function O(cN){var cM=[];aN(cN,function(cP,cO){cM.push(escape(cO)+(cP===true?"":"="+escape(cP)))});return cM.length?cM.join("&"):""}function bm(cN){if(cN.autobind){var cO=aX(bL.document,a1,{"$config":cN}),cM=cO.$inject("$browser");if(cN.css){cM.addCss(cN.base_url+cN.css)}else{if(ar<8){cM.addJs(cN.base_url+cN.ie_compat,cN.ie_compat_id)}}cO.$init()}}function bw(cN,cQ){var cM=cN.getElementsByTagName("script"),cP;cQ=bY({ie_compat_id:"ng-ie-compat"},cQ);for(var cO=0;cO<cM.length;cO++){cP=(cM[cO].src||"").match(ab);if(cP){cQ.base_url=cP[1];cQ.ie_compat=cP[1]+"angular-ie-compat"+(cP[2]||"")+".js";bY(cQ,af(cP[6]));aZ(cb(cM[cO]),function(cS,cR){if(/^ng:/.exec(cR)){cR=cR.substring(3).replace(/-/g,"_");if(cR=="autobind"){cS=true}cQ[cR]=cS}})}}return cQ}var G=[].constructor;function cd(cO,cN){var cM=[];bI(cM,cO,cN?"\n ":a1,[]);return cM.join("")}function R(cM){if(!cM){return cM}try{var cO=T(cM,true);var cP=cO.primary();cO.assertAllConsumed();return cP()}catch(cN){cw("fromJson error: ",cM,cN);throw cN}}ax.toJson=cd;ax.fromJson=R;function bI(cN,cP,cS,cU){if(typeof cP=="object"){if(u(cU,cP)){cN.push("RECURSION");return}cU.push(cP)}var cT=typeof cP;if(cP===a1){cN.push(v)}else{if(cP instanceof RegExp){cN.push(ax.String["quoteUnicode"](cP.toString()))}else{if(cT===bp){return}else{if(cT===b0){cN.push(""+cP)}else{if(cT===b8){if(isNaN(cP)){cN.push(v)}else{cN.push(""+cP)}}else{if(cT===Q){return cN.push(ax.String["quoteUnicode"](cP))}else{if(cT===aK){if(cP instanceof Array){cN.push("[");var cR=cP.length;var c1=false;for(var cQ=0;cQ<cR;cQ++){var cY=cP[cQ];if(c1){cN.push(",")}if(!(cY instanceof RegExp)&&(typeof cY==bp||typeof cY==q)){cN.push(v)}else{bI(cN,cY,cS,cU)}c1=true}cN.push("]")}else{if(cP instanceof Date){cN.push(ax.String["quoteUnicode"](ax.Date["toString"](cP)))}else{cN.push("{");if(cS){cN.push(cS)}var c0=false;var cZ=cS?cS+" ":false;var cX=[];for(var cO in cP){if(cO.indexOf("$")===0||cP[cO]===cI){continue}cX.push(cO)}cX.sort();for(var cM=0;cM<cX.length;cM++){var cW=cX[cM];var cV=cP[cW];if(typeof cV!=bp){if(c0){cN.push(",");if(cS){cN.push(cS)}}cN.push(ax.String["quote"](cW));cN.push(":");bI(cN,cV,cZ,cU);c0=true}}cN.push("}")}}}}}}}}}if(typeof cP==aK){cU.pop()}}function cn(cM){this.paths=[];this.children=[];this.inits=[];this.priority=cM;this.newScope=false}cn.prototype={init:function(cM,cN){var cO={};this.collectInits(cM,cO,cN);aq(cO,function(cP){aN(cP,function(cQ){cQ()})})},collectInits:function(cO,cR,cU){var cQ=cR[this.priority],cS=cU;if(!cQ){cR[this.priority]=cQ=[]}cO=cb(cO);if(this.newScope){cS=bM(cU);cU.$onEval(cS.$eval)}aN(this.inits,function(cW){cQ.push(function(){cS.$tryEval(function(){return cS.$inject(cW,cS,cO)},cO)})});var cP,cT=cO[0].childNodes,cN=this.children,cV=this.paths,cM=cV.length;for(cP=0;cP<cM;cP++){cN[cP].collectInits(cT[cV[cP]],cR,cS)}},addInit:function(cM){if(cM){this.inits.push(cM)}},addChild:function(cM,cN){if(cN){this.paths.push(cM);this.children.push(cN)}},empty:function(){return this.inits.length===0&&this.paths.length===0}};function a4(cM,cN,cP,cO){this.markup=cM;this.attrMarkup=cN;this.directives=cP;this.widgets=cO}a4.prototype={compile:function(cQ){cQ=cb(cQ);var cM=0,cP,cO=cQ.parent();if(cO&&cO[0]){cO=cO[0];for(var cN=0;cN<cO.childNodes.length;cN++){if(cO.childNodes[cN]==cQ[0]){cM=cN}}}cP=this.templatize(cQ,cM,0)||new cn();return function(cR,cT){cR=cb(cR);var cS=cT&&cT.$eval?cT:bM(cT);return bY(cS,{$element:cR,$init:function(){cP.init(cR,cS);cS.$eval();delete cS.$init;return cS}})}},templatize:function(cR,cN,cW){var c0=this,cS,cV,cO=c0.directives,cU=true,cP=true,c1=at(cR),cZ,cY={compile:bu(c0,c0.compile),comment:function(c2){return cb(r.createComment(c2))},element:function(c2){return cb(r.createElement(c2))},text:function(c2){return cb(r.createTextNode(c2))},descend:function(c2){if(cm(c2)){cU=c2}return cU},directives:function(c2){if(cm(c2)){cP=c2}return cP},scope:function(c2){if(cm(c2)){cZ.newScope=cZ.newScope||c2}return cZ.newScope}};try{cW=cR.attr("ng:eval-order")||cW||0}catch(cT){cW=cW||0}if(b9(cW)){cW=aH[bx(cW)]||parseInt(cW,10)}cZ=new cn(cW);aZ(cR,function(c3,c2){if(!cS){if(cS=c0.widgets("@"+c2)){cR.addClass("ng-attr-widget");cS=bu(cY,cS,c3,cR)}}});if(!cS){if(cS=c0.widgets(c1)){if(c1.indexOf(":")>0){cR.addClass("ng-widget")}cS=bu(cY,cS,cR)}}if(cS){cU=false;cP=false;var cX=cR.parent();cZ.addInit(cS.call(cY,cR));if(cX&&cX[0]){cR=cb(cX[0].childNodes[cN])}}if(cU){for(var cQ=0,cM=cR[0].childNodes;cQ<cM.length;cQ++){if(t(cM[cQ])){aN(c0.markup,function(c2){if(cQ<cM.length){var c3=cb(cM[cQ]);c2.call(cY,c3.text(),c3,cR)}})}}}if(cP){aZ(cR,function(c3,c2){aN(c0.attrMarkup,function(c4){c4.call(cY,c3,c2,cR)})});aZ(cR,function(c3,c2){cV=cO[c2];if(cV){cR.addClass("ng-directive");cZ.addInit((cO[c2]).call(cY,c3,cR))}})}if(cU){aS(cR,function(c3,c2){cZ.addChild(c2,c0.templatize(c3,c2,cW))})}return cZ.empty()?a1:cZ}};function aS(cN,cO){var cM,cQ=cN[0].childNodes||[],cP;for(cM=0;cM<cQ.length;cM++){if(!t(cP=cQ[cM])){cO(cb(cP),cM)}}}function aZ(cN,cR){var cO,cU=cN[0].attributes||[],cT,cQ,cM,cS,cP={};for(cO=0;cO<cU.length;cO++){cQ=cU[cO];cM=cQ.name;cS=cQ.value;if(ar&&cM=="href"){cS=decodeURIComponent(cN[0].getAttribute(cM,2))}cP[cM]=cS}aq(cP,cR)}function bH(cU,cV,cS){if(!cV){return cU}var cN=cV.split(".");var cT;var cM=cU;var cP=cN.length;for(var cO=0;cO<cP;cO++){cT=cN[cO];if(!cT.match(/^[\$\w][\$\w\d]*$/)){throw"Expression '"+cV+"' is not a valid expression for accesing variables."}if(cU){cM=cU;cU=cU[cT]}if(br(cU)&&cT.charAt(0)=="$"){var cQ=ax.Global["typeOf"](cM);cQ=ax[cQ.charAt(0).toUpperCase()+cQ.substring(1)];var cR=cQ?cQ[[cT.substring(1)]]:cI;if(cR){cU=bu(cM,cR,cM);return cU}}}if(!cS&&D(cU)){return bu(cM,cU)}return cU}function b4(cM,cS,cR){var cQ=cS.split(".");for(var cP=0;cQ.length>1;cP++){var cO=cQ.shift();var cN=cM[cO];if(!cN){cN={};cM[cO]=cN}cM=cN}cM[cQ.shift()]=cR;return cR}var aw=0,cu={},aI={},cD={};aN(("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default,delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto,if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private,protected,public,return,short,static,super,switch,synchronized,this,throw,throws,transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/),function(cM){cD[cM]=true});function cf(cO){var cM=cu[cO];if(cM){return cM}var cN="var l, fn, t;\n";aN(cO.split("."),function(cQ){cQ=(cD[cQ])?'["'+cQ+'"]':"."+cQ;cN+="if(!s) return s;\nl=s;\ns=s"+cQ+';\nif(typeof s=="function") s = function(){ return l'+cQ+".apply(l, arguments); };\n";if(cQ.charAt(1)=="$"){var cP=cQ.substr(2);cN+='if(!s) {\n t = angular.Global.typeOf(l);\n fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["'+cP+'"];\n if (fn) s = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0, arguments.length))); };\n}\n'}});cN+="return s;";cM=Function("s",cN);cM.toString=function(){return cN};return cu[cO]=cM}function bj(cP){if(typeof cP===bp){return cP}var cM=aI[cP];if(!cM){var cN=T(cP);var cO=cN.statements();cN.assertAllConsumed();cM=aI[cP]=bY(function(){return cO(this)},{fnSelf:cO})}return cM}function an(cN,cM){bR(cN,a,cm(cM)?cd(cM):cM)}function bM(cT,cR,cP){function cM(){}cT=cM.prototype=(cT||{});var cU=new cM();var cV={sorted:[]};var cQ=[],cN={},cO=0;bY(cU,{"this":cU,$id:(aw++),$parent:cT,$bind:bu(cU,bu,cU),$get:bu(cU,bH,cU),$set:bu(cU,b4,cU),$eval:function cS(c2){var c1=typeof c2;var cZ,cY;var cX,c3;var cW;var c0;if(c1==q){for(cZ=0,cY=cV.sorted.length;cZ<cY;cZ++){for(cW=cV.sorted[cZ],c3=cW.length,cX=0;cX<c3;cX++){cU.$tryEval(cW[cX].fn,cW[cX].handler)}}while(cQ.length){c0=cQ.shift();delete cN[c0.$postEvalId];cU.$tryEval(c0)}}else{if(c1===bp){return c2.call(cU)}else{if(c1==="string"){return bj(c2).call(cU)}}}},$tryEval:function(cZ,cW){var cX=typeof cZ;try{if(cX==bp){return cZ.call(cU)}else{if(cX=="string"){return bj(cZ).call(cU)}}}catch(cY){(cU.$log||{error:cw}).error(cY);if(D(cW)){cW(cY)}else{if(cW){an(cW,cY)}else{if(D(cU.$exceptionHandler)){cU.$exceptionHandler(cY)}}}}},$watch:function(c0,cZ,cW){var c1=bj(c0),cY;cZ=bj(cZ);function cX(){var c3=c1.call(cU),c2=cY;if(cY!==c3){cY=c3;cU.$tryEval(function(){return cZ.call(cU,c3,c2)},cW)}}cU.$onEval(am,cX);cX()},$onEval:function(cX,cZ,cW){if(!aP(cX)){cW=cZ;cZ=cX;cX=0}var cY=cV[cX];if(!cY){cY=cV[cX]=[];cY.priority=cX;cV.sorted.push(cY);cV.sorted.sort(function(c1,c0){return c1.priority-c0.priority})}cY.push({fn:bj(cZ),handler:cW})},$postEval:function(cX){if(cX){var cW=bj(cX);var cY=cW.$postEvalId;if(!cY){cY="$"+cU.$id+"_"+(cO++);cW.$postEvalId=cY}if(!cN[cY]){cQ.push(cN[cY]=cW)}}},$become:function(cW){if(D(cW)){cU.constructor=cW;aN(cW.prototype,function(cY,cX){cU[cX]=bu(cU,cY)});cU.$inject.apply(cU,a6([cW,cU],arguments,1));if(D(cW.prototype.init)){cU.init()}}},$new:function(cW){var cX=bM(cU);cX.$become.apply(cU,a6([cW],arguments,1));cU.$onEval(cX.$eval);return cX}});if(!cT.$root){cU.$root=cU;cU.$parent=cU;(cU.$inject=bP(cU,cR,cP))()}return cU}function bP(cN,cP,cM){cP=cP||bi;cM=cM||{};cN=cN||{};return function cO(cU,cT,cR){var cS,cV,cQ;if(b9(cU)){if(!cM.hasOwnProperty(cU)){cV=cP[cU];if(!cV){throw"Unknown provider for '"+cU+"'."}cM[cU]=cO(cV,cN)}cS=cM[cU]}else{if(a3(cU)){cS=[];aN(cU,function(cW){cS.push(cO(cW))})}else{if(D(cU)){cS=cO(cU.$inject||[]);cS=cU.apply(cT,a6(cS,arguments,2))}else{if(cH(cU)){aN(cP,function(cX,cW){cQ=cX.$creation;if(cQ=="eager"){cO(cW)}if(cQ=="eager-published"){b4(cU,cW,cO(cW))}})}else{cS=cO(cN)}}}}return cS}}var K={"null":function(cM){return a1},"true":function(cM){return true},"false":function(cM){return false},$undefined:j,"+":function(cO,cN,cM){return(cm(cN)?cN:0)+(cm(cM)?cM:0)},"-":function(cO,cN,cM){return(cm(cN)?cN:0)-(cm(cM)?cM:0)},"*":function(cO,cN,cM){return cN*cM},"/":function(cO,cN,cM){return cN/cM},"%":function(cO,cN,cM){return cN%cM},"^":function(cO,cN,cM){return cN^cM},"=":function(cO,cN,cM){return b4(cO,cN,cM)},"==":function(cO,cN,cM){return cN==cM},"!=":function(cO,cN,cM){return cN!=cM},"<":function(cO,cN,cM){return cN<cM},">":function(cO,cN,cM){return cN>cM},"<=":function(cO,cN,cM){return cN<=cM},">=":function(cO,cN,cM){return cN>=cM},"&&":function(cO,cN,cM){return cN&&cM},"||":function(cO,cN,cM){return cN||cM},"&":function(cO,cN,cM){return cN&cM},"|":function(cO,cN,cM){return cM(cO,cN)},"!":function(cN,cM){return !cM}};var U={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'};function bg(c0,cQ){var c5=cQ?20:-1,c2=[],cV,cU=0,c7=[],cY,c8=":";while(cU<c0.length){cY=c0.charAt(cU);if(cT("\"'")){cO(cY)}else{if(c1(cY)||cT(".")&&c1(c4())){cP()}else{if(cX("({[:,;")&&cT("/")){cN()}else{if(c3(cY)){cZ();if(cX("{,")&&c7[0]=="{"&&(cV=c2[c2.length-1])){cV.json=cV.text.indexOf(".")==-1}}else{if(cT("(){}[].,;:")){c2.push({index:cU,text:cY,json:cT("{}[]:,")});if(cT("{[")){c7.unshift(cY)}if(cT("}]")){c7.shift()}cU++}else{if(cS(cY)){cU++;continue}else{var cM=cY+c4(),cW=K[cY],c6=K[cM];if(c6){c2.push({index:cU,text:cM,fn:c6});cU+=2}else{if(cW){c2.push({index:cU,text:cY,fn:cW,json:cX("[,:")&&cT("+-")});cU+=1}else{throw"Lexer Error: Unexpected next character ["+c0.substring(cU)+"] in expression '"+c0+"' at column '"+(cU+1)+"'."}}}}}}}}c8=cY}return c2;function cT(c9){return c9.indexOf(cY)!=-1}function cX(c9){return c9.indexOf(c8)!=-1}function c4(){return cU+1<c0.length?c0.charAt(cU+1):false}function c1(c9){return"0"<=c9&&c9<="9"}function cS(c9){return c9==" "||c9=="\r"||c9=="\t"||c9=="\n"||c9=="\v"||c9=="\u00A0"}function c3(c9){return"a"<=c9&&c9<="z"||"A"<=c9&&c9<="Z"||"_"==c9||c9=="$"}function cR(c9){return c9=="-"||c9=="+"}function cP(){var db="";var dc=cU;while(cU<c0.length){var da=c0.charAt(cU);if(da=="."||c1(da)){db+=da}else{var c9=c4();if(da=="E"&&cR(c9)){db+=da}else{if(cR(da)&&c9&&c1(c9)&&db.charAt(db.length-1)=="E"){db+=da}else{if(cR(da)&&(!c9||!c1(c9))&&db.charAt(db.length-1)=="E"){throw'Lexer found invalid exponential value "'+c0+'"'}else{break}}}}cU++}db=1*db;c2.push({index:dc,text:db,json:true,fn:function(){return db}})}function cZ(){var db="";var dc=cU;while(cU<c0.length){var da=c0.charAt(cU);if(da=="."||c3(da)||c1(da)){db+=da}else{break}cU++}var c9=K[db];if(!c9){c9=cf(db);c9.isAssignable=db}c2.push({index:dc,text:db,fn:c9,json:K[db]})}function cO(c9){var dg=cU;cU++;var da="";var db=c9;var de=false;while(cU<c0.length){var dc=c0.charAt(cU);db+=dc;if(de){if(dc=="u"){var dd=c0.substring(cU+1,cU+5);if(!dd.match(/[\da-f]{4}/i)){throw"Lexer Error: Invalid unicode escape [\\u"+dd+"] starting at column '"+dg+"' in expression '"+c0+"'."}cU+=4;da+=String.fromCharCode(parseInt(dd,16))}else{var df=U[dc];if(df){da+=df}else{da+=dc}}de=false}else{if(dc=="\\"){de=true}else{if(dc==c9){cU++;c2.push({index:dg,text:db,string:da,json:true,fn:function(){return(da.length==c5)?ax.String["toDate"](da):da}});return}else{da+=dc}}}cU++}throw"Lexer Error: Unterminated quote ["+c0.substring(dg)+"] starting at column '"+(dg+1)+"' in expression '"+c0+"'."}function cN(db){var df=cU;cU++;var de="";var dd=false;while(cU<c0.length){var dc=c0.charAt(cU);if(dd){de+=dc;dd=false}else{if(dc==="\\"){de+=dc;dd=true}else{if(dc==="/"){cU++;var c9="";if(c3(c0.charAt(cU))){cZ();c9=c2.pop().text}var da=new RegExp(de,c9);c2.push({index:df,text:de,flags:c9,fn:function(){return da}});return}else{de+=dc}}}cU++}throw"Lexer Error: Unterminated RegExp ["+c0.substring(df)+"] starting at column '"+(df+1)+"' in expression '"+c0+"'."}}function T(db,dj){var cZ=ci(0),de=bg(db,dj);return{assertAllConsumed:c5,primary:c2,statements:cR,validator:dk,filter:df,watch:c3};function da(dp,dn){throw"Token '"+dn.text+"' is "+dp+" at column='"+(dn.index+1)+"' of expression '"+db+"' starting at '"+db.substring(dn.index)+"'."}function cS(){if(de.length===0){throw"Unexpected end of expression: "+db}return de[0]}function cU(dt,ds,dr,dq){if(de.length>0){var dp=de[0];var dn=dp.text;if(dn==dt||dn==ds||dn==dr||dn==dq||(!dt&&!ds&&!dr&&!dq)){return dp}}return false}function cO(ds,dr,dq,dp){var dn=cU(ds,dr,dq,dp);if(dn){if(dj&&!dn.json){index=dn.index;throw"Expression at column='"+dn.index+"' of expression '"+db+"' starting at '"+db.substring(dn.index)+"' is not valid json."}de.shift();this.currentToken=dn;return dn}return false}function c7(dp){if(!cO(dp)){var dn=cU();throw"Expecting '"+dp+"' at column '"+(dn.index+1)+"' in '"+db+"' got '"+db.substring(dn.index)+"'."}}function cY(dp,dn){return function(dq){return dp(dq,dn(dq))}}function dl(dq,dp,dn){return function(dr){return dp(dr,dq(dr),dn(dr))}}function cX(){return de.length>0}function c5(){if(de.length!==0){throw"Did not understand '"+db.substring(de[0].index)+"' while evaluating '"+db+"'."}}function cR(){var dn=[];while(true){if(de.length>0&&!cU("}",")",";","]")){dn.push(cV())}if(!cO(";")){return function(dp){var ds;for(var dq=0;dq<dn.length;dq++){var dr=dn[dq];if(dr){ds=dr(dp)}}return ds}}}}function cV(){var dp=c9();var dn;while(true){if((dn=cO("|"))){dp=dl(dp,dn.fn,df())}else{return dp}}}function df(){return cM(cl)}function dk(){return cM(aF)}function cM(dq){var dr=cP(dq);var dn=[];var dp;while(true){if((dp=cO(":"))){dn.push(c9())}else{var ds=function(du,dt){var dv=[dt];for(var dw=0;dw<dn.length;dw++){dv.push(dn[dw](du))}return dr.apply(du,dv)};return function(){return ds}}}}function c9(){return c4()}function c4(){if(cO("throw")){var dn=c0();return function(dp){throw dn(dp)}}else{return c0()}}function c0(){var dq=dh();var dn;if(dn=cO("=")){if(!dq.isAssignable){throw"Left hand side '"+db.substring(0,dn.index)+"' of assignment '"+db.substring(dn.index)+"' is not assignable."}var dp=function(){return dq.isAssignable};return dl(dp,dn.fn,dh())}else{return dq}}function dh(){var dp=cW();var dn;while(true){if((dn=cO("||"))){dp=dl(dp,dn.fn,cW())}else{return dp}}}function cW(){var dp=cQ();var dn;if((dn=cO("&&"))){dp=dl(dp,dn.fn,cW())}return dp}function cQ(){var dp=dc();var dn;if((dn=cO("==","!="))){dp=dl(dp,dn.fn,cQ())}return dp}function dc(){var dp=dd();var dn;if(dn=cO("<",">","<=",">=")){dp=dl(dp,dn.fn,dc())}return dp}function dd(){var dp=cN();var dn;while(dn=cO("+","-")){dp=dl(dp,dn.fn,cN())}return dp}function cN(){var dp=c6();var dn;while(dn=cO("*","/","%")){dp=dl(dp,dn.fn,c6())}return dp}function c6(){var dn;if(cO("+")){return c2()}else{if(dn=cO("-")){return dl(cZ,dn.fn,c6())}else{if(dn=cO("!")){return cY(dn.fn,c6())}else{return c2()}}}}function cP(dt){var ds=cO();var dr=ds.text.split(".");var dn=dt;var dq;for(var dp=0;dp<dr.length;dp++){dq=dr[dp];if(dn){dn=dn[dq]}}if(typeof dn!=bp){throw"Function '"+ds.text+"' at column '"+(ds.index+1)+"' in '"+db+"' is not defined."}return dn}function c2(){var dq;if(cO("(")){var dr=cV();c7(")");dq=dr}else{if(cO("[")){dq=cT()}else{if(cO("{")){dq=di()}else{var dn=cO();dq=dn.fn;if(!dq){da("not a primary expression",dn)}}}}var dp;while(dp=cO("(","[",".")){if(dp.text==="("){dq=c8(dq)}else{if(dp.text==="["){dq=c1(dq)}else{if(dp.text==="."){dq=dg(dq)}else{throw"IMPOSSIBLE"}}}}return dq}function dg(dp){var dr=cO().text;var dn=cf(dr);var dq=function(ds){return dn(dp(ds))};dq.isAssignable=dr;return dq}function c1(dp){var dn=c9();c7("]");if(cO("=")){var dq=c9();return function(dr){return dp(dr)[dn(dr)]=dq(dr)}}else{return function(dr){var dt=dp(dr);var ds=dn(dr);return(dt)?dt[ds]:cI}}}function c8(dp){var dn=[];if(cS().text!=")"){do{dn.push(c9())}while(cO(","))}c7(")");return function(dr){var ds=[];for(var dt=0;dt<dn.length;dt++){ds.push(dn[dt](dr))}var dq=dp(dr)||j;return dq.apply?dq.apply(dr,ds):dq(ds[0],ds[1],ds[2],ds[3],ds[4])}}function cT(){var dn=[];if(cS().text!="]"){do{dn.push(c9())}while(cO(","))}c7("]");return function(dp){var dr=[];for(var dq=0;dq<dn.length;dq++){dr.push(dn[dq](dp))}return dr}}function di(){var dn=[];if(cS().text!="}"){do{var dq=cO(),dp=dq.string||dq.text;c7(":");var dr=c9();dn.push({key:dp,value:dr})}while(cO(","))}c7("}");return function(ds){var dt={};for(var du=0;du<dn.length;du++){var dw=dn[du];var dv=dw.value(ds);dt[dw.key]=dv}return dt}}function c3(){var dn=[];while(cX()){dn.push(dm());if(!cO(";")){c5()}}c5();return function(dp){for(var dq=0;dq<dn.length;dq++){var dr=dn[dq](dp);dp.addListener(dr.name,dr.fn)}}}function dm(){var dn=cO().text;c7(":");var dp;if(cS().text=="{"){c7("{");dp=cR();c7("}")}else{dp=c9()}return function(dq){return{name:dn,fn:dp}}}}function bO(cN,cO){this.template=cN=cN+"#";this.defaults=cO||{};var cM=this.urlParams={};aN(cN.split(/\W/),function(cP){if(cP&&cN.match(new RegExp(":"+cP+"\\W"))){cM[cP]=true}})}bO.prototype={url:function(cQ){var cP=[];var cM=this;var cN=this.template;cQ=cQ||{};aN(this.urlParams,function(cS,cR){var cT=cQ[cR]||cM.defaults[cR]||"";cN=cN.replace(new RegExp(":"+cR+"(\\W)"),cT+"$1")});cN=cN.replace(/\/?#$/,"");var cO=[];aq(cQ,function(cS,cR){if(!cM.urlParams[cR]){cO.push(encodeURI(cR)+"="+encodeURI(cS))}});cN=cN.replace(/\/*$/,"");return cN+(cO.length?"?"+cO.join("&"):"")}};function bE(cM){this.xhr=cM}bE.DEFAULT_ACTIONS={get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:true},remove:{method:"DELETE"},"delete":{method:"DELETE"}};bE.prototype={route:function(cP,cQ,cS){var cN=this;var cM=new bO(cP);cS=bY({},bE.DEFAULT_ACTIONS,cS);function cO(cU){var cT={};aN(cQ||{},function(cW,cV){cT[cV]=cW.charAt&&cW.charAt(0)=="@"?bH(cU,cW.substr(1)):cW});return cT}function cR(cT){bl(cT||{},this)}aN(cS,function(cV,cU){var cT=cV.method=="POST"||cV.method=="PUT";cR[cU]=function(cX,cW,c2){var c0={};var cZ;var c1=j;switch(arguments.length){case 3:c1=c2;case 2:if(D(cW)){c1=cW}else{c0=cX;cZ=cW;break}case 1:if(D(cX)){c1=cX}else{if(cT){cZ=cX}else{c0=cX}}break;case 0:break;default:throw"Expected between 0-3 arguments [params, data, callback], got "+arguments.length+" arguments."}var cY=this instanceof cR?this:(cV.isArray?[]:new cR(cZ));cN.xhr(cV.method,cM.url(bY({},cV.params||{},cO(cZ),c0)),cZ,function(c4,c5,c3){if(c4==200){if(cV.isArray){cY.length=0;aN(c5,function(c6){cY.push(new cR(c6))})}else{bl(c5,cY)}(c1||j)(cY)}else{throw {status:c4,response:c5,message:c4+": "+c5}}},cV.verifyCache);return cY};cR.bind=function(cW){return cN.route(cP,bY({},cQ,cW),cS)};cR.prototype["$"+cU]=function(cX,cW){var cZ=cO(this);var c0=j;switch(arguments.length){case 2:cZ=cX;c0=cW;case 1:if(typeof cX==bp){c0=cX}else{cZ=cX}case 0:break;default:throw"Expected between 1-2 arguments [params, callback], got "+arguments.length+" arguments."}var cY=cT?this:cI;cR[cU].call(this,cZ,cY,c0)}});return cR}};var M=bL.XMLHttpRequest||function(){try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(cO){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(cN){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(cM){}throw new Error("This browser does not support XMLHttpRequest.")};function aJ(cX,cV,cW,cT,c0){var cY=this;cY.isMock=false;var cQ=0;var cS=0;var cZ=[];cY.xhr=function(c7,c2,c3,c6){if(D(c3)){c6=c3;c3=a1}if(al(c7)=="json"){var c4="angular_"+Math.random()+"_"+(cQ++);c4=c4.replace(/\d\./,"");var c1=cV[0].createElement("script");c1.type="text/javascript";c1.src=c2.replace("JSON_CALLBACK",c4);bL[c4]=function(c8){bL[c4]=cI;c6(200,c8)};cW.append(c1)}else{var c5=new cT();c5.open(c7,c2,true);c5.setRequestHeader("Content-Type","application/x-www-form-urlencoded");c5.setRequestHeader("Accept","application/json, text/plain, */*");c5.setRequestHeader("X-Requested-With","XMLHttpRequest");cS++;c5.onreadystatechange=function(){if(c5.readyState==4){try{c6(c5.status||200,c5.responseText)}finally{cS--;if(cS===0){while(cZ.length){try{cZ.pop()()}catch(c8){}}}}}};c5.send(c3||"")}};cY.notifyWhenNoOutstandingRequests=function(c1){if(cS===0){c1()}else{cZ.push(c1)}};var cP=[];function cU(){aN(cP,function(c1){c1()})}cY.poll=cU;cY.addPollFn=function(c1){cP.push(c1);return c1};cY.startPoller=function(c2,c3){(function c1(){cU();c3(c1,c2)})()};cY.setUrl=function(c2){var c1=cX.href;if(!c1.match(/#/)){c1+="#"}if(!c2.match(/#/)){c2+="#"}cX.href=c2};cY.getUrl=function(){return cX.href};var cM=cV[0];var cO={};var cN="";cY.cookies=function(c2,c4){var c6,c1,c3,c5;if(c2){if(c4===cI){cM.cookie=escape(c2)+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT"}else{if(b9(c4)){cM.cookie=escape(c2)+"="+escape(c4);c6=c2.length+c4.length+1;if(c6>4096){c0.warn("Cookie '"+c2+"' possibly not set or overflowed because it was too large ("+c6+" > 4096 bytes)!")}if(cO.length>20){c0.warn("Cookie '"+c2+"' possibly not set or overflowed because too many cookies were already set ("+cO.length+" > 20 )")}}}}else{if(cM.cookie!==cN){cN=cM.cookie;c1=cN.split("; ");cO={};for(c3=0;c3<c1.length;c3++){c5=c1[c3].split("=");if(c5.length===2){cO[unescape(c5[0])]=unescape(c5[1])}}}return cO}};var cR=j;cY.hover=function(c1){cR=c1};cY.bind=function(){cV.bind("mouseover",function(c1){cR(cb(ar?c1.srcElement:c1.target),true);return true});cV.bind("mouseleave mouseout click dblclick keypress keyup",function(c1){cR(cb(c1.target),false);return true})};cY.addCss=function(c1){var c2=cb(cM.createElement("link"));c2.attr("rel","stylesheet");c2.attr("type","text/css");c2.attr("href",c1);cW.append(c2)};cY.addJs=function(c3,c2){var c1=cb(cM.createElement("script"));c1.attr("type","text/javascript");c1.attr("src",c3);if(c2){c1.attr("id",c2)}cW.append(c1)}}var bX=/^<\s*([\w:]+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,n=/^<\s*\/\s*([\w:]+)[^>]*>/,cj=/(\w+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g,cp=/^</,g=/^<\s*\//,az=/<!--(.*?)-->/g,bN=/<!\[CDATA\[(.*?)]]>/g;var aQ=cx("area,base,basefont,br,col,hr,img,input,isindex,link,param");var bT=cx("address,blockquote,button,center,dd,del,dir,div,dl,dt,fieldset,form,hr,ins,isindex,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");var ak=cx("a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");var L=cx("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");var aW=cx("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");var bF=cx("script,style");var bn=bY({},aQ,bT,ak,L);var a2=bY({},aW,cx("abbr,align,alink,alt,archive,axis,background,bgcolor,border,cellpadding,cellspacing,cite,class,classid,clear,code,codebase,codetype,color,cols,colspan,content,coords,data,dir,face,for,headers,height,href,hreflang,hspace,id,label,lang,language,link,longdesc,marginheight,marginwidth,maxlength,media,method,name,nowrap,profile,prompt,rel,rev,rows,rowspan,rules,scheme,scope,scrolling,shape,size,span,src,standby,start,summary,tabindex,target,text,title,type,usemap,valign,value,valuetype,vlink,vspace,width"));var aM=function(cN,cV){var cQ,cR,cO,cS=[],cT=cN;cS.last=function(){return cS[cS.length-1]};while(cN){cR=true;if(!cS.last()||!bF[cS.last()]){if(cN.indexOf("<!--")===0){cQ=cN.indexOf("-->");if(cQ>=0){if(cV.comment){cV.comment(cN.substring(4,cQ))}cN=cN.substring(cQ+3);cR=false}}else{if(g.test(cN)){cO=cN.match(n);if(cO){cN=cN.substring(cO[0].length);cO[0].replace(n,cP);cR=false}}else{if(cp.test(cN)){cO=cN.match(bX);if(cO){cN=cN.substring(cO[0].length);cO[0].replace(bX,cM);cR=false}}}}if(cR){cQ=cN.indexOf("<");var cU=cQ<0?cN:cN.substring(0,cQ);cN=cQ<0?"":cN.substring(cQ);if(cV.chars){cV.chars(cU)}}}else{cN=cN.replace(new RegExp("(.*)<\\s*\\/\\s*"+cS.last()+"[^>]*>","i"),function(cW,cX){cX=cX.replace(az,"$1").replace(bN,"$1");if(cV.chars){cV.chars(cX)}return""});cP("",cS.last())}if(cN==cT){throw"Parse Error: "+cN}cT=cN}cP();function cM(cW,cZ,c0,cX){cZ=al(cZ);if(bT[cZ]){while(cS.last()&&ak[cS.last()]){cP("",cS.last())}}if(L[cZ]&&cS.last()==cZ){cP("",cZ)}cX=aQ[cZ]||!!cX;if(!cX){cS.push(cZ)}if(cV.start){var cY={};c0.replace(cj,function(c2,c1){var c3=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:aW[c1]?c1:"";cY[c1]=c3});if(cV.start){cV.start(cZ,cY,cX)}}}function cP(cW,cY){var cZ=0,cX;cY=al(cY);if(cY){for(cZ=cS.length-1;cZ>=0;cZ--){if(cS[cZ]==cY){break}}}if(cZ>=0){for(cX=cS.length-1;cX>=cZ;cX--){if(cV.end){cV.end(cS[cX])}}cS.length=cZ}}};function cx(cP){var cO={},cM=cP.split(","),cN;for(cN=0;cN<cM.length;cN++){cO[cM[cN]]=true}return cO}var ag=/^javascript:/i,E=/ /gim,F=/&#x([\da-f]*);?/igm,cL=/&#(\d+);?/igm,bD=/[\w:]/gm,bK=function(cM,cN){return H(parseInt(cN,16))},cA=function(cM,cN){return H(cN)};function bG(cM){var cN=[];cM.replace(E,"").replace(F,bK).replace(cL,cA).replace(bD,function(cO){cN.push(cO)});return ag.test(al(cN.join("")))}function a0(cN){var cO=false;var cM=bu(cN,cN.push);return{start:function(cP,cR,cQ){cP=al(cP);if(!cO&&bF[cP]){cO=cP}if(!cO&&bn[cP]){cM("<");cM(cP);aN(cR,function(cT,cS){if(a2[al(cS)]&&!bG(cT)){cM(" ");cM(cS);cM('="');cM(cT.replace(/</g,"<").replace(/>/g,">").replace(/\"/g,"""));cM('"')}});cM(cQ?"/>":">")}},end:function(cP){cP=al(cP);if(!cO&&bn[cP]){cM("</");cM(cP);cM(">")}if(cP==cO){cO=false}},chars:function(cP){if(!cO){cM(cP.replace(/&(\w+[&;\W])?/g,function(cR,cQ){return cQ?cR:"&"}).replace(/</g,"<").replace(/>/g,">"))}}}}var b3={},cs="ng-"+new Date().getTime(),ai=1,ay=(bL.document.attachEvent?function(cM,cO,cN){cM.attachEvent("on"+cO,cN)}:function(cM,cO,cN){cM.addEventListener(cO,cN,false)}),e=(bL.document.detachEvent?function(cM,cO,cN){cM.detachEvent("on"+cO,cN)}:function(cM,cO,cN){cM.removeEventListener(cO,cN,false)});function b6(){return(ai++)}function cK(cN){var cO=cN[cs],cM=b3[cO];if(cM){aN(cM.bind||{},function(cQ,cP){e(cN,cP,cQ)});delete b3[cO];if(ar){cN[cs]=""}else{delete cN[cs]}}}function b2(cO){var cR={},cP=cO[0].style,cQ,cM,cN;if(typeof cP.length=="number"){for(cN=0;cN<cP.length;cN++){cM=cP[cN];cR[cM]=cP[cM]}}else{for(cM in cP){cQ=cP[cM];if(1*cM!=cM&&cM!="cssText"&&cQ&&typeof cQ=="string"&&cQ!="false"){cR[cM]=cQ}}}return cR}function bk(cN){if(by(cN)){this[0]=cN;this.length=1}else{if(cm(cN.length)&&cN.item){for(var cM=0;cM<cN.length;cM++){this[cM]=cN[cM]}this.length=cN.length}}}bk.prototype={data:function(cO,cP){var cN=this[0],cQ=cN[cs],cM=b3[cQ||-1];if(cm(cP)){if(!cM){cN[cs]=cQ=b6();cM=b3[cQ]={}}cM[cO]=cP}else{return cM?cM[cO]:a1}},removeData:function(){cK(this[0])},dealoc:function(){(function cM(cP){cK(cP);for(var cO=0,cN=cP.childNodes;cO<cN.length;cO++){cM(cN[cO])}})(this[0])},bind:function(cQ,cP){var cM=this,cO=cM[0],cR=cM.data("bind"),cN;if(!cR){this.data("bind",cR={})}aN(cQ.split(" "),function(cS){cN=cR[cS];if(!cN){cR[cS]=cN=function(cT){if(!cT.preventDefault){cT.preventDefault=function(){cT.returnValue=false}}if(!cT.stopPropagation){cT.stopPropagation=function(){cT.cancelBubble=true}}aN(cN.fns,function(cU){cU.call(cM,cT)})};cN.fns=[];ay(cO,cS,cN)}cN.fns.push(cP)})},replaceWith:function(cM){this[0].parentNode.replaceChild(cb(cM)[0],this[0])},children:function(){return new bk(this[0].childNodes)},append:function(cN){var cM=this[0];cN=cb(cN);aN(cN,function(cO){cM.appendChild(cO)})},remove:function(){this.dealoc();var cM=this[0].parentNode;if(cM){cM.removeChild(this[0])}},removeAttr:function(cM){this[0].removeAttribute(cM)},after:function(cM){this[0].parentNode.insertBefore(cb(cM)[0],this[0].nextSibling)},hasClass:function(cM){var cN=" "+cM+" ";if((" "+this[0].className+" ").replace(/[\n\t]/g," ").indexOf(cN)>-1){return true}return false},removeClass:function(cM){this[0].className=au((" "+this[0].className+" ").replace(/[\n\t]/g," ").replace(" "+cM+" ",""))},toggleClass:function(cM,cO){var cN=this;(cO?cN.addClass:cN.removeClass).call(cN,cM)},addClass:function(cM){if(!this.hasClass(cM)){this[0].className=au(this[0].className+" "+cM)}},css:function(cM,cO){var cN=this[0].style;if(b9(cM)){if(cm(cO)){cN[cM]=cO}else{return cN[cM]}}else{bY(cN,cM)}},attr:function(cM,cN){var cO=this[0];if(cH(cM)){aN(cM,function(cQ,cP){cO.setAttribute(cP,cQ)})}else{if(cm(cN)){cO.setAttribute(cM,cN)}else{return cO.getAttribute(cM,2)}}},text:function(cM){if(cm(cM)){this[0].textContent=cM}return this[0].textContent},val:function(cM){if(cm(cM)){this[0].value=cM}return this[0].value},html:function(cN){if(cm(cN)){var cM=0,cO=this[0].childNodes;for(;cM<cO.length;cM++){cb(cO[cM]).dealoc()}this[0].innerHTML=cN}return this[0].innerHTML},parent:function(){return cb(this[0].parentNode)},clone:function(){return cb(this[0].cloneNode(true))}};if(ar){bY(bk.prototype,{text:function(cM){var cN=this[0];if(cN.nodeType==3){if(cm(cM)){cN.nodeValue=cM}return cN.nodeValue}else{if(cm(cM)){cN.innerText=cM}return cN.innerText}}})}var aT={typeOf:function(cN){if(cN===a1){return v}var cM=typeof cN;if(cM==aK){if(cN instanceof Array){return aY}if(cN instanceof Date){return a5}if(cN.nodeType==1){return ct}}return cM}};var cG={copy:bl,size:av,equals:p};var ba={extend:bY};var N={indexOf:cE,sum:function(cR,cQ){var cO=ax.Function["compile"](cQ);var cN=0;for(var cM=0;cM<cR.length;cM++){var cP=1*cO(cR[cM]);if(!isNaN(cP)){cN+=cP}}return cN},remove:function(cO,cN){var cM=cE(cO,cN);if(cM>=0){cO.splice(cM,1)}return cN},filter:function(cT,cS){var cO=[];cO.check=function(cV){for(var cU=0;cU<cO.length;cU++){if(!cO[cU](cV)){return false}}return true};var cQ=function(cW,cX){if(cX.charAt(0)==="!"){return !cQ(cW,cX.substr(1))}switch(typeof cW){case"boolean":case"number":case"string":return(""+cW).toLowerCase().indexOf(cX)>-1;case"object":for(var cV in cW){if(cV.charAt(0)!=="$"&&cQ(cW[cV],cX)){return true}}return false;case"array":for(var cU=0;cU<cW.length;cU++){if(cQ(cW[cU],cX)){return true}}return false;default:return false}};switch(typeof cS){case"boolean":case"number":case"string":cS={$:cS};case"object":for(var cP in cS){if(cP=="$"){(function(){var cU=(""+cS[cP]).toLowerCase();if(!cU){return}cO.push(function(cV){return cQ(cV,cU)})})()}else{(function(){var cU=cP;var cV=(""+cS[cP]).toLowerCase();if(!cV){return}cO.push(function(cW){return cQ(bH(cW,cU),cV)})})()}}break;case bp:cO.push(cS);break;default:return cT}var cN=[];for(var cM=0;cM<cT.length;cM++){var cR=cT[cM];if(cO.check(cR)){cN.push(cR)}}return cN},add:function(cN,cM){cN.push(br(cM)?{}:cM);return cN},count:function(cP,cO){if(!cO){return cP.length}var cM=ax.Function["compile"](cO),cN=0;aN(cP,function(cQ){if(cM(cQ)){cN++}});return cN},orderBy:function(cT,cS,cQ){cS=a3(cS)?cS:[cS];cS=aD(cS,function(cV){var cW=false,cU=cV||aB;if(b9(cV)){if((cV.charAt(0)=="+"||cV.charAt(0)=="-")){cW=cV.charAt(0)=="-";cV=cV.substring(1)}cU=bj(cV).fnSelf}return cN(function(cY,cX){return cR(cU(cY),cU(cX))},cW)});var cP=[];for(var cO=0;cO<cT.length;cO++){cP.push(cT[cO])}return cP.sort(cN(cM,cQ));function cM(cX,cW){for(var cV=0;cV<cS.length;cV++){var cU=cS[cV](cX,cW);if(cU!==0){return cU}}return 0}function cN(cU,cV){return cg(cV)?function(cX,cW){return cU(cW,cX)}:cU}function cR(cX,cW){var cV=typeof cX;var cU=typeof cW;if(cV==cU){if(cV=="string"){cX=cX.toLowerCase()}if(cV=="string"){cW=cW.toLowerCase()}if(cX===cW){return 0}return cX<cW?-1:1}else{return cV<cU?-1:1}}}};var ap={quote:function(cM){return'"'+cM.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\v/g,"\\v")+'"'},quoteUnicode:function(cM){var cR=ax.String["quote"](cM);var cQ=[];for(var cN=0;cN<cR.length;cN++){var cO=cR.charCodeAt(cN);if(cO<128){cQ.push(cR.charAt(cN))}else{var cP="000"+cO.toString(16);cQ.push("\\u"+cP.substring(cP.length-4))}}return cQ.join("")},toDate:function(cO){var cN;if(typeof cO=="string"&&(cN=cO.match(/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z$/))){var cM=new Date(0);cM.setUTCFullYear(cN[1],cN[2]-1,cN[3]);cM.setUTCHours(cN[4],cN[5],cN[6],0);return cM}return cO}};var ad={toString:function(cM){function cN(cO){return cO<10?"0"+cO:cO}return !cM?cM:cM.getUTCFullYear()+"-"+cN(cM.getUTCMonth()+1)+"-"+cN(cM.getUTCDate())+"T"+cN(cM.getUTCHours())+":"+cN(cM.getUTCMinutes())+":"+cN(cM.getUTCSeconds())+"Z"}};var w={compile:function(cM){if(D(cM)){return cM}else{if(cM){return bj(cM).fnSelf}else{return aB}}}};function J(cN,cM){ax[cN]=ax[cN]||{};aN(cM,function(cO){bY(ax[cN],cO)})}J("Global",[aT]);J("Collection",[aT,cG]);J("Array",[aT,cG,N]);J("Object",[aT,cG,ba]);J("String",[aT,ap]);J("Date",[aT,ad]);ax.Date["toString"]=ad.toString;J("Function",[aT,cG,w]);cl.currency=function(cM){this.$element.toggleClass("ng-format-negative",cM<0);return"$"+cl.number.apply(this,[cM,2])};cl.number=function(cP,cM){if(isNaN(cP)||!isFinite(cP)){return""}cM=typeof cM==q?2:cM;var cN=cP<0;cP=Math.abs(cP);var cS=Math.pow(10,cM);var cU=""+Math.round(cP*cS);var cT=cU.substring(0,cU.length-cM);cT=cT||"0";var cO=cU.substring(cU.length-cM);cU=cN?"-":"";for(var cR=0;cR<cT.length;cR++){if((cT.length-cR)%3===0&&cR!==0){cU+=","}cU+=cT.charAt(cR)}if(cM>0){for(var cQ=cO.length;cQ<cM;cQ++){cO+="0"}cU+="."+cO.substring(0,cM)}return cU};function ce(cN,cO,cM){var cP="";if(cN<0){cP="-";cN=-cN}cN=""+cN;while(cN.length<cO){cN="0"+cN}if(cM){cN=cN.substr(cN.length-cO)}return cP+cN}function bh(cN,cO,cP,cM){return function(cQ){var cR=cQ["get"+cN]();if(cP>0||cR>-cP){cR+=cP}if(cR===0&&cP==-12){cR=12}return ce(cR,cO,cM)}}var bv={yyyy:bh("FullYear",4),yy:bh("FullYear",2,0,true),MM:bh("Month",2,1),M:bh("Month",1,1),dd:bh("Date",2),d:bh("Date",1),HH:bh("Hours",2),H:bh("Hours",1),hh:bh("Hours",2,-12),h:bh("Hours",1,-12),mm:bh("Minutes",2),m:bh("Minutes",1),ss:bh("Seconds",2),s:bh("Seconds",1),a:function(cM){return cM.getHours()<12?"am":"pm"},Z:function(cM){var cN=cM.getTimezoneOffset();return ce(cN/60,2)+ce(Math.abs(cN%60),2)}};var ao=/([^yMdHhmsaZ]*)(y+|M+|d+|H+|h+|m+|s+|a|Z)(.*)/;var ch=/^\d+$/;cl.date=function(cM,cP){if(b9(cM)&&ch.test(cM)){cM=parseInt(cM,10)}if(aP(cM)){cM=new Date(cM)}else{if(!(cM instanceof Date)){return cM}}var cQ=cM.toLocaleDateString(),cN;if(cP&&b9(cP)){cQ="";var cO=[];while(cP){cO=a6(cO,ao.exec(cP),1);cP=cO.pop()}aN(cO,function(cR){cN=bv[cR];cQ+=cN?cN(cM):cR})}return cQ};cl.json=function(cM){this.$element.addClass("ng-monospace");return cd(cM,true)};cl.lowercase=al;cl.uppercase=bx;cl.html=function(cM,cN){return new aR(cM,cN)};cl.linky=function(cT){if(!cT){return cT}var cM=/((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/;var cP;var cO=cT;var cR=[];var cS=a0(cR);var cN;var cQ;while(cP=cO.match(cM)){cN=cP[0];if(cP[2]==cP[3]){cN="mailto:"+cN}cQ=cP.index;cS.chars(cO.substr(0,cQ));cS.start("a",{href:cN});cS.chars(cP[0].replace(/^mailto:/,""));cS.end("a");cO=cO.substring(cQ+cP[0].length)}cS.chars(cO);return new aR(cR.join(""))};function aV(cM,cN){return{format:cM,parse:cN||cM}}function C(cM){return(cm(cM)&&cM!==a1)?""+cM:cM}var aO=/^\s*[-+]?\d*(\.\d*)?\s*$/;l.noop=aV(aB,aB);l.json=aV(cd,R);l["boolean"]=aV(C,cg);l.number=aV(C,function(cM){if(cM==a1||aO.exec(cM)){return cM===a1||cM===""?a1:1*cM}else{throw"Not a number"}});l.list=aV(function(cM){return cM?cM.join(", "):cM},function(cN){var cM=[];aN((cN||"").split(","),function(cO){cO=au(cO);if(cO){cM.push(cO)}});return cM});l.trim=aV(function(cM){return cM?au(""+cM):""});aN({noop:function(){return a1},regexp:function(cN,cM,cO){if(!cN.match(cM)){return cO||"Value does not match expected format "+cM+"."}else{return a1}},number:function(cP,cO,cM){var cN=1*cP;if(cN==cP){if(typeof cO!=q&&cN<cO){return"Value can not be less than "+cO+"."}if(typeof cO!=q&&cN>cM){return"Value can not be greater than "+cM+"."}return a1}else{return"Not a number"}},integer:function(cP,cN,cM){var cO=aF.number(cP,cN,cM);if(cO){return cO}if(!(""+cP).match(/^\s*[\d+]*\s*$/)||cP!=Math.round(cP)){return"Not a whole number"}return a1},date:function(cO){var cM=/^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(cO);var cN=cM?new Date(cM[3],cM[1]-1,cM[2]):0;return(cN&&cN.getFullYear()==cM[3]&&cN.getMonth()==cM[1]-1&&cN.getDate()==cM[2])?a1:"Value is not a date. (Expecting format: 12/31/2009)."},ssn:function(cM){if(cM.match(/^\d\d\d-\d\d-\d\d\d\d$/)){return a1}return"SSN needs to be in 999-99-9999 format."},email:function(cM){if(cM.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)){return a1}return"Email needs to be in [email protected] format."},phone:function(cM){if(cM.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)){return a1}if(cM.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)){return a1}return"Phone number needs to be in 1(987)654-3210 format in North America or +999 (123) 45678 906 internationaly."},url:function(cM){if(cM.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)){return a1}return"URL needs to be in http://server[:port]/path format."},json:function(cM){try{R(cM);return a1}catch(cN){return cN.toString()}},asynchronous:function(cP,cS,cN){if(!cP){return}var cR=this;var cQ=cR.$element;var cO=cQ.data("$asyncValidator");if(!cO){cQ.data("$asyncValidator",cO={inputs:{}})}cO.current=cP;var cM=cO.inputs[cP];if(!cM){cO.inputs[cP]=cM={inFlight:true};cR.$invalidWidgets.markInvalid(cR.$element);cQ.addClass("ng-input-indicator-wait");cS(cP,function(cT,cU){cM.response=cU;cM.error=cT;cM.inFlight=false;if(cO.current==cP){cQ.removeClass("ng-input-indicator-wait");cR.$invalidWidgets.markValid(cQ)}cQ.data("$validate")();cR.$root.$eval()})}else{if(cM.inFlight){cR.$invalidWidgets.markInvalid(cR.$element)}else{(cN||j)(cM.response)}}return cM.error}},function(cN,cM){aF[cM]=cN});var I=/^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,y=/^([^\?]*)?(\?([^\?]*))?$/,cr={http:80,https:443,ftp:21},bJ="eager",bz=bJ+"-published";function cc(cN,cP,cO,cM){bi(cN,cP,{$inject:cO,$creation:cM})}cc("$window",bu(bL,aB,bL),[],bz);cc("$document",function(cM){return cb(cM.document)},["$window"],bz);cc("$location",function(cT){var c1=this,cX={toString:cN,update:cS,updateHash:cW},cR=cT.getUrl(),cP,cU;cT.addPollFn(function(){if(cR!=cT.getUrl()){cS(cR=cT.getUrl());c0();c1.$eval()}});this.$onEval(bf,cV);this.$onEval(b7,cV);cS(cR);c0();return cX;function cS(c2){if(b9(c2)){bY(cX,cZ(c2))}else{if(cm(c2.hash)){bY(c2,cQ(c2.hash))}bY(cX,c2);if(cm(c2.hashPath||c2.hashSearch)){cX.hash=cO(cX)}cX.href=cY(cX)}}function cW(c4,c2){var c3={};if(b9(c4)){c3.hashPath=c4;if(cm(c2)){c3.hashSearch=c2}}else{c3.hashSearch=c4}cS(c3)}function cN(){cM();return cX.href}function cM(){if(cX.href==cP){if(cX.hash==cU){cX.hash=cO(cX)}cX.href=cY(cX)}cS(cX.href)}function c0(){cP=cX.href;cU=cX.hash}function cV(){cM();if(cX.href!=cP){cT.setUrl(cR=cX.href);c0()}}function cY(c4){var c3=O(c4.search);var c2=(c4.port==cr[c4.protocol]?a1:c4.port);return c4.protocol+"://"+c4.host+(c2?":"+c2:"")+c4.path+(c3?"?"+c3:"")+(c4.hash?"#"+c4.hash:"")}function cO(c3){var c2=O(c3.hashSearch);return escape(c3.hashPath)+(c2?"?"+c2:"")}function cZ(c2){var c4={};var c3=I.exec(c2);if(c3){c4.href=c2.replace(/#$/,"");c4.protocol=c3[1];c4.host=c3[3]||"";c4.port=c3[5]||cr[c4.protocol]||a1;c4.path=c3[6]||"";c4.search=af(c3[8]);c4.hash=c3[10]||"";bY(c4,cQ(c4.hash))}return c4}function cQ(c4){var c3={};var c2=y.exec(c4);if(c2){c3.hash=c4;c3.hashPath=unescape(c2[1]||"");c3.hashSearch=af(c2[3])}return c3}},["$browser"],bz);cc("$log",function(cO){var cM=cO.console||{log:j,warn:j,info:j,error:j},cN=cM.log||j;return{log:bu(cM,cN),warn:bu(cM,cM.warn||cN),info:bu(cM,cM.info||cN),error:bu(cM,cM.error||cN)}},["$window"],bz);cc("$exceptionHandler",function(cM){return function(cN){cM.error(cN)}},["$log"],bz);cc("$hover",function(cR,cN){var cT,cP=this,cQ,cS=300,cO=10,cM=cb(cN[0].body);cR.hover(function(cX,cV){if(cV&&(cQ=cX.attr(a)||cX.attr(k))){if(!cT){cT={callout:cb('<div id="ng-callout"></div>'),arrow:cb("<div></div>"),title:cb('<div class="ng-title"></div>'),content:cb('<div class="ng-content"></div>')};cT.callout.append(cT.arrow);cT.callout.append(cT.title);cT.callout.append(cT.content);cM.append(cT.callout)}var cU=cM[0].getBoundingClientRect(),cW=cX[0].getBoundingClientRect(),cY=cU.right-cW.right-cO;cT.title.text(cX.hasClass("ng-exception")?"EXCEPTION:":"Validation error...");cT.content.text(cQ);if(cY<cS){cT.arrow.addClass("ng-arrow-right");cT.arrow.css({left:(cS+1)+"px"});cT.callout.css({position:"fixed",left:(cW.left-cO-cS-4)+"px",top:(cW.top-3)+"px",width:cS+"px"})}else{cT.arrow.addClass("ng-arrow-left");cT.callout.css({position:"fixed",left:(cW.right+cO)+"px",top:(cW.top-3)+"px",width:cS+"px"})}}else{if(cT){cT.callout.remove();cT=a1}}})},["$browser","$document"],bJ);cc("$invalidWidgets",function(){var cN=[];cN.markValid=function(cP){var cO=cE(cN,cP);if(cO!=-1){cN.splice(cO,1)}};cN.markInvalid=function(cP){var cO=cE(cN,cP);if(cO===-1){cN.push(cP)}};cN.visible=function(){var cO=0;aN(cN,function(cP){cO=cO+(aL(cP)?1:0)});return cO};this.$onEval(b7,function(){for(var cO=0;cO<cN.length;){var cP=cN[cO];if(cM(cP[0])){cN.splice(cO,1);if(cP.dealoc){cP.dealoc()}}else{cO++}}});function cM(cP){if(cP==bL.document){return false}var cO=cP.parentNode;return !cO||cM(cO)}return cN},[],bz);function a9(cN,cM,cQ){var cP="^"+cM.replace(/[\.\\\(\)\^\$]/g,"$1")+"$",cR=[],cS={};aN(cM.split(/\W/),function(cU){if(cU){var cT=new RegExp(":"+cU+"([\\W])");if(cP.match(cT)){cP=cP.replace(cT,"([^/]*)$1");cR.push(cU)}}});var cO=cN.match(new RegExp(cP));if(cO){aN(cR,function(cU,cT){cS[cU]=cO[cT+1]});if(cQ){this.$set(cQ,cS)}}return cO?cS:a1}cc("$route",function(cN){var cM={},cO=[],cS=a9,cQ=this,cP=0,cT={routes:cM,onChange:bu(cO,cO.push),when:function(cV,cW){if(ax.isUndefined(cV)){return cM}var cU=cM[cV];if(!cU){cU=cM[cV]={}}if(cW){ax.extend(cU,cW)}cP++;return cU}};function cR(){var cU;cT.current=a1;ax.foreach(cM,function(cV,cW){if(!cU){var cX=cS(cN.hashPath,cW);if(cX){cU=ax.scope(cQ);cT.current=ax.extend({},cV,{scope:cU,params:ax.extend({},cN.hashSearch,cX)})}}});ax.foreach(cO,cQ.$tryEval);if(cU){cU.$become(cT.current.controller)}}this.$watch(function(){return cP+cN.hash},cR);return cT},["$location"],bz);cc("$xhr",function(cN,cM,cP){var cO=this;return function(cT,cQ,cR,cS){if(D(cR)){cS=cR;cR=a1}if(cR&&cH(cR)){cR=cd(cR)}cN.xhr(cT,cQ,cR,function(cV,cU){try{if(b9(cU)&&/^\s*[\[\{]/.exec(cU)&&/[\}\]]\s*$/.exec(cU)){cU=R(cU)}if(cV==200){cS(cV,cU)}else{cM({method:cT,url:cQ,data:cR,callback:cS},{status:cV,body:cU})}}catch(cW){cP.error(cW)}finally{cO.$eval()}})}},["$browser","$xhr.error","$log"]);cc("$xhr.error",function(cM){return function(cO,cN){cM.error("ERROR: XHR: "+cO.url,cO,cN)}},["$log"]);cc("$xhr.bulk",function(cN,cM,cQ){var cR=[],cP=this;function cO(cW,cS,cT,cV){if(D(cT)){cV=cT;cT=a1}var cU;aN(cO.urls,function(cX){if(D(cX.match)?cX.match(cS):cX.match.exec(cS)){cU=cX}});if(cU){if(!cU.requests){cU.requests=[]}cU.requests.push({method:cW,url:cS,data:cT,callback:cV})}else{cN(cW,cS,cT,cV)}}cO.urls={};cO.flush=function(cS){aN(cO.urls,function(cT,cU){var cV=cT.requests;if(cV&&cV.length){cT.requests=[];cT.callbacks=[];cN("POST",cU,{requests:cV},function(cX,cW){aN(cW,function(cY,cZ){try{if(cY.status==200){(cV[cZ].callback||j)(cY.status,cY.response)}else{cM(cV[cZ],cY)}}catch(c0){cQ.error(c0)}});(cS||j)()});cP.$eval()}})};this.$onEval(b7,cO.flush);return cO},["$xhr","$xhr.error","$log"]);cc("$xhr.cache",function(cM){var cP={},cO=this;function cN(cV,cQ,cR,cU,cT){if(D(cR)){cU=cR;cR=a1}if(cV=="GET"){var cS;if(cS=cN.data[cQ]){cU(200,bl(cS.value));if(!cT){return}}if(cS=cP[cQ]){cS.callbacks.push(cU)}else{cP[cQ]={callbacks:[cU]};cN.delegate(cV,cQ,cR,function(cW,cX){if(cW==200){cN.data[cQ]={value:cX}}var cY=cP[cQ].callbacks;delete cP[cQ];aN(cY,function(c0){try{(c0||j)(cW,bl(cX))}catch(cZ){cO.$log.error(cZ)}})})}}else{cN.data={};cN.delegate(cV,cQ,cR,cU)}}cN.data={};cN.delegate=cM;return cN},["$xhr.bulk"]);cc("$resource",function(cM){var cN=new bE(cM);return bu(cN,cN.route)},["$xhr.cache"]);cc("$cookies",function(cN){var cQ=this,cR={},cO={},cM;cN.addPollFn(function(){var cS=cN.cookies();if(cM!=cS){cM=cS;bl(cS,cO);bl(cS,cR);cQ.$eval()}})();this.$onEval(b7,cP);return cR;function cP(){var cT,cU,cS;for(cT in cO){if(br(cR[cT])){cN.cookies(cT,cI)}}for(cT in cR){if(cR[cT]!==cO[cT]){cN.cookies(cT,cR[cT]);cS=true}}if(cS){cS=!cS;cU=cN.cookies();for(cT in cR){if(cR[cT]!==cU[cT]){if(br(cU[cT])){delete cR[cT]}else{cR[cT]=cU[cT]}cS=true}}if(cS){cQ.$eval()}}}},["$browser"],bz);cc("$cookieStore",function(cM){return{get:function(cN){return R(cM[cN])},put:function(cN,cO){cM[cN]=cd(cO)},remove:function(cN){delete cM[cN]}}},["$cookies"]);aa("ng:init",function(cM){return function(cN){this.$tryEval(cM,cN)}});aa("ng:controller",function(cM){this.scope(true);return function(cO){var cN=bH(bL,cM,true)||bH(this,cM,true);if(!cN){throw"Can not find '"+cM+"' controller."}if(!D(cN)){throw"Reference '"+cM+"' is not a class."}this.$become(cN)}});aa("ng:eval",function(cM){return function(cN){this.$onEval(cM,cN)}});aa("ng:bind",function(cN,cM){cM.addClass("ng-binding");return function(cP){var cO=j,cQ=j;this.$onEval(function(){var cS,cW,cT,cU,cV,cR=this.hasOwnProperty(bo)?this.$element:cI;this.$element=cP;cW=this.$tryEval(cN,function(cX){cS=cd(cX)});this.$element=cR;if(cU=(cW instanceof aR)){cW=(cT=cW).html}if(cO===cW&&cQ==cS){return}cV=by(cW);if(!cU&&!cV&&cH(cW)){cW=cd(cW)}if(cW!=cO||cS!=cQ){cO=cW;cQ=cS;bR(cP,a,cS);if(cS){cW=cS}if(cU){cP.html(cT.get())}else{if(cV){cP.html("");cP.append(cW)}else{cP.text(cW===cI?"":cW)}}}},cP)}});var bs={};function cJ(cN){var cM=bs[cN];if(!cM){var cO=[];aN(aU(cN),function(cQ){var cP=cz(cQ);cO.push(cP?function(cS){var cR,cT=this.$tryEval(cP,function(cU){cR=cd(cU)});bR(cS,a,cR);return cR?cR:cT}:function(){return cQ})});bs[cN]=cM=function(cS){var cU=[],cP=this,cQ=this.hasOwnProperty(bo)?cP.$element:cI;cP.$element=cS;for(var cR=0;cR<cO.length;cR++){var cT=cO[cR].call(cP,cS);if(by(cT)){cT=""}else{if(cH(cT)){cT=cd(cT,true)}}cU.push(cT)}cP.$element=cQ;return cU.join("")}}return cM}aa("ng:bind-template",function(cN,cM){cM.addClass("ng-binding");var cO=cJ(cN);return function(cQ){var cP;this.$onEval(function(){var cR=cO.call(this,cQ);if(cR!=cP){cQ.text(cR);cP=cR}},cQ)}});var f={disabled:"disabled",readonly:"readOnly",checked:"checked"};aa("ng:bind-attr",function(cM){return function(cP){var cO={};var cN=cP.parent().data("$update");this.$onEval(function(){var cQ=this.$eval(cM);for(var cR in cQ){var cT=cJ(cQ[cR]).call(this,cP),cS=f[al(cR)];if(cO[cR]!==cT){cO[cR]=cT;if(cS){if(cP[cS]=cg(cT)){cP.attr(cS,cT)}else{cP.removeAttr(cR)}(cP.data("$validate")||j)()}else{cP.attr(cR,cT)}this.$postEval(cN)}}},cP)}});A("@ng:non-bindable",j);A("@ng:repeat",function(cO,cM){cM.removeAttr("ng:repeat");cM.replaceWith(this.comment("ng:repeat: "+cO));var cN=this.compile(cM);return function(cP){var cT=cO.match(/^\s*(.+)\s+in\s+(.*)\s*$/),cQ,cW,cR,cV;if(!cT){throw"Expected ng:repeat in form of 'item in collection' but got '"+cO+"'."}cQ=cT[1];cW=cT[2];cT=cQ.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/);if(!cT){throw"'item' in 'item in collection' should be identifier or (key, value) but got '"+keyValue+"'."}cR=cT[3]||cT[1];cV=cT[2];var cU=[],cS=this;this.$onEval(function(){var cZ=0,cY=cU.length,cX,c3=cP,c2=this.$tryEval(cW,cP),c1=a3(c2);for(var c0 in c2){if(!c1||c2.hasOwnProperty(c0)){if(cZ<cY){cX=cU[cZ];cX[cR]=c2[c0];if(cV){cX[cV]=c0}}else{cX=cN(z(cM),bM(cS));cX[cR]=c2[c0];if(cV){cX[cV]=c0}c3.after(cX.$element);cX.$index=cZ;cX.$element.attr("ng:repeat-index",cZ);cX.$init();cU.push(cX)}cX.$eval();c3=cX.$element;cZ++}}while(cU.length>cZ){cU.pop().$element.remove()}},cP)}});aa("ng:click",function(cN,cM){return function(cP){var cO=this;cP.bind("click",function(cQ){cO.$tryEval(cN,cP);cO.$root.$eval();cQ.stopPropagation()})}});aa("ng:submit",function(cN,cM){return function(cP){var cO=this;cP.bind("submit",function(cQ){cO.$tryEval(cN,cP);cO.$root.$eval();cQ.preventDefault()})}});aa("ng:watch",function(cN,cM){return function(cP){var cO=this;T(cN).watch()({addListener:function(cQ,cR){cO.$watch(cQ,function(){return cR(cO)},cP)}})}});function bt(cM){return function(cP,cN){var cO=cN[0].className+" ";return function(cQ){this.$onEval(function(){if(cM(this.$index)){var cR=this.$eval(cP);if(a3(cR)){cR=cR.join(" ")}cQ[0].className=au(cO+cR)}},cQ)}}}aa("ng:class",bt(function(){return true}));aa("ng:class-odd",bt(function(cM){return cM%2===0}));aa("ng:class-even",bt(function(cM){return cM%2===1}));aa("ng:show",function(cN,cM){return function(cO){this.$onEval(function(){cO.css(aG,cg(this.$eval(cN))?"":b)},cO)}});aa("ng:hide",function(cN,cM){return function(cO){this.$onEval(function(){cO.css(aG,cg(this.$eval(cN))?b:"")},cO)}});aa("ng:style",function(cN,cM){return function(cO){var cP=b2(cO);this.$onEval(function(){var cR=this.$eval(cN)||{},cQ,cS={};for(cQ in cR){if(cP[cQ]===cI){cP[cQ]=""}cS[cQ]=cR[cQ]}for(cQ in cP){cS[cQ]=cS[cQ]||cP[cQ]}cO.css(cS)},cO)}});function aU(cN){var cO=[];var cP=0;var cM;while((cM=cN.indexOf("{{",cP))>-1){if(cP<cM){cO.push(cN.substr(cP,cM-cP))}cP=cM;cM=cN.indexOf("}}",cM);cM=cM<0?cN.length:cM+2;cO.push(cN.substr(cP,cM-cP));cP=cM}if(cP!=cN.length){cO.push(cN.substr(cP,cN.length-cP))}return cO.length===0?[cN]:cO}function cz(cM){var cN=cM.replace(/\n/gm," ").match(/^\{\{(.*)\}\}$/);return cN?cN[1]:a1}function cy(cM){return cM.length>1||cz(cM[0])!==a1}ae("{{}}",function(cQ,cP,cM){var cS=aU(cQ),cN=this;if(cy(cS)){if(bV(cM[0])){cM.attr("ng:bind-template",cQ)}else{var cO=cP,cR;aN(aU(cQ),function(cV){var cU=cz(cV);if(cU){cR=cN.element("span");cR.attr("ng:bind",cU)}else{cR=cN.text(cV)}if(ar&&cV.charAt(0)==" "){cR=cb("<span> </span>");var cT=cR.html();cR.text(cV.substr(1));cR.html(cT+cR.html())}cO.after(cR);cO=cR});cP.remove()}}});ae("OPTION",function(cP,cO,cN){if(at(cN)=="OPTION"){var cM=r.createElement("select");cM.insertBefore(cN[0].cloneNode(true),a1);if(!cM.innerHTML.match(/<option(\s.*\s|\s)value\s*=\s*.*>.*<\/\s*option\s*>/gi)){cN.attr("value",cP)}}});var bA="ng:bind-attr";var aC={"ng:src":"src","ng:href":"href"};s("{{}}",function(cP,cN,cO){if(aa(cN)||aa("@"+cN)){return}if(ar&&cN=="src"){cP=decodeURI(cP)}var cQ=aU(cP),cM;if(cy(cQ)){cO.removeAttr(cN);cM=R(cO.attr(bA)||"{}");cM[aC[cN]||cN]=cP;cO.attr(bA,cd(cM))}});function bC(cN,cM){var cO=cM.attr("name");if(!cO){throw"Required field 'name' not found."}return{get:function(){return cN.$eval(cO)},set:function(cP){if(cP!==cI){return cN.$tryEval(cO+"="+cd(cP),cM)}}}}function bd(cP,cO){var cM=bC(cP,cO),cQ=cO.attr("ng:format")||o,cN=l(cQ);if(!cN){throw"Formatter named '"+cQ+"' not found."}return{get:function(){return cN.format(cM.get())},set:function(cR){return cM.set(cN.parse(cR))}}}function d(cM){return T(cM).validator()()}function bS(cX,cQ){var cO=cQ.attr("ng:validate")||o,cN=d(cO),cM=cQ.attr("ng:required"),cY=cQ.attr("ng:format")||o,cW=l(cY),cV,cP,cS,cR,cU=cX.$invalidWidgets||{markValid:j,markInvalid:j};if(!cN){throw"Validator named '"+cO+"' not found."}if(!cW){throw"Formatter named '"+cY+"' not found."}cV=cW.format;cP=cW.parse;if(cM){cX.$watch(cM,function(cZ){cR=cZ;cT()})}else{cR=cM===""}cQ.data("$validate",cT);return{get:function(){if(cS){bR(cQ,k,a1)}try{var cZ=cP(cQ.val());cT();return cZ}catch(c0){cS=c0;bR(cQ,k,c0)}},set:function(c0){var cZ=cQ.val(),c1=cV(c0);if(cZ!=c1){cQ.val(c1||"")}cT()}};function cT(){var c1=au(cQ.val());if(cQ[0].disabled||cQ[0].readOnly){bR(cQ,k,a1);cU.markValid(cQ)}else{var c0,cZ=bW(cX,{$element:cQ});c0=cR&&!c1?"Required":(c1?cN(cZ,c1):a1);bR(cQ,k,c0);cS=c0;if(c0){cU.markInvalid(cQ)}else{cU.markValid(cQ)}}}}function aE(cN,cM){var cP=cM[0],cO=cP.value;return{get:function(){return !!cP.checked},set:function(cQ){cP.checked=cg(cQ)}}}function cF(cN,cM){var cO=cM[0];return{get:function(){return cO.checked?cO.value:a1},set:function(cP){cO.checked=cP==cO.value}}}function cq(cO,cN){var cM=cN[0].options;return{get:function(){var cP=[];aN(cM,function(cQ){if(cQ.selected){cP.push(cQ.value)}});return cP},set:function(cP){var cQ={};aN(cP,function(cR){cQ[cR]=true});aN(cM,function(cR){cR.selected=cQ[cR.value]})}}}function P(){return{get:j,set:j}}var bb=bQ("keyup change",bC,bS,h()),bU=bQ("click",P,P,j),cC={text:bb,textarea:bb,hidden:bb,password:bb,button:bU,submit:bU,reset:bU,image:bU,checkbox:bQ("click",bd,aE,h(false)),radio:bQ("click",bd,cF,ck),"select-one":bQ("change",bd,bS,h(a1)),"select-multiple":bQ("change",bd,cq,h([]))};function h(cM){return function(cO,cN){var cP=cN.get();if(!cP&&cm(cM)){cP=bl(cM)}if(br(cO.get())&&cm(cP)){cO.set(cP)}}}function ck(cP,cM,cQ){var cO=cP.get(),cR=cM.get(),cN=cQ[0];cN.checked=false;cN.name=this.$id+"@"+cN.name;if(br(cO)){cP.set(cO=a1)}if(cO==a1&&cR!==a1){cP.set(cR)}cM.set(cO)}function bQ(cO,cN,cM,cP){return function(cT){var cU=this,cS=cN(cU,cT),cQ=cM(cU,cT),cV=cT.attr("ng:change")||"",cR;cP.call(cU,cS,cQ,cT);this.$eval(cT.attr("ng:init")||"");if(cV||cN!==P){cT.bind(cO,function(cX){cS.set(cQ.get());cR=cS.get();cU.$tryEval(cV,cT);cU.$root.$eval()})}function cW(){cQ.set(cR=cS.get())}cW();cT.data("$update",cW);cU.$watch(cS.get,function(cX){if(cR!==cX){cQ.set(cR=cX)}})}}function Y(cM){this.directives(true);return cC[al(cM[0].type)]||j}A("input",Y);A("textarea",Y);A("button",Y);A("select",function(cM){this.descend(true);return Y.call(this,cM)});A("option",function(){this.descend(true);this.directives(true);return function(cM){this.$postEval(cM.parent().data("$update"))}});A("ng:include",function(cN){var cO=this,cM=cN.attr("src"),cP=cN.attr("scope")||"";if(cN[0]["ng:compiled"]){this.descend(true);this.directives(true)}else{cN[0]["ng:compiled"]=true;return bY(function(cV,cS){var cU=this,cQ;var cW=0;var cT=false;function cR(){cW++}this.$watch(cM,cR);this.$watch(cP,cR);cU.$onEval(function(){if(cQ&&!cT){cT=true;try{cQ.$eval()}finally{cT=false}}});this.$watch(function(){return cW},function(){var cY=this.$eval(cM),cX=this.$eval(cP);if(cY){cV("GET",cY,function(c0,cZ){cS.html(cZ);cQ=cX||bM(cU);cO.compile(cS)(cS,cQ);cQ.$init()})}else{cQ=null;cS.html("")}})},{$inject:["$xhr.cache"]})}});var m=A("ng:switch",function(cQ){var cR=this,cP=cQ.attr("on"),cT=(cQ.attr("using")||"equals"),cM=cT.split(":"),cN=m[cM.shift()],cO=cQ.attr("change")||"",cS=[];if(!cN){throw"Using expression '"+cT+"' unknown."}aS(cQ,function(cV){var cU=cV.attr("ng:switch-when");if(cU){cS.push({when:function(cX,cY){var cW=[cY,cU];aN(cM,function(cZ){cW.push(cZ)});return cN.apply(cX,cW)},change:cO,element:cV,template:cR.compile(cV)})}});aN(cS,function(cU){cU.element.remove()});cQ.html("");return function(cV){var cW=this,cU;this.$watch(cP,function(cX){cV.html("");cU=bM(cW);aN(cS,function(cY){if(cY.when(cU,cX)){var cZ=z(cY.element);cV.append(cZ);cU.$tryEval(cY.change,cV);cY.template(cZ,cU);cU.$init()}})});cW.$onEval(function(){if(cU){cU.$eval()}})}},{equals:function(cN,cM){return cN==cM},route:a9});ax.widget("a",function(){this.descend(true);this.directives(true);return function(cM){if(cM.attr("href")===""){cM.bind("click",function(cN){cN.preventDefault()})}}});var ca;bi("$browser",function(cM){if(!ca){ca=new aJ(bL.location,cb(bL.document),cb(bL.document.getElementsByTagName("head")[0]),M,cM);ca.startPoller(50,function(cN,cO){setTimeout(cN,cO)});ca.bind()}return ca},{inject:["$log"]});bY(ax,{element:cb,compile:aX,scope:bM,copy:bl,extend:bY,equals:p,foreach:aN,injector:bP,noop:j,bind:bu,toJson:cd,fromJson:R,identity:aB,isUndefined:br,isDefined:cm,isString:b9,isFunction:D,isObject:cH,isNumber:aP,isArray:a3});ax.scenario=ax.scenario||{};ax.scenario.output=ax.scenario.output||function(cM,cN){ax.scenario.output[cM]=cN};ax.scenario.dsl=ax.scenario.dsl||function(cM,cN){ax.scenario.dsl[cM]=function(){function cO(cU,cS){var cQ=cU.apply(this,cS);if(ax.isFunction(cQ)||cQ instanceof ax.scenario.Future){return cQ}var cR=this;var cT=ax.extend({},cQ);ax.foreach(cT,function(cW,cV){if(ax.isFunction(cW)){cT[cV]=function(){return cO.call(cR,cW,arguments)}}else{cT[cV]=cW}});return cT}var cP=cN.apply(this,arguments);return function(){return cO.call(this,cP,arguments)}}};ax.scenario.matcher=ax.scenario.matcher||function(cM,cN){ax.scenario.matcher[cM]=function(cP){var cQ="expect "+this.future.name+" ";if(this.inverse){cQ+="not "}var cO=this;this.addFuture(cQ+cM+" "+ax.toJson(cP),function(cR){var cS;cO.actual=cO.future.value;if((cO.inverse&&cN.call(cO,cP))||(!cO.inverse&&!cN.call(cO,cP))){cS="expected "+ax.toJson(cP)+" but was "+ax.toJson(cO.actual)}cR(cS)})}};function i(cR,cQ){var cO=bL.location.href;var cM=bZ(r.body);var cN=[];if(cQ.scenario_output){cN=cQ.scenario_output.split(",")}ax.foreach(ax.scenario.output,function(cV,cT){if(!cN.length||cE(cN,cT)!=-1){var cU=cM.append("<div></div>").find("div:last");cU.attr("id",cT);cV.call({},cU,cR)}});if(!/^http/.test(cO)&&!/^https/.test(cO)){cM.append('<p id="system-error"></p>');cM.find("#system-error").text("Scenario runner must be run using http or https. The protocol "+cO.split(":")[0]+":// is not supported.");return}var cS=cM.append('<div id="application"></div>').find("#application");var cP=new ax.scenario.Application(cS);cR.on("RunnerEnd",function(){cS.css("display","none");cS.find("iframe").attr("src","about:blank")});cR.on("RunnerError",function(cT){if(bL.console){console.log(W(cT))}else{alert(cT)}});cR.run(cP)}function X(cQ,cP,cN){var cO=0;function cM(cS,cR){if(cR&&cR>cO){cO=cR}if(cS||cO>=cQ.length){cN(cS)}else{try{cP(cQ[cO++],cM)}catch(cT){cN(cT)}}}cM()}function W(cN,cO){cO=cO||5;var cP=cN.toString();if(cN.stack){var cM=cN.stack.split("\n");if(cM[0].indexOf(cP)===-1){cO++;cM.unshift(cN.message)}cP=cM.slice(0,cO).join("\n")}return cP}function x(cN){var cM=new Error();return function(){var cO=(cM.stack||"").split("\n")[cN];if(cO){if(cO.indexOf("@")!==-1){cO=cO.substring(cO.indexOf("@")+1)}else{cO=cO.substring(cO.indexOf("(")+1).replace(")","")}}return cO||""}}function c(cM,cN){if(cM&&!cM.nodeName){cM=cM[0]}if(!cM){return}if(!cN){cN={text:"change",textarea:"change",hidden:"change",password:"change",button:"click",submit:"click",reset:"click",image:"click",checkbox:"click",radio:"click","select-one":"change","select-multiple":"change"}[cM.type]||"click"}if(al(at(cM))=="option"){cM.parentNode.value=cM.value;cM=cM.parentNode;cN="change"}if(ar){switch(cM.type){case"radio":case"checkbox":cM.checked=!cM.checked;break}cM.fireEvent("on"+cN);if(al(cM.type)=="submit"){while(cM){if(al(cM.nodeName)=="form"){cM.fireEvent("onsubmit");break}cM=cM.parentNode}}}else{var cO=r.createEvent("MouseEvents");cO.initMouseEvent(cN,true,true,bL,0,0,0,0,0,false,false,false,false,0,cM);cM.dispatchEvent(cO)}}(function(cN){var cM=cN.trigger;cN.trigger=function(cO){if(/(click|change|keyup)/.test(cO)){return this.each(function(cP,cQ){c(cQ,cO)})}return cM.apply(this,arguments)}})(bZ.fn);ax.scenario.Application=function(cM){this.context=cM;cM.append('<h2>Current URL: <a href="about:blank">None</a></h2><div id="test-frames"></div>')};ax.scenario.Application.prototype.getFrame_=function(){return this.context.find("#test-frames iframe:last")};ax.scenario.Application.prototype.getWindow_=function(){var cM=this.getFrame_().attr("contentWindow");if(!cM){throw"Frame window is not accessible."}return cM};ax.scenario.Application.prototype.checkUrlStatus_=function(cN,cO){var cM=this;bZ.ajax({url:cN,type:"HEAD",complete:function(cP){if(cP.status<200||cP.status>=300){if(!cP.status){cO.call(cM,"Sandbox Error: Cannot access "+cN)}else{cO.call(cM,cP.status+" "+cP.statusText)}}else{cO.call(cM)}}})};ax.scenario.Application.prototype.navigateTo=function(cN,cO,cQ){var cM=this;var cP=this.getFrame_();cQ=cQ||function(cR){throw cR};if(cN==="about:blank"){cQ("Sandbox Error: Navigating to about:blank is not allowed.")}else{if(cN.charAt(0)==="#"){cN=cP.attr("src").split("#")[0]+cN;cP.attr("src",cN);this.executeAction(cO)}else{cP.css("display","none").attr("src","about:blank");this.checkUrlStatus_(cN,function(cR){if(cR){return cQ(cR)}cM.context.find("#test-frames").append("<iframe>");cP=this.getFrame_();cP.load(function(){cP.unbind();try{cM.executeAction(cO)}catch(cS){cQ(cS)}}).attr("src",cN)})}}this.context.find("> h2 a").attr("href",cN).text(cN)};ax.scenario.Application.prototype.executeAction=function(cO){var cN=this;var cP=this.getWindow_();if(!cP.document){throw"Sandbox Error: Application document not accessible."}if(!cP.angular){return cO.call(this,cP,bZ(cP.document))}var cM=cP.angular.service.$browser();cM.poll();cM.notifyWhenNoOutstandingRequests(function(){cO.call(cN,cP,bZ(cP.document))})};ax.scenario.Describe=function(cN,cP){this.only=cP&&cP.only;this.beforeEachFns=[];this.afterEachFns=[];this.its=[];this.children=[];this.name=cN;this.parent=cP;this.id=ax.scenario.Describe.id++;var cM=this.beforeEachFns;this.setupBefore=function(){if(cP){cP.setupBefore.call(this)}ax.foreach(cM,function(cQ){cQ.call(this)},this)};var cO=this.afterEachFns;this.setupAfter=function(){ax.foreach(cO,function(cQ){cQ.call(this)},this);if(cP){cP.setupAfter.call(this)}}};ax.scenario.Describe.id=0;ax.scenario.Describe.prototype.beforeEach=function(cM){this.beforeEachFns.push(cM)};ax.scenario.Describe.prototype.afterEach=function(cM){this.afterEachFns.push(cM)};ax.scenario.Describe.prototype.describe=function(cN,cM){var cO=new ax.scenario.Describe(cN,this);this.children.push(cO);cM.call(cO)};ax.scenario.Describe.prototype.ddescribe=function(cN,cM){var cO=new ax.scenario.Describe(cN,this);cO.only=true;this.children.push(cO);cM.call(cO)};ax.scenario.Describe.prototype.xdescribe=ax.noop;ax.scenario.Describe.prototype.it=function(cN,cM){this.its.push({definition:this,only:this.only,name:cN,before:this.setupBefore,body:cM,after:this.setupAfter})};ax.scenario.Describe.prototype.iit=function(cN,cM){this.it.apply(this,arguments);this.its[this.its.length-1].only=true};ax.scenario.Describe.prototype.xit=ax.noop;ax.scenario.Describe.prototype.getSpecs=function(){var cN=arguments[0]||[];ax.foreach(this.children,function(cO){cO.getSpecs(cN)});ax.foreach(this.its,function(cO){cN.push(cO)});var cM=[];ax.foreach(cN,function(cO){if(cO.only){cM.push(cO)}});return(cM.length&&cM)||cN};ax.scenario.Future=function(cN,cO,cM){this.name=cN;this.behavior=cO;this.fulfilled=false;this.value=undefined;this.parser=ax.identity;this.line=cM||function(){return""}};ax.scenario.Future.prototype.execute=function(cN){var cM=this;this.behavior(function(cP,cO){cM.fulfilled=true;if(cO){try{cO=cM.parser(cO)}catch(cQ){cP=cQ}}cM.value=cP||cO;cN(cP,cO)})};ax.scenario.Future.prototype.parsedWith=function(cM){this.parser=cM;return this};ax.scenario.Future.prototype.fromJson=function(){return this.parsedWith(ax.fromJson)};ax.scenario.Future.prototype.toJson=function(){return this.parsedWith(ax.toJson)};ax.scenario.ObjectModel=function(cO){var cN=this;this.specMap={};this.value={name:"",children:{}};cO.on("SpecBegin",function(cP){var cQ=cN.value;ax.foreach(cN.getDefinitionPath(cP),function(cR){if(!cQ.children[cR.name]){cQ.children[cR.name]={id:cR.id,name:cR.name,children:{},specs:{}}}cQ=cQ.children[cR.name]});cN.specMap[cP.id]=cQ.specs[cP.name]=new ax.scenario.ObjectModel.Spec(cP.id,cP.name)});cO.on("SpecError",function(cP,cQ){var cR=cN.getSpec(cP.id);cR.status="error";cR.error=cQ});cO.on("SpecEnd",function(cP){var cQ=cN.getSpec(cP.id);cM(cQ)});cO.on("StepBegin",function(cP,cR){var cQ=cN.getSpec(cP.id);cQ.steps.push(new ax.scenario.ObjectModel.Step(cR.name))});cO.on("StepEnd",function(cP,cR){var cQ=cN.getSpec(cP.id);if(cQ.getLastStep().name!==cR.name){throw"Events fired in the wrong order. Step names don' match."}cM(cQ.getLastStep())});cO.on("StepFailure",function(cP,cT,cQ){var cR=cN.getSpec(cP.id);var cS=cR.getLastStep();cS.error=cQ;if(!cR.status){cR.status=cS.status="failure"}});cO.on("StepError",function(cP,cT,cQ){var cR=cN.getSpec(cP.id);var cS=cR.getLastStep();cR.status="error";cS.status="error";cS.error=cQ});function cM(cP){cP.endTime=new Date().getTime();cP.duration=cP.endTime-cP.startTime;cP.status=cP.status||"success"}};ax.scenario.ObjectModel.prototype.getDefinitionPath=function(cM){var cO=[];var cN=cM.definition;while(cN&&cN.name){cO.unshift(cN);cN=cN.parent}return cO};ax.scenario.ObjectModel.prototype.getSpec=function(cM){return this.specMap[cM]};ax.scenario.ObjectModel.Spec=function(cN,cM){this.id=cN;this.name=cM;this.startTime=new Date().getTime();this.steps=[]};ax.scenario.ObjectModel.Spec.prototype.addStep=function(cM){var cN=new ax.scenario.ObjectModel.Step(cM);this.steps.push(cN);return cN};ax.scenario.ObjectModel.Spec.prototype.getLastStep=function(){return this.steps[this.steps.length-1]};ax.scenario.ObjectModel.Step=function(cM){this.name=cM;this.startTime=new Date().getTime()};ax.scenario.Describe=function(cN,cP){this.only=cP&&cP.only;this.beforeEachFns=[];this.afterEachFns=[];this.its=[];this.children=[];this.name=cN;this.parent=cP;this.id=ax.scenario.Describe.id++;var cM=this.beforeEachFns;this.setupBefore=function(){if(cP){cP.setupBefore.call(this)}ax.foreach(cM,function(cQ){cQ.call(this)},this)};var cO=this.afterEachFns;this.setupAfter=function(){ax.foreach(cO,function(cQ){cQ.call(this)},this);if(cP){cP.setupAfter.call(this)}}};ax.scenario.Describe.id=0;ax.scenario.Describe.prototype.beforeEach=function(cM){this.beforeEachFns.push(cM)};ax.scenario.Describe.prototype.afterEach=function(cM){this.afterEachFns.push(cM)};ax.scenario.Describe.prototype.describe=function(cN,cM){var cO=new ax.scenario.Describe(cN,this);this.children.push(cO);cM.call(cO)};ax.scenario.Describe.prototype.ddescribe=function(cN,cM){var cO=new ax.scenario.Describe(cN,this);cO.only=true;this.children.push(cO);cM.call(cO)};ax.scenario.Describe.prototype.xdescribe=ax.noop;ax.scenario.Describe.prototype.it=function(cN,cM){this.its.push({definition:this,only:this.only,name:cN,before:this.setupBefore,body:cM,after:this.setupAfter})};ax.scenario.Describe.prototype.iit=function(cN,cM){this.it.apply(this,arguments);this.its[this.its.length-1].only=true};ax.scenario.Describe.prototype.xit=ax.noop;ax.scenario.Describe.prototype.getSpecs=function(){var cN=arguments[0]||[];ax.foreach(this.children,function(cO){cO.getSpecs(cN)});ax.foreach(this.its,function(cO){cN.push(cO)});var cM=[];ax.foreach(cN,function(cO){if(cO.only){cM.push(cO)}});return(cM.length&&cM)||cN};ax.scenario.Runner=function(cM){this.listeners=[];this.$window=cM;this.rootDescribe=new ax.scenario.Describe();this.currentDescribe=this.rootDescribe;this.api={it:this.it,iit:this.iit,xit:ax.noop,describe:this.describe,ddescribe:this.ddescribe,xdescribe:ax.noop,beforeEach:this.beforeEach,afterEach:this.afterEach};ax.foreach(this.api,ax.bind(this,function(cO,cN){this.$window[cN]=ax.bind(this,cO)}))};ax.scenario.Runner.prototype.emit=function(cN){var cM=this;var cO=Array.prototype.slice.call(arguments,1);cN=cN.toLowerCase();if(!this.listeners[cN]){return}ax.foreach(this.listeners[cN],function(cP){cP.apply(cM,cO)})};ax.scenario.Runner.prototype.on=function(cM,cN){cM=cM.toLowerCase();this.listeners[cM]=this.listeners[cM]||[];this.listeners[cM].push(cN)};ax.scenario.Runner.prototype.describe=function(cO,cM){var cN=this;this.currentDescribe.describe(cO,function(){var cP=cN.currentDescribe;cN.currentDescribe=this;try{cM.call(this)}finally{cN.currentDescribe=cP}})};ax.scenario.Runner.prototype.ddescribe=function(cO,cM){var cN=this;this.currentDescribe.ddescribe(cO,function(){var cP=cN.currentDescribe;cN.currentDescribe=this;try{cM.call(this)}finally{cN.currentDescribe=cP}})};ax.scenario.Runner.prototype.it=function(cN,cM){this.currentDescribe.it(cN,cM)};ax.scenario.Runner.prototype.iit=function(cN,cM){this.currentDescribe.iit(cN,cM)};ax.scenario.Runner.prototype.beforeEach=function(cM){this.currentDescribe.beforeEach(cM)};ax.scenario.Runner.prototype.afterEach=function(cM){this.currentDescribe.afterEach(cM)};ax.scenario.Runner.prototype.createSpecRunner_=function(cM){return cM.$new(ax.scenario.SpecRunner)};ax.scenario.Runner.prototype.run=function(cN){var cM=this;var cO=ax.scope(this);cO.application=cN;this.emit("RunnerBegin");X(this.rootDescribe.getSpecs(),function(cP,cS){var cQ={};var cR=cM.createSpecRunner_(cO);ax.foreach(ax.scenario.dsl,function(cU,cT){cQ[cT]=cU.call(cO)});ax.foreach(ax.scenario.dsl,function(cU,cT){cM.$window[cT]=function(){var cV=x(3);var cW=ax.scope(cR);cW.dsl={};ax.foreach(cQ,function(cY,cX){cW.dsl[cX]=function(){return cQ[cX].apply(cW,arguments)}});cW.addFuture=function(){Array.prototype.push.call(arguments,cV);return ax.scenario.SpecRunner.prototype.addFuture.apply(cW,arguments)};cW.addFutureAction=function(){Array.prototype.push.call(arguments,cV);return ax.scenario.SpecRunner.prototype.addFutureAction.apply(cW,arguments)};return cW.dsl[cT].apply(cW,arguments)}});cR.run(cP,cS)},function(cP){if(cP){cM.emit("RunnerError",cP)}cM.emit("RunnerEnd")})};ax.scenario.SpecRunner=function(){this.futures=[];this.afterIndex=0};ax.scenario.SpecRunner.prototype.run=function(cN,cP){var cM=this;this.spec=cN;this.emit("SpecBegin",cN);try{cN.before.call(this);cN.body.call(this);this.afterIndex=this.futures.length;cN.after.call(this)}catch(cO){this.emit("SpecError",cN,cO);this.emit("SpecEnd",cN);cP();return}var cQ=function(cS,cR){if(cM.error){return cR()}cM.error=true;cR(null,cM.afterIndex)};X(this.futures,function(cR,cS){cM.step=cR;cM.emit("StepBegin",cN,cR);try{cR.execute(function(cU){if(cU){cM.emit("StepFailure",cN,cR,cU);cM.emit("StepEnd",cN,cR);return cQ(cU,cS)}cM.emit("StepEnd",cN,cR);cM.$window.setTimeout(function(){cS()},0)})}catch(cT){cM.emit("StepError",cN,cR,cT);cM.emit("StepEnd",cN,cR);cQ(cT,cS)}},function(cR){if(cR){cM.emit("SpecError",cN,cR)}cM.emit("SpecEnd",cN);cM.$window.setTimeout(function(){cP()},0)})};ax.scenario.SpecRunner.prototype.addFuture=function(cO,cP,cN){var cM=new ax.scenario.Future(cO,ax.bind(this,cP),cN);this.futures.push(cM);return cM};ax.scenario.SpecRunner.prototype.addFutureAction=function(cO,cP,cM){var cN=this;return this.addFuture(cO,function(cQ){this.application.executeAction(function(cT,cS){cS.elements=function(cV){var cW=Array.prototype.slice.call(arguments,1);cV=(cN.selector||"")+" "+(cV||"");ax.foreach(cW,function(cY,cX){cV=cV.replace("$"+(cX+1),cY)});var cU=cS.find(cV);if(!cU.length){throw {type:"selector",message:"Selector "+cV+" did not match any elements."}}return cU};try{cP.call(cN,cT,cS,cQ)}catch(cR){if(cR.type&&cR.type==="selector"){cQ(cR.message)}else{throw cR}}})},cM)};ax.scenario.dsl("wait",function(){return function(){return this.addFuture("waiting for you to resume",function(cM){this.emit("InteractiveWait",this.spec,this.step);this.$window.resume=function(){cM()}})}});ax.scenario.dsl("pause",function(){return function(cM){return this.addFuture("pause for "+cM+" seconds",function(cN){this.$window.setTimeout(function(){cN(null,cM*1000)},cM*1000)})}});ax.scenario.dsl("browser",function(){var cM={};cM.navigateTo=function(cO,cP){var cN=this.application;return this.addFuture("browser navigate to '"+cO+"'",function(cQ){if(cP){cO=cP.call(this,cO)}cN.navigateTo(cO,function(){cQ(null,cO)},cQ)})};cM.reload=function(){var cN=this.application;return this.addFutureAction("browser reload",function(cR,cQ,cO){var cP=cR.location.href;cN.navigateTo(cP,function(){cO(null,cP)},cO)})};cM.location=function(){var cN={};cN.href=function(){return this.addFutureAction("browser url",function(cQ,cP,cO){cO(null,cQ.location.href)})};cN.hash=function(){return this.addFutureAction("browser url hash",function(cQ,cP,cO){cO(null,cQ.location.hash.replace("#",""))})};cN.path=function(){return this.addFutureAction("browser url path",function(cQ,cP,cO){cO(null,cQ.location.pathname)})};cN.search=function(){return this.addFutureAction("browser url search",function(cQ,cP,cO){cO(null,cQ.angular.scope().$location.search)})};cN.hashSearch=function(){return this.addFutureAction("browser url hash search",function(cQ,cP,cO){cO(null,cQ.angular.scope().$location.hashSearch)})};cN.hashPath=function(){return this.addFutureAction("browser url hash path",function(cQ,cP,cO){cO(null,cQ.angular.scope().$location.hashPath)})};return cN};return function(cN){return cM}});ax.scenario.dsl("expect",function(){var cM=ax.extend({},ax.scenario.matcher);cM.not=function(){this.inverse=true;return cM};return function(cN){this.future=cN;return cM}});ax.scenario.dsl("using",function(){return function(cM,cN){this.selector=bZ.trim((this.selector||"")+" "+cM);if(ax.isString(cN)&&cN.length){this.label=cN+" ( "+this.selector+" )"}else{this.label=this.selector}return this.dsl}});ax.scenario.dsl("binding",function(){function cM(cO,cN){return cN instanceof RegExp?cN.test(cO):cO&&cO.indexOf(cN)>=0}return function(cN){return this.addFutureAction("select binding '"+cN+"'",function(cT,cS,cO){var cR=cS.elements(".ng-binding");for(var cQ=0;cQ<cR.length;cQ++){var cP=new cR.init(cR[cQ]);if(cM(cP.attr("ng:bind"),cN)||cM(cP.attr("ng:bind-template"),cN)){if(cP.is("input, textarea")){cO(null,cP.val())}else{cO(null,cP.html())}return}}cO("Binding selector '"+cN+"' did not match.")})}});ax.scenario.dsl("input",function(){var cM={};cM.enter=function(cN){return this.addFutureAction("input '"+this.name+"' enter '"+cN+"'",function(cR,cQ,cO){var cP=cQ.elements('input[name="$1"]',this.name);cP.val(cN);cP.trigger("change");cO()})};cM.check=function(){return this.addFutureAction("checkbox '"+this.name+"' toggle",function(cQ,cP,cN){var cO=cP.elements('input:checkbox[name="$1"]',this.name);cO.trigger("click");cN()})};cM.select=function(cN){return this.addFutureAction("radio button '"+this.name+"' toggle '"+cN+"'",function(cR,cQ,cO){var cP=cQ.elements('input:radio[name$="@$1"][value="$2"]',this.name,cN);cP.trigger("click");cO()})};return function(cN){this.name=cN;return cM}});ax.scenario.dsl("textarea",function(){var cM={};cM.enter=function(cN){return this.addFutureAction("textarea '"+this.name+"' enter '"+cN+"'",function(cR,cQ,cP){var cO=cQ.elements('textarea[name="$1"]',this.name);cO.val(cN);cO.trigger("change");cP()})};return function(cN){this.name=cN;return cM}});ax.scenario.dsl("repeater",function(){var cM={};cM.count=function(){return this.addFutureAction("repeater '"+this.label+"' count",function(cQ,cP,cN){try{cN(null,cP.elements().length)}catch(cO){cN(null,0)}})};cM.column=function(cN){return this.addFutureAction("repeater '"+this.label+"' column '"+cN+"'",function(cR,cQ,cO){var cP=[];cQ.elements().each(function(){bZ(this).find(":visible").each(function(){var cS=bZ(this);if(cS.attr("ng:bind")===cN){cP.push(cS.text())}})});cO(null,cP)})};cM.row=function(cN){return this.addFutureAction("repeater '"+this.label+"' row '"+cN+"'",function(cS,cR,cO){var cP=[];var cQ=cR.elements().slice(cN,cN+1);if(!cQ.length){return cO("row "+cN+" out of bounds")}bZ(cQ[0]).find(":visible").each(function(){var cT=bZ(this);if(ax.isDefined(cT.attr("ng:bind"))){cP.push(cT.text())}});cO(null,cP)})};return function(cN,cO){this.dsl.using(cN,cO);return cM}});ax.scenario.dsl("select",function(){var cM={};cM.option=function(cN){return this.addFutureAction("select '"+this.name+"' option '"+cN+"'",function(cR,cQ,cP){var cO=cQ.elements('select[name="$1"]',this.name);cO.val(cN);cO.trigger("change");cP()})};cM.options=function(){var cN=arguments;return this.addFutureAction("select '"+this.name+"' options '"+cN+"'",function(cR,cQ,cP){var cO=cQ.elements('select[multiple][name="$1"]',this.name);cO.val(cN);cO.trigger("change");cP()})};return function(cN){this.name=cN;return cM}});ax.scenario.dsl("element",function(){var cN=["val","text","html","height","innerHeight","outerHeight","width","innerWidth","outerWidth","position","scrollLeft","scrollTop","offset"];var cM={};cM.count=function(){return this.addFutureAction("element '"+this.label+"' count",function(cR,cQ,cO){try{cO(null,cQ.elements().length)}catch(cP){cO(null,0)}})};cM.click=function(){return this.addFutureAction("element '"+this.label+"' click",function(cS,cR,cO){var cQ=cR.elements();var cP=cQ.attr("href");cQ.trigger("click");if(cP&&cQ[0].nodeName.toUpperCase()==="A"){this.application.navigateTo(cP,function(){cO()},cO)}else{cO()}})};cM.attr=function(cO,cQ){var cP="element '"+this.label+"' get attribute '"+cO+"'";if(ax.isDefined(cQ)){cP="element '"+this.label+"' set attribute '"+cO+"' to '"+cQ+"'"}return this.addFutureAction(cP,function(cT,cS,cR){cR(null,cS.elements().attr(cO,cQ))})};cM.query=function(cO){return this.addFutureAction("element "+this.label+" custom query",function(cR,cQ,cP){cO.call(this,cQ.elements(),cP)})};ax.foreach(cN,function(cO){cM[cO]=function(cQ){var cP="element '"+this.label+"' "+cO;if(ax.isDefined(cQ)){cP="element '"+this.label+"' set "+cO+" to '"+cQ+"'"}return this.addFutureAction(cP,function(cU,cT,cR){var cS=cT.elements();cR(null,cS[cO].call(cS,cQ))})}});return function(cO,cP){this.dsl.using(cO,cP);return cM}});ax.scenario.matcher("toEqual",function(cM){return ax.equals(this.actual,cM)});ax.scenario.matcher("toBe",function(cM){return this.actual===cM});ax.scenario.matcher("toBeDefined",function(){return ax.isDefined(this.actual)});ax.scenario.matcher("toBeTruthy",function(){return this.actual});ax.scenario.matcher("toBeFalsy",function(){return !this.actual});ax.scenario.matcher("toMatch",function(cM){return new RegExp(cM).test(this.actual)});ax.scenario.matcher("toBeNull",function(){return this.actual===null});ax.scenario.matcher("toContain",function(cM){return u(this.actual,cM)});ax.scenario.matcher("toBeLessThan",function(cM){return this.actual<cM});ax.scenario.matcher("toBeGreaterThan",function(cM){return this.actual>cM});ax.scenario.output("html",function(cP,cR){var cO=new ax.scenario.ObjectModel(cR);cP.append('<div id="header"> <h1><span class="angular"><angular/></span>: Scenario Test Runner</h1> <ul id="status-legend" class="status-display"> <li class="status-error">0 Errors</li> <li class="status-failure">0 Failures</li> <li class="status-success">0 Passed</li> </ul></div><div id="specs"> <div class="test-children"></div></div>');cR.on("InteractiveWait",function(cS,cT){var cU=cO.getSpec(cS.id).getLastStep().ui;cU.find(".test-title").html('waiting for you to <a href="javascript:resume()">resume</a>.')});cR.on("SpecBegin",function(cS){var cT=cQ(cS);cT.find("> .tests").append('<li class="status-pending test-it"></li>');cT=cT.find("> .tests li:last");cT.append('<div class="test-info"> <p class="test-title"> <span class="timer-result"></span> <span class="test-name"></span> </p></div><div class="scrollpane"> <ol class="test-actions"></ol></div>');cT.find("> .test-info .test-name").text(cS.name);cT.find("> .test-info").click(function(){var cV=cT.find("> .scrollpane");var cW=cV.find("> .test-actions");var cU=cP.find("> .test-info .test-name");if(cW.find(":visible").length){cW.hide();cU.removeClass("open").addClass("closed")}else{cW.show();cV.attr("scrollTop",cV.attr("scrollHeight"));cU.removeClass("closed").addClass("open")}});cO.getSpec(cS.id).ui=cT});cR.on("SpecError",function(cS,cT){var cU=cO.getSpec(cS.id).ui;cU.append("<pre></pre>");cU.find("> pre").text(W(cT))});cR.on("SpecEnd",function(cS){cS=cO.getSpec(cS.id);cS.ui.removeClass("status-pending");cS.ui.addClass("status-"+cS.status);cS.ui.find("> .test-info .timer-result").text(cS.duration+"ms");if(cS.status==="success"){cS.ui.find("> .test-info .test-name").addClass("closed");cS.ui.find("> .scrollpane .test-actions").hide()}cN(cS.status)});cR.on("StepBegin",function(cS,cU){cS=cO.getSpec(cS.id);cU=cS.getLastStep();cS.ui.find("> .scrollpane .test-actions").append('<li class="status-pending"></li>');cU.ui=cS.ui.find("> .scrollpane .test-actions li:last");cU.ui.append('<div class="timer-result"></div><div class="test-title"></div>');cU.ui.find("> .test-title").text(cU.name);var cT=cU.ui.parents(".scrollpane");cT.attr("scrollTop",cT.attr("scrollHeight"))});cR.on("StepFailure",function(cS,cU,cT){var cV=cO.getSpec(cS.id).getLastStep().ui;cM(cV,cU.line,cT)});cR.on("StepError",function(cS,cU,cT){var cV=cO.getSpec(cS.id).getLastStep().ui;cM(cV,cU.line,cT)});cR.on("StepEnd",function(cS,cU){cS=cO.getSpec(cS.id);cU=cS.getLastStep();cU.ui.find(".timer-result").text(cU.duration+"ms");cU.ui.removeClass("status-pending");cU.ui.addClass("status-"+cU.status);var cT=cS.ui.find("> .scrollpane");cT.attr("scrollTop",cT.attr("scrollHeight"))});function cQ(cS){var cT=cP.find("#specs");ax.foreach(cO.getDefinitionPath(cS),function(cU){var cV="describe-"+cU.id;if(!cP.find("#"+cV).length){cT.find("> .test-children").append('<div class="test-describe" id="'+cV+'"> <h2></h2> <div class="test-children"></div> <ul class="tests"></ul></div>');cP.find("#"+cV).find("> h2").text("describe: "+cU.name)}cT=cP.find("#"+cV)});return cP.find("#describe-"+cS.definition.id)}function cN(cS){var cT=cP.find("#status-legend .status-"+cS);var cV=cT.text().split(" ");var cU=(cV[0]*1)+1;cT.text(cU+" "+cV[1])}function cM(cU,cS,cT){cU.find(".test-title").append("<pre></pre>");var cV=bZ.trim(cS()+"\n\n"+W(cT));cU.find(".test-title pre:last").text(cV)}});ax.scenario.output("json",function(cN,cO){var cM=new ax.scenario.ObjectModel(cO);cO.on("RunnerEnd",function(){cN.text(ax.toJson(cM.value))})});ax.scenario.output("xml",function(cN,cP){var cM=new ax.scenario.ObjectModel(cP);var cQ=function(cR){return new cN.init(cR)};cP.on("RunnerEnd",function(){var cR=cQ("<scenario></scenario>");cN.append(cR);cO(cR,cM.value)});function cO(cT,cR){ax.foreach(cR.children,function(cV){var cU=cQ("<describe></describe>");cU.attr("id",cV.id);cU.attr("name",cV.name);cT.append(cU);cO(cU,cV)});var cS=cQ("<its></its>");cT.append(cS);ax.foreach(cR.specs,function(cU){var cV=cQ("<it></it>");cV.attr("id",cU.id);cV.attr("name",cU.name);cV.attr("duration",cU.duration);cV.attr("status",cU.status);cS.append(cV);ax.foreach(cU.steps,function(cY){var cX=cQ("<step></step>");cX.attr("name",cY.name);cX.attr("duration",cY.duration);cX.attr("status",cY.status);cV.append(cX);if(cY.error){var cW=cQ("<error></error");cX.append(cW);cW.text(W(cX.error))}})})}});ax.scenario.output("object",function(cM,cN){cN.$window.$result=new ax.scenario.ObjectModel(cN).value});var aj=new ax.scenario.Runner(bL);bL.onload=function(){try{if(a8){a8()}}catch(cM){}i(aj,bw(r))}})(window,document,window.onload);document.write('<style type="text/css">@charset "UTF-8";\n\n.ng-format-negative {\n color: red;\n}\n\n.ng-exception {\n border: 2px solid #FF0000;\n font-family: "Courier New", Courier, monospace;\n font-size: smaller;\n}\n\n.ng-validation-error {\n border: 2px solid #FF0000;\n}\n\n\n/*****************\n * TIP\n *****************/\n#ng-callout {\n margin: 0;\n padding: 0;\n border: 0;\n outline: 0;\n font-size: 13px;\n font-weight: normal;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n vertical-align: baseline;\n background: transparent;\n text-decoration: none;\n}\n\n#ng-callout .ng-arrow-left{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n left:-12px;\n height:23px;\n width:10px;\n top:-3px;\n}\n\n#ng-callout .ng-arrow-right{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n height:23px;\n width:11px;\n top:-2px;\n}\n\n#ng-callout {\n position: absolute;\n z-index:100;\n border: 2px solid #CCCCCC;\n background-color: #fff;\n}\n\n#ng-callout .ng-content{\n padding:10px 10px 10px 10px;\n color:#333333;\n}\n\n#ng-callout .ng-title{\n background-color: #CCCCCC;\n text-align: left;\n padding-left: 8px;\n padding-bottom: 5px;\n padding-top: 2px;\n font-weight:bold;\n}\n\n\n/*****************\n * indicators\n *****************/\n.ng-input-indicator-wait {\n background-image: url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAkKAAAALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEvqxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEETAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQJCgAAACwAAAAAEAAQAAAFeCAgAgLZDGU5jgRECEUiCI+yioSDwDJyLKsXoHFQxBSHAoAAFBhqtMJg8DgQBgfrEsJAEAg4YhZIEiwgKtHiMBgtpg3wbUZXGO7kOb1MUKRFMysCChAoggJCIg0GC2aNe4gqQldfL4l/Ag1AXySJgn5LcoE3QXI3IQAh+QQJCgAAACwAAAAAEAAQAAAFdiAgAgLZNGU5joQhCEjxIssqEo8bC9BRjy9Ag7GILQ4QEoE0gBAEBcOpcBA0DoxSK/e8LRIHn+i1cK0IyKdg0VAoljYIg+GgnRrwVS/8IAkICyosBIQpBAMoKy9dImxPhS+GKkFrkX+TigtLlIyKXUF+NjagNiEAIfkECQoAAAAsAAAAABAAEAAABWwgIAICaRhlOY4EIgjH8R7LKhKHGwsMvb4AAy3WODBIBBKCsYA9TjuhDNDKEVSERezQEL0WrhXucRUQGuik7bFlngzqVW9LMl9XWvLdjFaJtDFqZ1cEZUB0dUgvL3dgP4WJZn4jkomWNpSTIyEAIfkECQoAAAAsAAAAABAAEAAABX4gIAICuSxlOY6CIgiD8RrEKgqGOwxwUrMlAoSwIzAGpJpgoSDAGifDY5kopBYDlEpAQBwevxfBtRIUGi8xwWkDNBCIwmC9Vq0aiQQDQuK+VgQPDXV9hCJjBwcFYU5pLwwHXQcMKSmNLQcIAExlbH8JBwttaX0ABAcNbWVbKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICSRBlOY7CIghN8zbEKsKoIjdFzZaEgUBHKChMJtRwcWpAWoWnifm6ESAMhO8lQK0EEAV3rFopIBCEcGwDKAqPh4HUrY4ICHH1dSoTFgcHUiZjBhAJB2AHDykpKAwHAwdzf19KkASIPl9cDgcnDkdtNwiMJCshACH5BAkKAAAALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAkKAAAALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQJCgAAACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");\n background-position: right;\n background-repeat: no-repeat;\n}\n</style>');document.write("<style type=\"text/css\">@charset \"UTF-8\";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: '\\25b8\\00A0';\n}\n\n.test-info .open:before {\n content: '\\25be\\00A0';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: '\\00bb\\00A0';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>"); |
web/react360/src/components/locs/Hero/HeroText.js | JamesMillercus/Portfolio-Website | /*eslint max-len: ["error", { "code": 800 }]*/
import React from 'react';
import {
View,
Text,
StyleSheet
} from 'react-360';
import { connect } from 'react-redux';
class HeroText extends React.Component {
textStyle() {
const { heroHover, heroText } = this.props;
if (heroText === 'scrolled') {
if (heroHover === 'centerLeftIcon') return this.styles.leftHeroText;
else if (heroHover === 'centerRightIcon') return this.styles.rightHeroText;
return this.styles.heroText;
}
return this.styles.unscrolledHeroText;
}
renderText() {
const {
heroText, heroHover, textNoScroll, textScrollHero, textScrollCenterLeftIcon, textScrollCenterRightIcon, logoTextScrolled, centerLogoIconName
} = this.props;
if (heroText === 'scrolled') {
if (heroHover === 'centerLeftIcon') return textScrollCenterLeftIcon;
else if (heroHover === 'centerRightIcon') return textScrollCenterRightIcon;
else if (heroHover === centerLogoIconName) return logoTextScrolled;
return textScrollHero;
}
return textNoScroll;
}
render() {
this.styles = StyleSheet.create({
heroText: {
marginTop: 270,
fontSize: 25,
color: this.props.textColorScrollHero,
fontWeight: 'bold',
textAlign: 'center',
position: 'absolute',
width: 700,
height: 80
},
unscrolledHeroText: {
marginTop: 270,
fontSize: 20,
color: this.props.textColorNoScroll,
fontWeight: 'bold',
textAlign: 'center',
position: 'absolute',
width: 700,
height: 80
},
leftHeroText: {
marginTop: 270,
fontSize: 25,
color: this.props.textColorScrollCenterLeftIcon,
fontWeight: 'bold',
textAlign: 'center',
position: 'absolute',
width: 700,
height: 80
},
rightHeroText: {
marginTop: 270,
fontSize: 25,
color: this.props.textColorScrollCenterRightIcon,
fontWeight: 'bold',
textAlign: 'center',
position: 'absolute',
width: 700,
height: 80
}
});
return (
<View>
<Text style={this.textStyle()} >
{this.renderText()}
</Text>
</View>
);
}
}
const mapStateToProps = ({ heroHover, heroText }) => ({ heroHover, heroText });
export default connect(mapStateToProps, null)(HeroText);
|
src/containers/DevTools/DevTools.js | captainill/react-redux-universal-hot-example | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="H"
changePositionKey="Q">
<LogMonitor />
</DockMonitor>
);
|
ajax/libs/react-table/5.0.1/react-table.js | maruilian11/cdnjs | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.reactTable = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}function _defineProperty(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function _toConsumableArray(t){if(Array.isArray(t)){for(var e=0,n=Array(t.length);e<t.length;e++)n[e]=t[e];return n}return Array.from(t)}var _typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};Object.defineProperty(exports,"__esModule",{value:!0});var _slicedToArray=function(){function t(t,e){var n=[],r=!0,o=!1,i=void 0;try{for(var u,a=t[Symbol.iterator]();!(r=(u=a.next()).done)&&(n.push(u.value),!e||n.length!==e);r=!0);}catch(t){o=!0,i=t}finally{try{!r&&a.return&&a.return()}finally{if(o)throw i}}return n}return function(e,n){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return t(e,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(t){return"undefined"==typeof t?"undefined":_typeof2(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":"undefined"==typeof t?"undefined":_typeof2(t)},_extends=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},_utils=require("./utils"),_utils2=_interopRequireDefault(_utils);exports.default={getDataModel:function(t,e){var n=this,r=this.getResolvedState(t,e),o=r.columns,i=r.pivotBy,u=void 0===i?[]:i,a=r.data,s=r.pivotIDKey,f=r.pivotValKey,c=r.subRowsKey,l=r.expanderColumnWidth,d=r.SubComponent,p=!1;o.forEach(function(t){t.columns&&(p=!0)});var h=[],g=[],y=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t[0];h.push(_extends({},n.props.column,e,{columns:t})),g=[]},m=o.map(function(t){return _extends({},t,{columns:t.columns?t.columns.filter(function(t){return!t.expander}):void 0})}),v=o.findIndex(function(t){return t.expander}),_=(d||u.length)&&v===-1,b=_?[{expander:!0}].concat(_toConsumableArray(m)):m;_&&(v=0);var S=function(t){var e=_extends({},n.props.column,t);if(e.expander)return e.width=l,e;if("string"==typeof e.accessor){var r=function(){e.id=e.id||e.accessor;var t=e.accessor;return e.accessor=function(e){return _utils2.default.get(e,t)},{v:e}}();if("object"===("undefined"==typeof r?"undefined":_typeof(r)))return r.v}if(e.accessor&&!e.id)throw console.warn(e),new Error("A column id is required if using a non-string accessor for column above.");return e.accessor||(e.accessor=function(t){}),e.maxWidth<e.minWidth&&(e.minWidth=e.maxWidth),e},x=function(t){var e=S(t);return C.push(e),e},C=[],D=b.map(function(t,e){return t.columns?_extends({},t,{columns:t.columns.map(x)}):x(t)}),w=D.slice(),O=[];if(w=w.map(function(t,e){if(t.columns){var n=t.columns.filter(function(t){return!(u.indexOf(t.id)>-1)&&_utils2.default.getFirstDefined(t.show,!0)});return _extends({},t,{columns:n})}return t}),w=w.filter(function(t){return t.columns?t.columns.length:!(u.indexOf(t.id)>-1)&&_utils2.default.getFirstDefined(t.show,!0)}),u.length){for(var P=[],R=0;R<C.length;R++)u.indexOf(C[R].id)>-1&&P.push(C[R]);var A=_extends({},P[0],{pivotColumns:P,expander:!0});w[v]=A}w.forEach(function(t,e){return t.columns?(O=O.concat(t.columns),g.length>0&&y(g),void y(t.columns,t)):(O.push(t),void g.push(t))}),p&&g.length>0&&y(g);var E=a.map(function(t,e){var n={__original:t,__index:e};return C.forEach(function(e){e.expander||(n[e.id]=e.accessor(t))}),n}),W=function(t){var e={};return I.forEach(function(n){var r=t.map(function(t){return t[n.id]});e[n.id]=n.aggregate(r,t)}),e},j=u.length?O.slice(1):O,I=j.filter(function(t){return t.aggregate}),K=void 0;return u.length&&!function(){K=O[0];var t=function t(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(r===n.length)return e;var o=Object.entries(_utils2.default.groupBy(e,n[r])).map(function(t){var e,o=_slicedToArray(t,2),i=o[0],u=o[1];return e={},_defineProperty(e,s,n[r]),_defineProperty(e,f,i),_defineProperty(e,n[r],i),_defineProperty(e,c,u),e});return o=o.map(function(e){var o=t(e[c],n,r+1);return _extends({},e,_defineProperty({},c,o),W(o))})};E=t(E,u)}(),{resolvedData:E,pivotColumn:K,allVisibleColumns:O,headerGroups:h,allDecoratedColumns:C,hasHeaderGroups:p}},getSortedData:function(t,e){var n=this.getResolvedState(t,e),r=n.manual,o=n.sorting,i=n.allDecoratedColumns,u=n.resolvedData,a=o.length?o:this.getInitSorting(i);return{resolvedSorting:a,sortedData:r?u:this.sortData(u,a)}},fireOnChange:function(){this.props.onChange(this.getResolvedState(),this)},getPropOrState:function(t){return _utils2.default.getFirstDefined(this.props[t],this.state[t])},getStateOrProp:function(t){return _utils2.default.getFirstDefined(this.state[t],this.props[t])},getInitSorting:function(t){if(!t)return[];var e=t.filter(function(t){return"undefined"!=typeof t.sort}).map(function(t){return{id:t.id,asc:"asc"===t.sort}});return e},sortData:function(t,e){var n=this,r=_utils2.default.orderBy(t,e.map(function(t){return function(e){return null===e[t.id]||void 0===e[t.id]?-(1/0):"string"==typeof e[t.id]?e[t.id].toLowerCase():e[t.id]}}),e.map(function(t){return t.asc?"asc":"desc"}));return r.map(function(t){return t[n.props.subRowsKey]?_extends({},t,_defineProperty({},n.props.subRowsKey,n.sortData(t[n.props.subRowsKey],e))):t})},getMinRows:function(){return _utils2.default.getFirstDefined(this.props.minRows,this.getStateOrProp("pageSize"))},onPageChange:function t(e){var n=this,t=this.props.onPageChange;return t?t(e):void this.setStateWithData({expandedRows:{},page:e},function(){n.fireOnChange()})},onPageSizeChange:function t(e){var n=this,t=this.props.onPageSizeChange,r=this.getResolvedState(),o=r.pageSize,i=r.page,u=o*i,a=Math.floor(u/e);return t?t(e,a):void this.setStateWithData({pageSize:e,page:a},function(){n.fireOnChange()})},sortColumn:function(t,e){var n=this,r=this.getResolvedState(),o=r.sorting,i=this.props.onSortingChange;if(i)return i(t,e);var u=_utils2.default.clone(o||[]);if(_utils2.default.isArray(t))!function(){var n=u.findIndex(function(e){return e.id===t[0].id});if(n>-1){var r=u[n];r.asc?t.forEach(function(t,e){u[n+e].asc=!1}):e?u.splice(n,t.length):t.forEach(function(t,e){u[n+e].asc=!0}),e||(u=u.slice(n,t.length))}else u=e?u.concat(t.map(function(t){return{id:t.id,asc:!0}})):t.map(function(t){return{id:t.id,asc:!0}})}();else{var a=u.findIndex(function(e){return e.id===t.id});if(a>-1){var s=u[a];s.asc?(s.asc=!1,e||(u=[s])):e?u.splice(a,1):(s.asc=!0,u=[s])}else e?u.push({id:t.id,asc:!0}):u=[{id:t.id,asc:!0}]}this.setStateWithData({page:!o.length&&u.length||!e?0:this.state.page,sorting:u},function(){n.fireOnChange()})}};
},{"./utils":4}],2:[function(require,module,exports){
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _objectWithoutProperties(e,t){var a={};for(var s in e)t.indexOf(s)>=0||Object.prototype.hasOwnProperty.call(e,s)&&(a[s]=e[s]);return a}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReactTableDefaults=void 0;var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(e[s]=a[s])}return e},_react=require("react"),_react2=_interopRequireDefault(_react),_classnames=require("classnames"),_classnames2=_interopRequireDefault(_classnames),_utils=require("./utils"),_utils2=_interopRequireDefault(_utils),_componentMethods=require("./componentMethods"),_componentMethods2=_interopRequireDefault(_componentMethods),_pagination=require("./pagination"),_pagination2=_interopRequireDefault(_pagination),emptyObj=function(){return{}},ReactTableDefaults={data:[],loading:!1,showPagination:!0,showPageSizeOptions:!0,pageSizeOptions:[5,10,20,25,50,100],defaultPageSize:20,showPageJump:!0,expanderColumnWidth:35,onExpandSubComponent:void 0,onPageChange:void 0,onPageSizeChange:void 0,onSortingChange:void 0,pivotBy:void 0,pivotColumnWidth:200,pivotValKey:"_pivotVal",pivotIDKey:"_pivotID",subRowsKey:"_subRows",onExpandRow:void 0,onChange:function(){return null},className:"",style:{},getProps:emptyObj,getTableProps:emptyObj,getTheadGroupProps:emptyObj,getTheadGroupTrProps:emptyObj,getTheadGroupThProps:emptyObj,getTheadProps:emptyObj,getTheadTrProps:emptyObj,getTheadThProps:emptyObj,getTbodyProps:emptyObj,getTrGroupProps:emptyObj,getTrProps:emptyObj,getThProps:emptyObj,getTdProps:emptyObj,getPaginationProps:emptyObj,getLoadingProps:emptyObj,column:{sortable:!0,show:!0,minWidth:100,render:void 0,className:"",style:{},getProps:function(){return{}},header:void 0,headerClassName:"",headerStyle:{},getHeaderProps:function(){return{}}},previousText:"Previous",nextText:"Next",loadingText:"Loading...",pageText:"Page",ofText:"of",rowsText:"rows",TableComponent:_utils2.default.makeTemplateComponent("rt-table"),TheadComponent:_utils2.default.makeTemplateComponent("rt-thead"),TbodyComponent:_utils2.default.makeTemplateComponent("rt-tbody"),TrGroupComponent:_utils2.default.makeTemplateComponent("rt-tr-group"),TrComponent:_utils2.default.makeTemplateComponent("rt-tr"),ThComponent:function(e){var t=e.toggleSort,a=e.className,s=e.children,n=_objectWithoutProperties(e,["toggleSort","className","children"]);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)(a,"rt-th"),onClick:function(e){t&&t(e)}},n),s)},TdComponent:_utils2.default.makeTemplateComponent("rt-td"),ExpanderComponent:function(e){var t=e.isExpanded,a=_objectWithoutProperties(e,["isExpanded"]);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)("rt-expander",t&&"-open")},a),"•")},PaginationComponent:_pagination2.default,PreviousComponent:void 0,NextComponent:void 0,LoadingComponent:function(e){var t=e.className,a=e.loading,s=e.loadingText,n=_objectWithoutProperties(e,["className","loading","loadingText"]);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)("-loading",{"-active":a},t)},n),_react2.default.createElement("div",{className:"-loading-inner"},s))}};exports.ReactTableDefaults=ReactTableDefaults,exports.default=_react2.default.createClass(_extends({displayName:"src",getDefaultProps:function(){return ReactTableDefaults},getInitialState:function(){return{page:0,pageSize:this.props.defaultPageSize||10,sorting:[],expandedRows:{}}},getResolvedState:function(e,t){var a=_extends({},this.state,t,this.props,e);return a},componentWillMount:function(){this.setStateWithData(this.getDataModel())},componentDidMount:function(){this.fireOnChange()},componentWillReceiveProps:function(e,t){var a=this.getResolvedState(),s=this.getResolvedState(e,t);a.data===s.data&&a.columns===s.columns&&a.pivotBy===s.pivotBy&&a.sorting===s.sorting||this.setStateWithData(this.getDataModel(e,t))},setStateWithData:function(e,t){var a=this.getResolvedState(),s=this.getResolvedState({},e);return a.resolvedData===s.resolvedData&&a.sorting===s.sorting||Object.assign(e,this.getSortedData({},e)),s.resolvedData&&(e.pages=s.manual?s.pages:Math.ceil(s.resolvedData.length/s.pageSize)),this.setState(e,t)},shouldComponentUpdate:function(e,t){var a=this.getResolvedState(),s=this.getResolvedState(e,t);return a.sortedData!==s.sortedData||a.page!==s.page||a.pageSize!==s.pageSize||a.expandedRows!==s.expandedRows},render:function(){var e=this,t=this.getResolvedState(),a=t.children,s=t.className,n=t.style,l=t.getProps,r=t.getTableProps,o=t.getTheadGroupProps,d=t.getTheadGroupTrProps,i=t.getTheadGroupThProps,u=t.getTheadProps,p=t.getTheadTrProps,c=t.getTheadThProps,m=t.getTbodyProps,f=t.getTrGroupProps,_=t.getTrProps,h=t.getThProps,g=t.getTdProps,x=t.getPaginationProps,v=t.getLoadingProps,y=t.showPagination,P=t.expanderColumnWidth,w=t.manual,T=t.loadingText,N=t.loading,C=t.pageSize,b=t.page,E=t.resolvedSorting,R=t.pages,D=t.pivotValKey,S=t.subRowsKey,W=t.expandedRows,O=t.onExpandRow,j=t.TableComponent,k=t.TheadComponent,M=t.TbodyComponent,G=t.TrGroupComponent,z=t.TrComponent,q=t.ThComponent,F=t.TdComponent,V=t.ExpanderComponent,K=t.PaginationComponent,I=t.LoadingComponent,L=t.SubComponent,H=t.resolvedData,B=t.allVisibleColumns,J=t.headerGroups,U=t.hasHeaderGroups,A=t.sortedData,Q=C*b,X=Q+C,Y=w?H:A.slice(Q,X),Z=this.getMinRows(),$=R>1?_utils2.default.range(C-Y.length):Z?_utils2.default.range(Math.max(Z-Y.length,0)):[],ee=function e(t){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;return t.forEach(function(t,n){s++,t._viewIndex=s;var l=a.concat([n]);t[S]&&_utils2.default.get(W,l)&&(s=e(t[S],l,s))}),s};ee(Y);var te=b>0,ae=b+1<R,se=_utils2.default.sum(B.map(function(e){return _utils2.default.getFirstDefined(e.width,e.minWidth)})),ne=-1,le=_extends({},t,{startRow:Q,endRow:X,pageRows:Y,minRows:Z,padRows:$,canPrevious:te,canNext:ae,rowMinWidth:se}),re=function(){var e=_utils2.default.splitProps(o(le)),t=_utils2.default.splitProps(d(le));return _react2.default.createElement(k,_extends({className:(0,_classnames2.default)("-headerGroups",e.className),style:_extends({},e.style,{minWidth:se+"px"})},e.rest),_react2.default.createElement(z,_extends({className:t.className,style:t.style},t.rest),J.map(oe)))},oe=function(e,t){var a=_utils2.default.sum(e.columns.map(function(e){return e.width?0:e.minWidth})),s=_utils2.default.sum(e.columns.map(function(e){return _utils2.default.getFirstDefined(e.width,e.minWidth)})),n=_utils2.default.sum(e.columns.map(function(e){return _utils2.default.getFirstDefined(e.width,e.maxWidth)})),l=_utils2.default.splitProps(i(le,void 0,e)),r=_utils2.default.splitProps(e.getHeaderProps(le,void 0,e)),o=[e.headerClassName,l.className,r.className],d=_extends({},e.headerStyle,l.style,r.style),u=_extends({},l.rest,r.rest),p={flex:a+" 0 auto",width:s+"px",maxWidth:n+"px"};return e.expander?e.pivotColumns?_react2.default.createElement(q,_extends({className:(0,_classnames2.default)("rt-pivot-header",o),style:_extends({},d,p)},u)):_react2.default.createElement(q,_extends({className:(0,_classnames2.default)("rt-expander-header",o),style:_extends({},d,{flex:"0 0 auto",width:P+"px"})},u)):_react2.default.createElement(q,_extends({key:t,className:(0,_classnames2.default)(o),style:_extends({},d,p)},u),"function"==typeof e.header?_react2.default.createElement(e.header,{data:A,column:e}):e.header)},de=function(){var e=_utils2.default.splitProps(u(le)),t=_utils2.default.splitProps(p(le));return _react2.default.createElement(k,_extends({className:(0,_classnames2.default)("-header",e.className),style:_extends({},e.style,{minWidth:se+"px"})},e.rest),_react2.default.createElement(z,_extends({className:t.className,style:t.style},t.rest),B.map(ie)))},ie=function(t,a){var s=E.find(function(e){return e.id===t.id}),n="function"==typeof t.show?t.show():t.show,l=_utils2.default.getFirstDefined(t.width,t.minWidth),r=_utils2.default.getFirstDefined(t.width,t.maxWidth),o=_utils2.default.splitProps(c(le,void 0,t)),d=_utils2.default.splitProps(t.getHeaderProps(le,void 0,t)),i=[t.headerClassName,o.className,d.className],u=_extends({},t.headerStyle,o.style,d.style),p=_extends({},o.rest,d.rest);if(t.expander){if(t.pivotColumns){var m=E.find(function(e){return e.id===t.id});return _react2.default.createElement(q,_extends({key:a,className:(0,_classnames2.default)("rt-pivot-header",t.sortable&&"-cursor-pointer",i,m?m.asc?"-sort-asc":"-sort-desc":""),style:_extends({},u,{flex:l+" 0 auto",width:l+"px",maxWidth:r+"px"}),toggleSort:function(a){t.sortable&&e.sortColumn(t.pivotColumns,a.shiftKey)}},p),t.pivotColumns.map(function(e,a){return _react2.default.createElement("span",{key:e.id},"function"==typeof e.header?_react2.default.createElement(e.header,{data:A,column:e}):e.header,a<t.pivotColumns.length-1&&_react2.default.createElement(V,null))}))}return _react2.default.createElement(q,_extends({key:a,className:(0,_classnames2.default)("rt-expander-header",i),style:_extends({},u,{flex:"0 0 auto",width:P+"px"})},p))}return _react2.default.createElement(q,_extends({key:a,className:(0,_classnames2.default)(i,s?s.asc?"-sort-asc":"-sort-desc":"",t.sortable&&"-cursor-pointer",!n&&"-hidden"),style:_extends({},u,{flex:l+" 0 auto",width:l+"px",maxWidth:r+"px"}),toggleSort:function(a){t.sortable&&e.sortColumn(t,a.shiftKey)}},p),"function"==typeof t.header?_react2.default.createElement(t.header,{data:A,column:t}):t.header)},ue=function t(a,s){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],l={row:a.__original,rowValues:a,index:a.__index,viewIndex:++ne,level:n.length,nestingPath:n.concat([s]),aggregated:!!a[S],subRows:a[S]},r=_utils2.default.get(W,l.nestingPath),o=f(le,l),d=_utils2.default.splitProps(_(le,l));return _react2.default.createElement(G,_extends({key:l.nestingPath.join("_")},o),_react2.default.createElement(z,_extends({className:(0,_classnames2.default)(d.className,a._viewIndex%2?"-even":"-odd"),style:d.style},d.rest),B.map(function(t,s){var n=t.render,o="function"==typeof t.show?t.show():t.show,d=_utils2.default.getFirstDefined(t.width,t.minWidth),i=_utils2.default.getFirstDefined(t.width,t.maxWidth),u=_utils2.default.splitProps(g(le,l,t)),p=_utils2.default.splitProps(t.getProps(le,l,t)),c=[u.className,t.className,p.className],m=_extends({},u.style,t.style,p.style);if(t.expander){var f=function(t){if(O)return O(l.nestingPath,t);var a=_utils2.default.clone(W);return r?e.setStateWithData({expandedRows:_utils2.default.set(a,l.nestingPath,!1)}):e.setStateWithData({expandedRows:_utils2.default.set(a,l.nestingPath,{})})};if(t.pivotColumns){var _=t.pivotRender;return _react2.default.createElement(F,_extends({className:(0,_classnames2.default)("rt-pivot",c),style:_extends({},m,{paddingLeft:1===l.nestingPath.length?void 0:30*(l.nestingPath.length-1)+"px",flex:d+" 0 auto",width:d+"px",maxWidth:i+"px"})},u.rest,{onClick:f}),l.subRows?_react2.default.createElement("span",null,_react2.default.createElement(V,{isExpanded:r}),t&&t.pivotRender?_react2.default.createElement(_,_extends({},l,{value:l.rowValues[D]})):_react2.default.createElement("span",null,a[D]," (",l.subRows.length,")")):L?_react2.default.createElement("span",null,_react2.default.createElement(V,{isExpanded:r})):null)}return _react2.default.createElement(F,{className:(0,_classnames2.default)(c,{hidden:!o}),style:_extends({},m,{flex:"0 0 auto",width:P+"px"}),onClick:f},_react2.default.createElement("span",null,_react2.default.createElement(V,{isExpanded:r})))}return _react2.default.createElement(F,_extends({key:s,className:(0,_classnames2.default)(c,!o&&"hidden"),style:_extends({},m,{flex:d+" 0 auto",width:d+"px",maxWidth:i+"px"})},u.rest),"function"==typeof n?_react2.default.createElement(n,_extends({},l,{value:l.rowValues[t.id]})):"undefined"!=typeof n?n:l.rowValues[t.id])})),l.subRows&&r&&l.subRows.map(function(e,a){return t(e,a,l.nestingPath)}),L&&!l.subRows&&r&&L(l))},pe=function(e,t){var a=f(le),s=_utils2.default.splitProps(_(le)),n=_utils2.default.splitProps(h(le));return _react2.default.createElement(G,_extends({key:t},a),_react2.default.createElement(z,{className:(0,_classnames2.default)("-padRow",s.className),style:s.style||{}},L&&_react2.default.createElement(q,_extends({className:(0,_classnames2.default)("rt-expander-header",n.className),style:_extends({},n.style,{flex:"0 0 auto",width:P+"px"})},n.rest)),B.map(function(e,t){var a="function"==typeof e.show?e.show():e.show,s=_utils2.default.getFirstDefined(e.width,e.minWidth),n=_utils2.default.getFirstDefined(e.width,e.maxWidth),l=_utils2.default.splitProps(g(le,void 0,e)),r=_utils2.default.splitProps(e.getProps(le,void 0,e)),o=[l.className,e.className,r.className],d=_extends({},l.style,e.style,r.style);return _react2.default.createElement(F,_extends({key:t,className:(0,_classnames2.default)(o,!a&&"hidden"),style:_extends({},d,{flex:s+" 0 auto",width:s+"px",maxWidth:n+"px"})},l.rest)," ")})))},ce=function(){var a=_utils2.default.splitProps(l(le)),o=_utils2.default.splitProps(r(le)),d=_utils2.default.splitProps(m(le)),i=_utils2.default.splitProps(x(le)),u=v(le);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)("ReactTable",s,a.className),style:_extends({},n,a.style)},a.rest),_react2.default.createElement(j,_extends({className:(0,_classnames2.default)(o.className),style:o.style},o.rest),U&&re(),de(),_react2.default.createElement(M,_extends({className:(0,_classnames2.default)(d.className),style:_extends({},d.style,{minWidth:se+"px"})},d.rest),Y.map(function(e,t){return ue(e,t)}),$.map(pe))),y&&_react2.default.createElement(K,_extends({},t,{pages:R,canPrevious:te,canNext:ae,onPageChange:e.onPageChange,onPageSizeChange:e.onPageSizeChange,className:i.className,style:i.style},i.rest)),_react2.default.createElement(I,_extends({loading:N,loadingText:T},u)))};return a?a(le,ce,this):ce()}},_componentMethods2.default));
},{"./componentMethods":1,"./pagination":3,"./utils":4,"classnames":5,"react":"react"}],3:[function(require,module,exports){
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},_react=require("react"),_react2=_interopRequireDefault(_react),_classnames=require("classnames"),_classnames2=_interopRequireDefault(_classnames),defaultButton=function(e){return _react2.default.createElement("button",_extends({},e,{className:"-btn"}),e.children)};exports.default=_react2.default.createClass({displayName:"pagination",getInitialState:function(){return{page:this.props.page}},componentWillReceiveProps:function(e){this.setState({page:e.page})},getSafePage:function(e){return Math.min(Math.max(e,0),this.props.pages-1)},changePage:function(e){e=this.getSafePage(e),this.setState({page:e}),this.props.onPageChange(e)},applyPage:function(e){e&&e.preventDefault();var t=this.state.page;this.changePage(""===t?this.props.page:t)},render:function(){var e=this,t=this.props,a=t.pages,n=t.page,s=t.showPageSizeOptions,r=t.pageSizeOptions,l=t.pageSize,c=t.showPageJump,i=t.canPrevious,p=t.canNext,o=t.onPageSizeChange,u=t.className,g=t.PreviousComponent,f=void 0===g?defaultButton:g,m=t.NextComponent,d=void 0===m?defaultButton:m;return _react2.default.createElement("div",{className:(0,_classnames2.default)(u,"-pagination"),style:this.props.paginationStyle},_react2.default.createElement("div",{className:"-previous"},_react2.default.createElement(f,{onClick:function(t){i&&e.changePage(n-1)},disabled:!i},this.props.previousText)),_react2.default.createElement("div",{className:"-center"},_react2.default.createElement("span",{className:"-pageInfo"},this.props.pageText," ",c?_react2.default.createElement("form",{className:"-pageJump",onSubmit:this.applyPage},_react2.default.createElement("input",{type:""===this.state.page?"text":"number",onChange:function(t){var a=t.target.value,n=a-1;return""===a?e.setState({page:a}):void e.setState({page:e.getSafePage(n)})},value:""===this.state.page?"":this.state.page+1,onBlur:this.applyPage})):_react2.default.createElement("span",{className:"-currentPage"},n+1)," ",this.props.ofText," ",_react2.default.createElement("span",{className:"-totalPages"},a)),s&&_react2.default.createElement("span",{className:"select-wrap -pageSizeOptions"},_react2.default.createElement("select",{onChange:function(e){return o(Number(e.target.value))},value:l},r.map(function(t,a){return _react2.default.createElement("option",{key:a,value:t},t," ",e.props.rowsText)})))),_react2.default.createElement("div",{className:"-next"},_react2.default.createElement(d,{onClick:function(t){p&&e.changePage(n+1)},disabled:!p},this.props.nextText)))}});
},{"classnames":5,"react":"react"}],4:[function(require,module,exports){
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _objectWithoutProperties(e,r){var t={};for(var n in e)r.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}function get(e,r,t){if(!r)return e;var n=makePathArray(r),a=void 0;try{a=n.reduce(function(e,r){return e[r]},e)}catch(e){}return"undefined"!=typeof a?a:t}function set(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments[1],t=arguments[2],n=makePathArray(r),a=void 0,i=e;(a=n.shift())&&n.length;)i[a]||(i[a]={}),i=i[a];return i[a]=t,e}function takeRight(e,r){var t=r>e.length?0:e.length-r;return e.slice(t)}function last(e){return e[e.length-1]}function range(e){for(var r=[],t=0;t<e;t++)r.push(e);return r}function orderBy(e,r,t){return e.sort(function(e,n){for(var a=0;a<r.length;a++){var i=r[a],o=i(e),u=i(n),s=t[a]===!1||"desc"===t[a];if(o>u)return s?-1:1;if(o<u)return s?1:-1}return t[0]?e.__index-n.__index:n.__index-n.__index})}function remove(e,r){return e.filter(function(t,n){var a=r(t);return!!a&&(e.splice(n,1),!0)})}function clone(e){try{return JSON.parse(JSON.stringify(e,function(e,r){return"function"==typeof r?r.toString():r}))}catch(r){return e}}function getFirstDefined(){for(var e=arguments.length,r=Array(e),t=0;t<e;t++)r[t]=arguments[t];for(var n=0;n<r.length;n++)if("undefined"!=typeof r[n])return r[n]}function sum(e){return e.reduce(function(e,r){return e+r},0)}function makeTemplateComponent(e){return function(r){var t=r.children,n=r.className,a=_objectWithoutProperties(r,["children","className"]);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)(e,n)},a),t)}}function groupBy(e,r){return e.reduce(function(e,t,n){var a="function"==typeof r?r(t,n):t[r];return e[a]=isArray(e[a])?e[a]:[],e[a].push(t),e},{})}function isArray(e){return Array.isArray(e)}function makePathArray(e){return flattenDeep(e).join(".").replace("[",".").replace("]","").split(".")}function flattenDeep(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(isArray(e))for(var t=0;t<e.length;t++)flattenDeep(e[t],r);else r.push(e);return r}function splitProps(e){var r=e.className,t=e.style,n=_objectWithoutProperties(e,["className","style"]);return{className:r,style:t,rest:n}}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},_react=require("react"),_react2=_interopRequireDefault(_react),_classnames=require("classnames"),_classnames2=_interopRequireDefault(_classnames);exports.default={get:get,set:set,takeRight:takeRight,last:last,orderBy:orderBy,range:range,remove:remove,clone:clone,getFirstDefined:getFirstDefined,sum:sum,makeTemplateComponent:makeTemplateComponent,groupBy:groupBy,isArray:isArray,splitProps:splitProps};
},{"classnames":5,"react":"react"}],5:[function(require,module,exports){
!function(){"use strict";function e(){for(var r=[],o=0;o<arguments.length;o++){var f=arguments[o];if(f){var i=typeof f;if("string"===i||"number"===i)r.push(f);else if(Array.isArray(f))r.push(e.apply(null,f));else if("object"===i)for(var t in f)n.call(f,t)&&f[t]&&r.push(t)}}return r.join(" ")}var n={}.hasOwnProperty;"undefined"!=typeof module&&module.exports?module.exports=e:"function"==typeof define&&"object"==typeof define.amd&&define.amd?define("classnames",[],function(){return e}):window.classNames=e}();
},{}]},{},[2])(2)
}); |
src/components/Projects.js | dtjv/dtjv.github.io | import React from 'react'
import { Project } from './Project'
export const Projects = ({ projects = [], feature }) => {
if (!projects.length) return null
const featuredProjects = projects.filter((project) => project.feature)
const nonFeaturedProjects = projects.filter((project) => !project.feature)
return (
<>
{feature ? (
<ul className="divide-y divide-gray-200">
{featuredProjects.map((project) => (
<li key={project.id} className="flex py-12 space-x-6">
<Project project={project} />
</li>
))}
</ul>
) : (
<ul className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-12">
{nonFeaturedProjects.map((project) => (
<li key={project.id} className="p-4 border rounded-lg shadow-md">
<Project project={{ ...project, images: [] }} />
</li>
))}
</ul>
)}
</>
)
}
|
rtsupport/index.js | rtran58/react-golang | import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.render(<App />, document.getElementById('root'));
|
ajax/libs/forerunnerdb/1.3.591/fdb-legacy.js | rlugojr/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind'),
Grid = _dereq_('../lib/Grid');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":33,"./Shared":39}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":33,"./Shared":39}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Crc,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
self.chainSend('insert', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
joinMatchData,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self._resolveDynamicQuery(joinMatchData.$query, resultArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatchData, resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = new Path(query.substr(3, query.length - 3)).value(item);
} else {
pathResult = new Path(query).value(item);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
case '2d':
index = new Index2d(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":7,"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],5:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":4,"./Shared":39}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],7:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Shared.mixin(FdbDocument.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)});
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
var result = this.updateObject(this._data, update, query, options);
if (result) {
this.deferEmit('change', {type: 'update', data: this.decouple(this._data)});
}
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance.
* @func document
* @memberof Db
* @param {String} documentName The name of the document to create.
* @returns {*}
*/
Db.prototype.document = function (documentName) {
if (documentName) {
// Handle being passed an instance
if (documentName instanceof FdbDocument) {
if (documentName.state() !== 'droppped') {
return documentName;
} else {
documentName = documentName.name();
}
}
this._document = this._document || {};
this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this);
return this._document[documentName];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":4,"./Shared":39}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Shared.mixin(Grid.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
delete this._listeners;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener );
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
template: [
'<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">',
'<input type="search" class="form-control gridFilterSearch" placeholder="Search...">',
'<span class="input-group-btn">',
'<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',
'</span>',
'</li>',
'<li role="presentation" class="divider"></li>',
'<li role="presentation" data-val="$all">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox" checked> All',
'</a>',
'</li>',
'<li role="presentation" class="divider"></li>',
'{^{for options}}',
'<li role="presentation" data-link="data-val{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy,
this._options
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
sData,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
if (xAxis.categories) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
} else {
seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]);
}
}
sData = {
name: seriesName,
data: seriesValues
};
if (options.seriesOptions) {
for (k in options.seriesOptions) {
if (options.seriesOptions.hasOwnProperty(k)) {
sData[k] = options.seriesOptions[k];
}
}
}
seriesData.push(sData);
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () {
self._changeListener.apply(self, arguments);
});
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () {
self.drop.apply(self);
});
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if (typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy,
self._options
);
if (seriesData.xAxis.categories) {
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
}
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
if (callback) {
callback(false, true);
}
delete this._listeners;
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via selector.
* @func lineChart
* @memberof Highchart
* @param {String} selector The chart selector.
* @returns {*}
*/
'string': function (selector) {
return this._highcharts[selector];
},
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":31,"./Shared":39}],13:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":33,"./Shared":39}],16:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":39}],17:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":30,"./Shared":39}],18:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],19:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, data, options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":31,"./Serialiser":38}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],22:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":31}],23:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
}
};
module.exports = Matching;
},{}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],28:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = this;
this._binds = [];
this._renderStart = 0;
this._renderEnd = 0;
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
_bindInsert: [],
_bindUpdate: [],
_bindRemove: [],
_bindUpsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100,
_bindInsert: 100,
_bindUpdate: 100,
_bindRemove: 100,
_bindUpsert: 100
};
this._deferTime = {
insert: 100,
update: 1,
remove: 1,
upsert: 1,
_bindInsert: 100,
_bindUpdate: 1,
_bindRemove: 1,
_bindUpsert: 1
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":39}],29:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
DbInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
delete this._listeners;
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._oldViews = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":4,"./CollectionGroup":5,"./Shared":39}],30:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":33,"./Shared":39}],31:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload: ', def);
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],32:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Shared.mixin(Overview.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
delete this._name;
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
}
return true;
};
Db.prototype.overview = function (overviewName) {
if (overviewName) {
// Handle being passed an instance
if (overviewName instanceof Overview) {
return overviewName;
}
this._overview = this._overview || {};
this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this);
return this._overview[overviewName];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":4,"./Document":9,"./Shared":39}],33:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":39}],34:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the auto flag which determines if the persistence module
* will automatically load data for collections the first time they are
* accessed and save data whenever it changes. This is disabled by
* default.
* @param {Boolean} val Set to true to enable, false to disable
* @returns {*}
*/
Shared.synthesize(Persist.prototype, 'auto', function (val) {
var self = this;
if (val !== undefined) {
if (val) {
// Hook db events
this._db.on('create', function () { self._autoLoad.apply(self, arguments); });
this._db.on('change', function () { self._autoSave.apply(self, arguments); });
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save enabled');
}
} else {
// Un-hook db events
this._db.off('create', this._autoLoad);
this._db.off('change', this._autoSave);
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save disbled');
}
}
}
return this.$super.call(this, val);
});
Persist.prototype._autoLoad = function (obj, objType, name) {
var self = this;
if (typeof obj.load === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name);
}
obj.load(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic load failed:', err);
}
self.emit('load', err, data);
});
} else {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping');
}
}
};
Persist.prototype._autoSave = function (obj, objType, name) {
var self = this;
if (typeof obj.save === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name);
}
obj.save(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic save failed:', err);
}
self.emit('save', err, data);
});
}
};
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); }
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) { callback(err, data, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
//self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) { callback(err, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
/**
* Gets the data that represents this collection for easy storage using
* a third-party method / plugin instead of using the standard persistent
* storage system.
* @param {Function} callback The method to call with the data response.
*/
Collection.prototype.saveCustom = function (callback) {
var self = this,
myData = {},
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.data = {
name: self._db._name + '-' + self._name,
store: data,
tableStats: tableStats
};
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.metaData = {
name: self._db._name + '-' + self._name + '-metaData',
store: data,
tableStats: tableStats
};
callback(false, myData);
} else {
callback(err);
}
});
} else {
callback(err);
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads custom data loaded by a third-party plugin into the collection.
* @param {Object} myData Data object previously saved by using saveCustom()
* @param {Function} callback A callback method to receive notification when
* data has loaded.
*/
Collection.prototype.loadCustom = function (myData, callback) {
var self = this;
if (self._name) {
if (self._db) {
if (myData.data && myData.data.store) {
if (myData.metaData && myData.metaData.store) {
self.decode(myData.data.store, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
self.decode(myData.metaData.store, function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
if (callback) { callback(err, tableStats, metaStats); }
}
} else {
callback(err);
}
});
}
} else {
callback(err);
}
});
} else {
callback('No "metaData" key found in passed object!');
}
} else {
callback('No "data" key found in passed object!');
}
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
Db.prototype.load = new Overload({
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (myData, callback) {
this.$main.call(this, myData, callback);
},
'$main': function (myData, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) {
callback(false);
}
}
} else {
if (callback) {
callback(err);
}
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
if (!myData) {
obj[index].load(loadCallback);
} else {
obj[index].loadCustom(myData, loadCallback);
}
}
}
}
});
Db.prototype.save = new Overload({
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (options, callback) {
this.$main.call(this, options, callback);
},
'$main': function (options, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
if (!options.custom) {
obj[index].save(saveCallback);
} else {
obj[index].saveCustom(saveCallback);
}
}
}
}
});
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,"async":41,"localforage":77}],35:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":39,"pako":78}],36:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":39,"crypto-js":50}],37:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":39}],38:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Handler for Date() objects
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
// Handler for RegExp() objects
this.registerEncoder('$regexp', function (data) {
if (data instanceof RegExp) {
return {
source: data.source,
params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '')
};
}
});
this.registerDecoder('$regexp', function (data) {
var type = typeof data;
if (type === 'object') {
return new RegExp(data.source, data.params);
} else if (type === 'string') {
return new RegExp(data);
}
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],39:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.591',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload');
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this.publicData().findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
// Check if we have an existing reactor io
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
var coll = this.publicData();
return coll.distinct.apply(coll, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this.publicData().primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._publicData && this._publicData !== this._privateData) {
this._publicData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
}
});
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
//pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var self = this;
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
if (this._transformEnabled) {
// Check for / create the public data collection
if (!this._publicData) {
// Create the public data collection
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
// Create a chain reaction IO node to keep the private and
// public data collections in sync
this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) {
var data = chainPacket.data;
switch (chainPacket.type) {
case 'primaryKey':
self._publicData.primaryKey(data);
this.chainSend('primaryKey', data);
break;
case 'setData':
self._publicData.setData(data);
this.chainSend('setData', data);
break;
case 'insert':
self._publicData.insert(data);
this.chainSend('insert', data);
break;
case 'update':
// Do the update
self._publicData.update(
data.query,
data.update,
data.options
);
this.chainSend('update', data);
break;
case 'remove':
self._publicData.remove(data.query, chainPacket.options);
this.chainSend('remove', data);
break;
default:
break;
}
});
}
// Set initial data and settings
this._publicData.primaryKey(this.privateData().primaryKey());
this._publicData.setData(this.privateData().find());
} else {
// Remove the public data collection
if (this._publicData) {
this._publicData.drop();
delete this._publicData;
if (this._transformIo) {
this._transformIo.drop();
delete this._transformIo;
}
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
var self = this;
// Handle being passed an instance
if (viewName instanceof View) {
return viewName;
}
if (this._view[viewName]) {
return this._view[viewName];
} else {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
self.emit('create', [self._view[viewName], 'view', viewName]);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (!callback) {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has inexistant dependency');
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback(null);
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
while(workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":76}],42:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 () {
// Shortcuts
var key = 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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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":44}],44:[function(_dereq_,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) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
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
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('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;
}));
},{}],45:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":44}],46:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":44}],47:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./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":44,"./hmac":49,"./sha1":68}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":43,"./core":44}],49:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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":44}],50:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":44}],52:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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":44}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
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);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":43,"./core":44}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby [email protected]
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":43,"./core":44}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":43,"./core":44}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":43,"./core":44}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":43,"./core":44}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
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;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":43,"./core":44}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
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;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":43,"./core":44}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":43,"./core":44}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":43,"./core":44}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":43,"./core":44}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./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 SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
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.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @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 HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @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.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(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 _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_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];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_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] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 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 < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
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 f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* 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.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* 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.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":44}],68:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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":44}],69:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], 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_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* 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.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* 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.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":44,"./sha256":70}],70:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_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];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// 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;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 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.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* 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.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":44}],71:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-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_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].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.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* 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.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":44,"./x64-core":75}],72:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* 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.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* 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.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 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 + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* 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.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* 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.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":44,"./x64-core":75}],74:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":44}],76:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],77:[function(_dereq_,module,exports){
(function (process,global){
/*!
localForage -- Offline Storage, Improved
Version 1.3.0
https://mozilla.github.io/localForage
(c) 2013-2015 Mozilla, Apache License 2.0
*/
(function() {
var define, requireModule, _dereq_, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = _dereq_ = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
define("promise/all",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
var isFunction = __dependency1__.isFunction;
/**
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The return promise
is fulfilled with an array that gives all the values in the order they were
passed in the `promises` array argument.
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.resolve(2);
var promise3 = RSVP.resolve(3);
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.reject(new Error("2"));
var promise3 = RSVP.reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@for RSVP
@param {Array} promises
@param {String} label
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
*/
function all(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return new Promise(function(resolve, reject) {
var results = [], remaining = promises.length,
promise;
if (remaining === 0) {
resolve([]);
}
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function resolveAll(index, value) {
results[index] = value;
if (--remaining === 0) {
resolve(results);
}
}
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && isFunction(promise.then)) {
promise.then(resolver(i), reject);
} else {
resolveAll(i, promise);
}
}
});
}
__exports__.all = all;
});
define("promise/asap",
["exports"],
function(__exports__) {
"use strict";
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
// node
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useSetTimeout() {
return function() {
local.setTimeout(flush, 1);
};
}
var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0], arg = tuple[1];
callback(arg);
}
queue = [];
}
var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
}
function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
// If length is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush();
}
}
__exports__.asap = asap;
});
define("promise/config",
["exports"],
function(__exports__) {
"use strict";
var config = {
instrument: false
};
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
__exports__.config = config;
__exports__.configure = configure;
});
define("promise/polyfill",
["./promise","./utils","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/*global self*/
var RSVPPromise = __dependency1__.Promise;
var isFunction = __dependency2__.isFunction;
function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = RSVPPromise;
}
}
__exports__.polyfill = polyfill;
});
define("promise/promise",
["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) {
"use strict";
var config = __dependency1__.config;
var configure = __dependency1__.configure;
var objectOrFunction = __dependency2__.objectOrFunction;
var isFunction = __dependency2__.isFunction;
var now = __dependency2__.now;
var all = __dependency3__.all;
var race = __dependency4__.race;
var staticResolve = __dependency5__.resolve;
var staticReject = __dependency6__.reject;
var asap = __dependency7__.asap;
var counter = 0;
config.async = asap; // default async is asap;
function Promise(resolver) {
if (!isFunction(resolver)) {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
if (!(this instanceof Promise)) {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
this._subscribers = [];
invokeResolver(resolver, this);
}
function invokeResolver(resolver, promise) {
function resolvePromise(value) {
resolve(promise, value);
}
function rejectPromise(reason) {
reject(promise, reason);
}
try {
resolver(resolvePromise, rejectPromise);
} catch(e) {
rejectPromise(e);
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
try {
value = callback(detail);
succeeded = true;
} catch(e) {
failed = true;
error = e;
}
} else {
value = detail;
succeeded = true;
}
if (handleThenable(promise, value)) {
return;
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
resolve(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
var PENDING = void 0;
var SEALED = 0;
var FULFILLED = 1;
var REJECTED = 2;
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
}
function publish(promise, settled) {
var child, callback, subscribers = promise._subscribers, detail = promise._detail;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
invokeCallback(settled, child, callback, detail);
}
promise._subscribers = null;
}
Promise.prototype = {
constructor: Promise,
_state: undefined,
_detail: undefined,
_subscribers: undefined,
then: function(onFulfillment, onRejection) {
var promise = this;
var thenPromise = new this.constructor(function() {});
if (this._state) {
var callbacks = arguments;
config.async(function invokePromiseCallback() {
invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
});
} else {
subscribe(this, thenPromise, onFulfillment, onRejection);
}
return thenPromise;
},
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
Promise.all = all;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject;
function handleThenable(promise, value) {
var then = null,
resolved;
try {
if (promise === value) {
throw new TypeError("A promises callback cannot return that same promise.");
}
if (objectOrFunction(value)) {
then = value.then;
if (isFunction(then)) {
then.call(value, function(val) {
if (resolved) { return true; }
resolved = true;
if (value !== val) {
resolve(promise, val);
} else {
fulfill(promise, val);
}
}, function(val) {
if (resolved) { return true; }
resolved = true;
reject(promise, val);
});
return true;
}
}
} catch (error) {
if (resolved) { return true; }
reject(promise, error);
return true;
}
return false;
}
function resolve(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (!handleThenable(promise, value)) {
fulfill(promise, value);
}
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = value;
config.async(publishFulfillment, promise);
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = reason;
config.async(publishRejection, promise);
}
function publishFulfillment(promise) {
publish(promise, promise._state = FULFILLED);
}
function publishRejection(promise) {
publish(promise, promise._state = REJECTED);
}
__exports__.Promise = Promise;
});
define("promise/race",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
/**
`RSVP.race` allows you to watch a series of promises and act as soon as the
first promise given to the `promises` argument fulfills or rejects.
Example:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 2");
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// result === "promise 2" because it was resolved before promise1
// was resolved.
});
```
`RSVP.race` is deterministic in that only the state of the first completed
promise matters. For example, even if other promises given to the `promises`
array argument are resolved, but the first completed promise has become
rejected before the other promises became fulfilled, the returned promise
will become rejected:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error("promise 2"));
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// Code here never runs because there are rejected promises!
}, function(reason){
// reason.message === "promise2" because promise 2 became rejected before
// promise 1 became fulfilled
});
```
@method race
@for RSVP
@param {Array} promises array of promises to observe
@param {String} label optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise that becomes fulfilled with the value the first
completed promises is resolved with if the first completed promise was
fulfilled, or rejected with the reason that the first completed promise
was rejected with.
*/
function race(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve, reject) {
var results = [], promise;
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && typeof promise.then === 'function') {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
});
}
__exports__.race = race;
});
define("promise/reject",
["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.reject` returns a promise that will become rejected with the passed
`reason`. `RSVP.reject` is essentially shorthand for the following:
```javascript
var promise = new RSVP.Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
var promise = RSVP.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@for RSVP
@param {Any} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become rejected with the given
`reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Promise = this;
return new Promise(function (resolve, reject) {
reject(reason);
});
}
__exports__.reject = reject;
});
define("promise/resolve",
["exports"],
function(__exports__) {
"use strict";
function resolve(value) {
/*jshint validthis:true */
if (value && typeof value === 'object' && value.constructor === this) {
return value;
}
var Promise = this;
return new Promise(function(resolve) {
resolve(value);
});
}
__exports__.resolve = resolve;
});
define("promise/utils",
["exports"],
function(__exports__) {
"use strict";
function objectOrFunction(x) {
return isFunction(x) || (typeof x === "object" && x !== null);
}
function isFunction(x) {
return typeof x === "function";
}
function isArray(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
// Date.now is not available in browsers < IE9
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
var now = Date.now || function() { return new Date().getTime(); };
__exports__.objectOrFunction = objectOrFunction;
__exports__.isFunction = isFunction;
__exports__.isArray = isArray;
__exports__.now = now;
});
requireModule('promise/polyfill').polyfill();
}());(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["localforage"] = factory();
else
root["localforage"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
(function () {
'use strict';
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'];
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function (self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function () {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB && typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function () {
try {
return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem;
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var LocalForage = (function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
this.INDEXEDDB = DriverType.INDEXEDDB;
this.LOCALSTORAGE = DriverType.LOCALSTORAGE;
this.WEBSQL = DriverType.WEBSQL;
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver);
}
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof options === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
var namingError = new Error('Custom driver name already in use: ' + driverObject._driver);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function (supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
promise.then(callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var self = this;
var getDriverPromise = (function () {
if (isLibraryDriver(driverName)) {
switch (driverName) {
case self.INDEXEDDB:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(1));
});
case self.LOCALSTORAGE:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(2));
});
case self.WEBSQL:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(4));
});
}
} else if (CustomDrivers[driverName]) {
return Promise.resolve(CustomDrivers[driverName]);
}
return Promise.reject(new Error('Driver not found.'));
})();
getDriverPromise.then(callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
});
if (callback && typeof callback === 'function') {
serializerPromise.then(function (result) {
callback(result);
});
}
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
promise.then(callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
})['catch'](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () {
return Promise.resolve();
}) : Promise.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})['catch'](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
});
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
})();
var localForage = new LocalForage();
exports['default'] = localForage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 1 */
/***/ function(module, exports) {
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
var dbContexts;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({ status: xhr.status, response: xhr.response });
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function (resolve, reject) {
var blob = _createBlob([''], { type: 'image/png' });
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function () {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function (e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function (res) {
resolve(!!(res && res.type === 'image/png'));
}, function () {
resolve(false);
}).then(function () {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Initialize a singleton container for all running localForages.
if (!dbContexts) {
dbContexts = {};
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null
};
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(this);
// Create an array of readiness of the related localForages.
var readyPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== this) {
// Don't wait for itself...
readyPromises.push(forage.ready()['catch'](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise.all(readyPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k in forages) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise(function (resolve, reject) {
if (dbInfo.db) {
if (upgradeNeeded) {
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = indexedDB.open.apply(indexedDB, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function () {
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
};
});
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void 0) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function (blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function (value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = asyncStorage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
if (dbInfo.storeName !== self._defaultConfig.storeName) {
dbInfo.keyPrefix += dbInfo.storeName + '/';
}
self._dbInfo = dbInfo;
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = localStorageWrapper;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
(function () {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
exports['default'] = localforageSerializer;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function () {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
});
});
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = webSQLStorage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":76}],78:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],82:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":81}],83:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],84:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],85:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],86:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],88:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],89:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":81}],91:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],92:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":81}],93:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
|
views/main.js | jqk6/black-screen | import React from 'react';
import _ from 'lodash';
import Rx from 'rx';
import ApplicationView from './compiled/src/views/ApplicationView.js';
var keys = {
goUp: event => (event.ctrlKey && event.keyCode === 80) || event.keyCode === 38,
goDown: event => (event.ctrlKey && event.keyCode === 78) || event.keyCode === 40,
enter: event => event.keyCode === 13,
tab: event => event.keyCode === 9,
deleteWord: event => event.ctrlKey && event.keyCode === 87
};
function scrollToBottom() {
$('html body').animate({ scrollTop: $(document).height() }, 0);
}
function focusLastInput(event) {
if (_.contains(event.target.classList, 'prompt') || event.metaKey) {
return;
}
var originalEvent = event.originalEvent;
if (isMetaKey(originalEvent)) {
return;
}
var newEvent = new KeyboardEvent("keydown", _.pick(originalEvent, [
'altkey', 'bubbles', 'cancelBubble', 'cancelable', 'charCode',
'ctrlKey', 'keyIdentifier', 'metaKey', 'shiftKey'
]));
var target = _.last(document.getElementsByClassName('prompt'));
target.focus();
withCaret(target, () => target.innerText.length);
target.dispatchEvent(newEvent)
}
function setCaretPosition(node, position) {
var selection = window.getSelection();
var range = document.createRange();
if (node.childNodes.length) {
range.setStart(node.childNodes[0], position);
} else {
range.setStart(node, 0);
}
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
function withCaret(target, callback) {
var selection = window.getSelection();
var range = document.createRange();
var offset = callback(selection.baseOffset);
if (target.childNodes.length) {
range.setStart(target.childNodes[0], offset);
} else {
range.setStart(target, 0);
}
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
function isCommandKey(event) {
return _.contains([16, 17, 18], event.keyCode) || event.ctrlKey || event.altKey || event.metaKey;
}
function isMetaKey(event) {
return event.metaKey || _.some([event.key, event.keyIdentifier],
key => _.includes(['Shift', 'Alt', 'Ctrl'], key));
}
const isDefinedKey = _.memoize(event => _.some(_.values(keys), matcher => matcher(event)),
event => [event.ctrlKey, event.keyCode]);
function stopBubblingUp(event) {
event.stopPropagation();
event.preventDefault();
return event;
}
// TODO: Figure out how it works.
function createEventHandler() {
var subject = function() {
subject.onNext.apply(subject, arguments);
};
getEnumerablePropertyNames(Rx.Subject.prototype)
.forEach(function (property) {
subject[property] = Rx.Subject.prototype[property];
});
Rx.Subject.call(subject);
return subject;
}
function getEnumerablePropertyNames(target) {
var result = [];
for (var key in target) {
result.push(key);
}
return result;
}
$(document).ready(() => {
React.render(<ApplicationView/>, document.getElementById('black-board'));
// TODO: focus the last input of the active terminal.
$(document).keydown(event => focusLastInput(event));
});
|
files/rxjs/2.3.21/rx.lite.js | cedricbousmanne/jsdelivr | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise,
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var deprecate = Rx.helpers.deprecate = function (name, alternative) {
/*if (typeof console !== "undefined" && typeof console.warn === "function") {
console.warn(name + ' is deprecated, use ' + alternative + ' instead.', new Error('').stack);
}*/
}
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
// Fix for Tessel
if (!propertyIsEnumerable) {
propertyIsEnumerable = objectProto.propertyIsEnumerable = function (key) {
for (var k in this) { if (k === key) { return true; } }
return false;
};
}
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dueTime);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
var onGlobalPostMessage = function (event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
var notification = new Notification('E');
notification.exception = e;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError(err);
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError(err);
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe(observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var source = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return source.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
}, source);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._s.charAt(this._i++);
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._a[this._i++];
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
var list = Object(iterable), it = getIterable(list);
return new AnonymousObservable(function (observer) {
var i = 0;
return scheduler.scheduleRecursive(function (self) {
var next;
try {
next = it.next();
} catch (e) {
observer.onError(e);
return;
}
if (next.done) {
observer.onCompleted();
return;
}
var result = next.value;
if (mapFn && isFunction(mapFn)) {
try {
result = mapFn.call(thisArg, result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
deprecate('fromArray', 'from');
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
return observableOf(null, arguments);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
return observableOf(scheduler, slice.call(arguments, 1));
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/** @deprecated use return or just */
Observable.returnValue = function () {
deprecate('returnValue', 'return or just');
return observableReturn.apply(null, arguments);
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* @deprecated use #catch or #catchError instead.
*/
observableProto.catchException = function (handlerOrSecond) {
deprecate('catchException', 'catch or catchError');
return this.catchError(handlerOrSecond);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = function () {
return enumerableOf(argsOrArray(arguments, 0)).catchError();
};
/**
* @deprecated use #catch or #catchError instead.
*/
Observable.catchException = function () {
deprecate('catchException', 'catch or catchError');
return observableCatch.apply(null, arguments);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
return enumerableOf(argsOrArray(arguments, 0)).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = function () {
return this.merge(1);
};
/** @deprecated Use `concatAll` instead. */
observableProto.concatObservable = function () {
deprecate('concatObservable', 'concatAll');
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); }
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [];
function subscribe(xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
isPromise(xs) && (xs = observableFromPromise(xs));
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
isStopped && activeCount === 0 && observer.onCompleted();
}
}));
}
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
activeCount === 0 && observer.onCompleted();
}));
return group;
}, sources);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && observer.onCompleted();
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
group.length === 1 && observer.onCompleted();
}));
return group;
}, sources);
};
/**
* @deprecated use #mergeAll instead.
*/
observableProto.mergeObservable = function () {
deprecate('mergeObservable', 'mergeAll');
return this.mergeAll.apply(this, arguments);
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
observer.onError.bind(observer),
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
}, source);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, first);
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0), first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; }
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
return new AnonymousObservable(this.subscribe.bind(this), this);
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (e) {
observer.onError(e);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (e) {
observer.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (onError) {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
}
observer.onError(err);
}, function () {
if (onCompleted) {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
}
observer.onCompleted();
});
}, this);
};
/** @deprecated use #do or #tap instead. */
observableProto.doAction = function () {
deprecate('doAction', 'do or tap');
return this.tap.apply(this, arguments);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
!hasValue && hasSeed && observer.onNext(seed);
observer.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && observer.onNext(q.shift());
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableOf([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while (q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
}, source);
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var selectorFn = isFunction(selector) ? selector : function () { return selector; },
source = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return source.subscribe(function (value) {
var result;
try {
result = selectorFn.call(thisArg, value, count++, source);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} prop The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (prop) {
return this.map(function (x) { return x[prop]; });
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new Error(argumentOutOfRange); }
var source = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
running && observer.onNext(x);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new RangeError(argumentOutOfRange); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
observer.onNext(x);
remaining === 0 && observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return source.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (e) {
observer.onError(e);
return;
}
shouldRun && observer.onNext(value);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler() {
var results = arguments;
if (selector) {
try {
results = selector(results);
} catch (err) {
observer.onError(err);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
// Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs
// for proper loading order!
var marionette = !!root.Backbone && !!root.Backbone.Marionette;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
if (marionette) {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, subject.subscribe.bind(subject));
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var count = 0, d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count++);
self(d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
}, source);
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
* @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, this);
};
/**
* @deprecated use #debounce or #throttleWithTimeout instead.
*/
observableProto.throttle = function(dueTime, scheduler) {
deprecate('throttle', 'debounce or throttleWithTimeout');
return this.debounce(dueTime, scheduler);
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (observer) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
observer.onNext(x);
}
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer)
);
}, source);
};
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (observer) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
observer.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}
if (isDone && values[1]) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
observer.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer),
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(observer) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
observer.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
observer.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
(!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted();
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
(!this.enableQueue || this.queue.length === 0) && this.subject.onError(error);
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(value);
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
return this.queue.length !== 0 ?
{ numberOfItems: numberOfItems, returnValue: true } :
{ numberOfItems: numberOfItems, returnValue: false };
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
!noError && this.dispose();
}
};
AutoDetachObserverPrototype.error = function (err) {
try {
this.observer.onError(err);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.exception = error;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
|
FrontEnd/TodoList/__tests__/index.android.js | JamesLiAndroid/TodoList | import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
docs/src/pages/utils/popovers/MouseOverPopover.js | cherniavskii/material-ui | /* eslint-disable jsx-a11y/mouse-events-have-key-events */
import React from 'react';
import PropTypes from 'prop-types';
import Popover from 'material-ui/Popover';
import Typography from 'material-ui/Typography';
import { withStyles } from 'material-ui/styles';
import Grow from 'material-ui/transitions/Grow';
import Paper from 'material-ui/Paper';
import { Manager, Target, Popper } from 'react-popper';
const styles = theme => ({
paper: {
padding: theme.spacing.unit,
},
popover: {
pointerEvents: 'none',
},
popperClose: {
pointerEvents: 'none',
},
});
class MouseOverPopover extends React.Component {
state = {
anchorEl: null,
popperOpen: false,
};
handlePopoverOpen = event => {
this.setState({ anchorEl: event.target });
};
handlePopoverClose = () => {
this.setState({ anchorEl: null });
};
handlePopperOpen = () => {
this.setState({ popperOpen: true });
};
handlePopperClose = () => {
this.setState({ popperOpen: false });
};
render() {
const { classes } = this.props;
const { anchorEl, popperOpen } = this.state;
const open = !!anchorEl;
return (
<div className="wrapper">
<Typography onMouseOver={this.handlePopoverOpen} onMouseOut={this.handlePopoverClose}>
Hover with a Popover.
</Typography>
<Popover
className={classes.popover}
classes={{
paper: classes.paper,
}}
open={open}
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'left',
}}
onClose={this.handlePopoverClose}
disableRestoreFocus
>
<Typography>I use Popover.</Typography>
</Popover>
<Manager>
<Target>
<Typography
aria-describedby="react-popper-tooltip"
onMouseOver={this.handlePopperOpen}
onMouseOut={this.handlePopperClose}
>
Hover with react-popper.
</Typography>
</Target>
<Popper
placement="bottom-start"
eventsEnabled={popperOpen}
className={!popperOpen ? classes.popperClose : ''}
>
<Grow in={popperOpen} style={{ transformOrigin: '0 0 0' }}>
<Paper
id="react-popper-tooltip"
className={classes.paper}
role="tooltip"
aria-hidden={!popperOpen}
elevation={8}
>
<Typography>I use react-popper.</Typography>
</Paper>
</Grow>
</Popper>
</Manager>
</div>
);
}
}
MouseOverPopover.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(MouseOverPopover);
|
bug-ticket-editor0/index.js | espeakers/react-loose-forms.examples | var _ = require("lodash");
var dd = require("react-dd");
var React = require("react");
require("../bootstrap.min.css");
require("react-loose-forms.bootstrap3").install(require("react-loose-forms/InputTypes"));
var TicketForm = require("./TicketForm");
var App = dd.createClass({
getInitialState: function(){
return {
opened_ticket_id: null,
tickets: _.object(_.map([
{product: "Dehydrated Boulders", description: "When I opened your box, they fell into my glass of water... as a result I broke both my legs :(", date: "2015 Jul 27", level: "High"},
{product: "Jet-Propelled Unicycle", description: "The jet's were installed backwards!", date: "2015 Jul 28", level: "High"},
{product: "DIY Tornado Kit", description: "I planted 10 tornado seeds in my neighbors yard, but 3 of them attacked my house!", date: "2015 Jul 26", level: "Medium"},
{product: "Earthquake Pills", description: "I ate them, but it didn't do anything!?!?", date: "2015 Jul 25", level: "Low"},
{product: "Iron Carrot", description: "I chipped my tooth!", date: "2015 Jul 25", level: "Low"}
], function(t, i){
var t2 = _.assign({id: "111" + i}, t);
return [t2.id, t2];
}))
};
},
__saveTicket: function(data){
console.log(JSON.stringify(data, false, 2));
var opened_ticket_id = this.state.opened_ticket_id;
var opened_ticket = this.state.tickets[opened_ticket_id];
if(opened_ticket){
this.setState({tickets: _.assign(this.state.tickets, _.object([
[opened_ticket_id, _.assign(opened_ticket, data)]
]))});
}else{
var new_id = _.uniqueId("new");
this.setState({tickets: _.assign(this.state.tickets, _.object([
[new_id, _.assign(data, {id: new_id, date: "today"})]
]))});
}
},
__openTicketOnClick: function(id){
var self = this;
return function(e){
e.preventDefault();
self.setState({opened_ticket_id: id});
};
},
render: function(){
var tickets = this.state.tickets;
var opened_ticket_id = this.state.opened_ticket_id;
var opened_ticket = tickets[opened_ticket_id];
return dd.div({className: "container-fluid"},
dd.h1(null, "ACME Bug Tracker"),
dd.div({className: "row"},
dd.div({className: "col-sm-6"},
dd.table({className: "table"},
dd.thead(null,
dd.tr(null,
dd.th(null, "Date"),
dd.th(null, "Product"),
dd.th(null, "Description"),
dd.th(null, "Level")
)
),
dd.tbody(null,
_.map(tickets, function(ticket, id){
var is_open = opened_ticket && (opened_ticket.id === id);
return dd.tr({key: id, onClick: this.__openTicketOnClick(id), className: is_open ? "active" : null},
dd.td(null, dd[is_open ? "b" : "span"](null, ticket.date)),
dd.td(null, dd[is_open ? "b" : "span"](null, ticket.product)),
dd.td(null, dd[is_open ? "b" : "span"](null, ticket.description)),
dd.td(null, dd[is_open ? "b" : "span"](null, ticket.level))
);
}, this)
)
)
),
opened_ticket ? dd.div({className: "col-sm-6"},
dd.div({style: {width: 500}},
dd.div({className: "well"},
dd.h3({style: {marginTop: 0}},
"Ticket #" + opened_ticket.id,
dd.small({className: "pull-right"}, opened_ticket.date)
),
TicketForm({
onSubmit: this.__saveTicket,
ticket: opened_ticket
})
)
)
) : null
)
);
}
});
React.render(App(), document.body);
|
src/svg-icons/device/location-searching.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceLocationSearching = (props) => (
<SvgIcon {...props}>
<path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
</SvgIcon>
);
DeviceLocationSearching = pure(DeviceLocationSearching);
DeviceLocationSearching.displayName = 'DeviceLocationSearching';
DeviceLocationSearching.muiName = 'SvgIcon';
export default DeviceLocationSearching;
|
src/components/Scores/index.js | CodersInTheCommunity/curve-calculator | import React from 'react';
export default class Scores extends React.Component {
constructor(props) {
super(props);
}
handleClick(i, e) {
this.props.removeScore(i);
}
render() {
return(
<div className="scores">
{!this.props.scores.length ? null :
<i>(Click on a score to remove it)</i>
}
<ul>
{this.props.scores.map(function(score, i){
return(
<li key={i}>
<span
style={{cursor:'pointer'}}
onClick={this.handleClick.bind(this, i)}>
{score}
</span>
</li>
);
}.bind(this))}
</ul>
</div>
);
}
}
|
docs/src/app/components/pages/components/List/ExamplePhone.js | IsenrichO/mui-with-arrows | import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import CommunicationCall from 'material-ui/svg-icons/communication/call';
import CommunicationChatBubble from 'material-ui/svg-icons/communication/chat-bubble';
import {indigo500} from 'material-ui/styles/colors';
import CommunicationEmail from 'material-ui/svg-icons/communication/email';
const ListExamplePhone = () => (
<MobileTearSheet>
<List>
<ListItem
leftIcon={<CommunicationCall color={indigo500} />}
rightIcon={<CommunicationChatBubble />}
primaryText="(650) 555 - 1234"
secondaryText="Mobile"
/>
<ListItem
insetChildren={true}
rightIcon={<CommunicationChatBubble />}
primaryText="(323) 555 - 6789"
secondaryText="Work"
/>
</List>
<Divider inset={true} />
<List>
<ListItem
leftIcon={<CommunicationEmail color={indigo500} />}
primaryText="[email protected]"
secondaryText="Personal"
/>
<ListItem
insetChildren={true}
primaryText="[email protected]"
secondaryText="Work"
/>
</List>
</MobileTearSheet>
);
export default ListExamplePhone;
|
src/index.js | devgeeks/react-animated-views | import React from 'react';
import { popFade, none, slideLeft, slideUp } from './animations';
function getInnerDisplayName(InnerPage) {
return InnerPage.displayName || InnerPage.name || 'Component';
}
export default function (InnerPage) {
return React.createClass({
displayName: `ReactAnimatedView(${getInnerDisplayName(InnerPage)})`,
propTypes: {
direction: React.PropTypes.string,
location: React.PropTypes.object,
},
contextTypes: {
router: React.PropTypes.object.isRequired,
},
getInitialState() {
const { direction } = this.props;
return {
action: direction || 'pop',
};
},
componentWillMount() {
const { location: { query: { animation } } } = this.props;
this.setAnimationFunction(animation);
},
setAction(action) {
this.setState({
action,
});
},
setAnimationFunction(animation) {
switch (animation) {
case 'slideLeft':
this.animationFunction = slideLeft;
break;
case 'popFade':
this.animationFunction = popFade;
break;
case 'slideUp':
this.animationFunction = slideUp;
break;
case 'none':
default:
this.animationFunction = none;
break;
}
},
animationFunction: popFade,
push(url, animation) {
const { router } = this.context;
// replace current route with current route and current animation
// this means coming back will show the correct animation
router.replace({
pathname: this.props.location.pathname,
query: { ...{ animation } },
});
this.setAnimationFunction(animation);
this.setAction('push');
router.push({
pathname: url,
query: { animation },
});
},
pop(animation) {
const { router } = this.context;
animation && this.setAnimationFunction(animation);
this.setAction('pop');
router.goBack();
},
componentWillLeave(done) {
const { action } = this.state;
this.animationFunction(this, {
action,
direction: 'out',
}, done);
},
componentDidLeave() {
// reset to default
this.setState({
action: 'pop',
});
},
componentWillEnter(done) {
const { action } = this.state;
this.animationFunction(this, {
action,
direction: 'in',
}, done);
},
componentDidEnter() {
// reset to default
this.setState({
action: 'pop',
});
},
render() {
return (
<InnerPage
{ ...this.state }
{ ...this.props }
setAction={ this.setAction }
push={ this.push }
pop={ this.pop }
/>
);
},
});
}
|
src/App.js | linxlad/tracksy-client | import React from 'react';
import { browserHistory, Router } from 'react-router';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
class App extends React.Component {
static propTypes = {
store: PropTypes.object.isRequired,
routes: PropTypes.object.isRequired
}
shouldComponentUpdate() {
return false;
}
render() {
return (
<Provider store={this.props.store}>
<div style={{ height: '100%' }}>
<Router history={browserHistory} children={this.props.routes} />
</div>
</Provider>
);
}
}
export default App;
|
app/src/Frontend/modules/weui/pages/toast/index.js | ptphp/ptphp | /**
* Created by jf on 15/12/10.
*/
"use strict";
import React from 'react';
import {Button, Toast} from '../../../../index';
import Page from '../../component/page';
export default class ToastDemo extends React.Component {
state = {
showToast: false,
showLoading: false,
toastTimer: null,
loadingTimer: null
};
componentWillUnmount() {
this.state.toastTimer && clearTimeout(this.state.toastTimer);
this.state.loadingTimer && clearTimeout(this.state.loadingTimer);
}
render() {
return (
<Page className="toast" title="Toast" spacing>
<Button onClick={this.showToast.bind(this)}>Toast</Button>
<Button onClick={this.showLoading.bind(this)}>Loading</Button>
<Toast show={this.state.showToast}>完成</Toast>
<Toast icon="loading" show={this.state.showLoading}>正在加载中...</Toast>
</Page>
);
}
showToast() {
this.setState({showToast: true});
this.state.toastTimer = setTimeout(()=> {
this.setState({showToast: false});
}, 2000);
}
showLoading() {
this.setState({showLoading: true});
this.state.loadingTimer = setTimeout(()=> {
this.setState({showLoading: false});
}, 2000);
}
}; |
packages/wix-style-react/src/Input/Ticker/Ticker.spec.js | wix/wix-style-react | import React from 'react';
import { createUniDriverFactory } from 'wix-ui-test-utils/uni-driver-factory';
import { tickerPrivateDriverFactory } from './Ticker.private.uni.driver';
import Ticker from './Ticker';
import Input from '../Input';
describe('<Ticker/>', () => {
const createDriver = createUniDriverFactory(tickerPrivateDriverFactory);
const getInputWithTicker = (ticker, props = {}) => {
return <Input suffix={ticker} {...props} />;
};
it('should create a ticker', async () => {
const driver = createDriver(getInputWithTicker(<Ticker />));
expect(await driver.exists()).toEqual(true);
});
it('should allow handling up action', async () => {
const onUp = jest.fn();
const driver = createDriver(getInputWithTicker(<Ticker onUp={onUp} />));
await driver.clickUp();
expect(onUp).toHaveBeenCalled();
});
it('should allow handling down action', async () => {
const onDown = jest.fn();
const driver = createDriver(getInputWithTicker(<Ticker onDown={onDown} />));
await driver.clickDown();
expect(onDown).toHaveBeenCalled();
});
it('should allow disabling up action', async () => {
const onUp = jest.fn();
const driver = createDriver(
getInputWithTicker(<Ticker onUp={onUp} upDisabled />),
);
expect(await driver.isUpDisabled()).toEqual(true);
await driver.clickUp();
expect(onUp).not.toHaveBeenCalled();
});
it('should allow disabling down action', async () => {
const onDown = jest.fn();
const driver = createDriver(
getInputWithTicker(<Ticker onDown={onDown} downDisabled />),
);
expect(await driver.isDownDisabled()).toEqual(true);
await driver.clickUp();
expect(onDown).not.toHaveBeenCalled();
});
it('should be disabled in case input is disabled', async () => {
const onDown = jest.fn();
const onUp = jest.fn();
const driver = createDriver(
getInputWithTicker(<Input.Ticker onDown={onDown} onUp={onUp} />, {
disabled: true,
}),
);
expect(await driver.isDownDisabled()).toEqual(true);
expect(await driver.isUpDisabled()).toEqual(true);
driver.clickUp();
driver.clickDown();
expect(onUp).not.toHaveBeenCalled();
expect(onDown).not.toHaveBeenCalled();
});
});
|
ajax/libs/yui/3.5.0/event-custom-base/event-custom-base-debug.js | Assalaam/cdnjs | YUI.add('event-custom-base', function(Y) {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
*/
Y.Env.evt = {
handles: {},
plugins: {}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* Allows for the insertion of methods that are executed before or after
* a specified method
* @class Do
* @static
*/
var DO_BEFORE = 0,
DO_AFTER = 1,
DO = {
/**
* Cache of objects touched by the utility
* @property objs
* @static
*/
objs: {},
/**
* <p>Execute the supplied method before the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>
* <dd>Replace the arguments that the original function will be
* called with.</dd>
* <dt></code>Y.Do.Prevent(message)</code></dt>
* <dd>Don't execute the wrapped function. Other before phase
* wrappers will be executed.</dd>
* </dl>
*
* @method before
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {string} handle for the subscription
* @static
*/
before: function(fn, obj, sFn, c) {
// Y.log('Do before: ' + sFn, 'info', 'event');
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_BEFORE, f, obj, sFn);
},
/**
* <p>Execute the supplied method after the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt>
* <dd>Return <code>returnValue</code> instead of the wrapped
* method's original return value. This can be further altered by
* other after phase wrappers.</dd>
* </dl>
*
* <p>The static properties <code>Y.Do.originalRetVal</code> and
* <code>Y.Do.currentRetVal</code> will be populated for reference.</p>
*
* @method after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return {string} handle for the subscription
* @static
*/
after: function(fn, obj, sFn, c) {
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_AFTER, f, obj, sFn);
},
/**
* Execute the supplied method before or after the specified function.
* Used by <code>before</code> and <code>after</code>.
*
* @method _inject
* @param when {string} before or after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @return {string} handle for the subscription
* @private
* @static
*/
_inject: function(when, fn, obj, sFn) {
// object id
var id = Y.stamp(obj), o, sid;
if (! this.objs[id]) {
// create a map entry for the obj if it doesn't exist
this.objs[id] = {};
}
o = this.objs[id];
if (! o[sFn]) {
// create a map entry for the method if it doesn't exist
o[sFn] = new Y.Do.Method(obj, sFn);
// re-route the method to our wrapper
obj[sFn] =
function() {
return o[sFn].exec.apply(o[sFn], arguments);
};
}
// subscriber id
sid = id + Y.stamp(fn) + sFn;
// register the callback
o[sFn].register(sid, fn, when);
return new Y.EventHandle(o[sFn], sid);
},
/**
* Detach a before or after subscription.
*
* @method detach
* @param handle {string} the subscription handle
* @static
*/
detach: function(handle) {
if (handle.detach) {
handle.detach();
}
},
_unload: function(e, me) {
}
};
Y.Do = DO;
//////////////////////////////////////////////////////////////////////////
/**
* Contains the return value from the wrapped method, accessible
* by 'after' event listeners.
*
* @property originalRetVal
* @static
* @since 3.2.0
*/
/**
* Contains the current state of the return value, consumable by
* 'after' event listeners, and updated if an after subscriber
* changes the return value generated by the wrapped function.
*
* @property currentRetVal
* @static
* @since 3.2.0
*/
//////////////////////////////////////////////////////////////////////////
/**
* Wrapper for a displaced method with aop enabled
* @class Do.Method
* @constructor
* @param obj The object to operate on
* @param sFn The name of the method to displace
*/
DO.Method = function(obj, sFn) {
this.obj = obj;
this.methodName = sFn;
this.method = obj[sFn];
this.before = {};
this.after = {};
};
/**
* Register a aop subscriber
* @method register
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype.register = function (sid, fn, when) {
if (when) {
this.after[sid] = fn;
} else {
this.before[sid] = fn;
}
};
/**
* Unregister a aop subscriber
* @method delete
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype._delete = function (sid) {
// Y.log('Y.Do._delete: ' + sid, 'info', 'Event');
delete this.before[sid];
delete this.after[sid];
};
/**
* <p>Execute the wrapped method. All arguments are passed into the wrapping
* functions. If any of the before wrappers return an instance of
* <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped
* function nor any after phase subscribers will be executed.</p>
*
* <p>The return value will be the return value of the wrapped function or one
* provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or
* <code>Y.Do.AlterReturn</code>.
*
* @method exec
* @param arg* {any} Arguments are passed to the wrapping and wrapped functions
* @return {any} Return value of wrapped function unless overwritten (see above)
*/
DO.Method.prototype.exec = function () {
var args = Y.Array(arguments, 0, true),
i, ret, newRet,
bf = this.before,
af = this.after,
prevented = false;
// execute before
for (i in bf) {
if (bf.hasOwnProperty(i)) {
ret = bf[i].apply(this.obj, args);
if (ret) {
switch (ret.constructor) {
case DO.Halt:
return ret.retVal;
case DO.AlterArgs:
args = ret.newArgs;
break;
case DO.Prevent:
prevented = true;
break;
default:
}
}
}
}
// execute method
if (!prevented) {
ret = this.method.apply(this.obj, args);
}
DO.originalRetVal = ret;
DO.currentRetVal = ret;
// execute after methods.
for (i in af) {
if (af.hasOwnProperty(i)) {
newRet = af[i].apply(this.obj, args);
// Stop processing if a Halt object is returned
if (newRet && newRet.constructor == DO.Halt) {
return newRet.retVal;
// Check for a new return value
} else if (newRet && newRet.constructor == DO.AlterReturn) {
ret = newRet.newRetVal;
// Update the static retval state
DO.currentRetVal = ret;
}
}
}
return ret;
};
//////////////////////////////////////////////////////////////////////////
/**
* Return an AlterArgs object when you want to change the arguments that
* were passed into the function. Useful for Do.before subscribers. An
* example would be a service that scrubs out illegal characters prior to
* executing the core business logic.
* @class Do.AlterArgs
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newArgs {Array} Call parameters to be used for the original method
* instead of the arguments originally passed in.
*/
DO.AlterArgs = function(msg, newArgs) {
this.msg = msg;
this.newArgs = newArgs;
};
/**
* Return an AlterReturn object when you want to change the result returned
* from the core method to the caller. Useful for Do.after subscribers.
* @class Do.AlterReturn
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newRetVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.AlterReturn = function(msg, newRetVal) {
this.msg = msg;
this.newRetVal = newRetVal;
};
/**
* Return a Halt object when you want to terminate the execution
* of all subsequent subscribers as well as the wrapped method
* if it has not exectued yet. Useful for Do.before subscribers.
* @class Do.Halt
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.Halt = function(msg, retVal) {
this.msg = msg;
this.retVal = retVal;
};
/**
* Return a Prevent object when you want to prevent the wrapped function
* from executing, but want the remaining listeners to execute. Useful
* for Do.before subscribers.
* @class Do.Prevent
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
*/
DO.Prevent = function(msg) {
this.msg = msg;
};
/**
* Return an Error object when you want to terminate the execution
* of all subsequent method calls.
* @class Do.Error
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
* @deprecated use Y.Do.Halt or Y.Do.Prevent
*/
DO.Error = DO.Halt;
//////////////////////////////////////////////////////////////////////////
// Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do);
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
// var onsubscribeType = "_event:onsub",
var AFTER = 'after',
CONFIGS = [
'broadcast',
'monitored',
'bubbles',
'context',
'contextFn',
'currentTarget',
'defaultFn',
'defaultTargetOnly',
'details',
'emitFacade',
'fireOnce',
'async',
'host',
'preventable',
'preventedFn',
'queuable',
'silent',
'stoppedFn',
'target',
'type'
],
YUI3_SIGNATURE = 9,
YUI_LOG = 'yui:log';
/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String} type The type of event, which is passed to the callback
* when the event fires.
* @param {object} o configuration object.
* @class CustomEvent
* @constructor
*/
Y.CustomEvent = function(type, o) {
// if (arguments.length > 2) {
// this.log('CustomEvent context and silent are now in the config', 'warn', 'Event');
// }
o = o || {};
this.id = Y.stamp(this);
/**
* The type of event, returned to subscribers when the event fires
* @property type
* @type string
*/
this.type = type;
/**
* The context the the event will fire from by default. Defaults to the YUI
* instance.
* @property context
* @type object
*/
this.context = Y;
/**
* Monitor when an event is attached or detached.
*
* @property monitored
* @type boolean
*/
// this.monitored = false;
this.logSystem = (type == YUI_LOG);
/**
* If 0, this event does not broadcast. If 1, the YUI instance is notified
* every time this event fires. If 2, the YUI instance and the YUI global
* (if event is enabled on the global) are notified every time this event
* fires.
* @property broadcast
* @type int
*/
// this.broadcast = 0;
/**
* By default all custom events are logged in the debug build, set silent
* to true to disable debug outpu for this event.
* @property silent
* @type boolean
*/
this.silent = this.logSystem;
/**
* Specifies whether this event should be queued when the host is actively
* processing an event. This will effect exectution order of the callbacks
* for the various events.
* @property queuable
* @type boolean
* @default false
*/
// this.queuable = false;
/**
* The subscribers to this event
* @property subscribers
* @type Subscriber {}
*/
this.subscribers = {};
/**
* 'After' subscribers
* @property afters
* @type Subscriber {}
*/
this.afters = {};
/**
* This event has fired if true
*
* @property fired
* @type boolean
* @default false;
*/
// this.fired = false;
/**
* An array containing the arguments the custom event
* was last fired with.
* @property firedWith
* @type Array
*/
// this.firedWith;
/**
* This event should only fire one time if true, and if
* it has fired, any new subscribers should be notified
* immediately.
*
* @property fireOnce
* @type boolean
* @default false;
*/
// this.fireOnce = false;
/**
* fireOnce listeners will fire syncronously unless async
* is set to true
* @property async
* @type boolean
* @default false
*/
//this.async = false;
/**
* Flag for stopPropagation that is modified during fire()
* 1 means to stop propagation to bubble targets. 2 means
* to also stop additional subscribers on this target.
* @property stopped
* @type int
*/
// this.stopped = 0;
/**
* Flag for preventDefault that is modified during fire().
* if it is not 0, the default behavior for this event
* @property prevented
* @type int
*/
// this.prevented = 0;
/**
* Specifies the host for this custom event. This is used
* to enable event bubbling
* @property host
* @type EventTarget
*/
// this.host = null;
/**
* The default function to execute after event listeners
* have fire, but only if the default action was not
* prevented.
* @property defaultFn
* @type Function
*/
// this.defaultFn = null;
/**
* The function to execute if a subscriber calls
* stopPropagation or stopImmediatePropagation
* @property stoppedFn
* @type Function
*/
// this.stoppedFn = null;
/**
* The function to execute if a subscriber calls
* preventDefault
* @property preventedFn
* @type Function
*/
// this.preventedFn = null;
/**
* Specifies whether or not this event's default function
* can be cancelled by a subscriber by executing preventDefault()
* on the event facade
* @property preventable
* @type boolean
* @default true
*/
this.preventable = true;
/**
* Specifies whether or not a subscriber can stop the event propagation
* via stopPropagation(), stopImmediatePropagation(), or halt()
*
* Events can only bubble if emitFacade is true.
*
* @property bubbles
* @type boolean
* @default true
*/
this.bubbles = true;
/**
* Supports multiple options for listener signatures in order to
* port YUI 2 apps.
* @property signature
* @type int
* @default 9
*/
this.signature = YUI3_SIGNATURE;
this.subCount = 0;
this.afterCount = 0;
// this.hasSubscribers = false;
// this.hasAfters = false;
/**
* If set to true, the custom event will deliver an EventFacade object
* that is similar to a DOM event object.
* @property emitFacade
* @type boolean
* @default false
*/
// this.emitFacade = false;
this.applyConfig(o, true);
// this.log("Creating " + this.type);
};
Y.CustomEvent.prototype = {
constructor: Y.CustomEvent,
/**
* Returns the number of subscribers for this event as the sum of the on()
* subscribers and after() subscribers.
*
* @method hasSubs
* @return Number
*/
hasSubs: function(when) {
var s = this.subCount, a = this.afterCount, sib = this.sibling;
if (sib) {
s += sib.subCount;
a += sib.afterCount;
}
if (when) {
return (when == 'after') ? a : s;
}
return (s + a);
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('detach', 'attach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
this.monitored = true;
var type = this.id + '|' + this.type + '_' + what,
args = Y.Array(arguments, 0, true);
args[0] = type;
return this.host.on.apply(this.host, args);
},
/**
* Get all of the subscribers to this event and any sibling event
* @method getSubs
* @return {Array} first item is the on subscribers, second the after.
*/
getSubs: function() {
var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling;
if (sib) {
Y.mix(s, sib.subscribers);
Y.mix(a, sib.afters);
}
return [s, a];
},
/**
* Apply configuration properties. Only applies the CONFIG whitelist
* @method applyConfig
* @param o hash of properties to apply.
* @param force {boolean} if true, properties that exist on the event
* will be overwritten.
*/
applyConfig: function(o, force) {
if (o) {
Y.mix(this, o, force, CONFIGS);
}
},
/**
* Create the Subscription for subscribing function, context, and bound
* arguments. If this is a fireOnce event, the subscriber is immediately
* notified.
*
* @method _on
* @param fn {Function} Subscription callback
* @param [context] {Object} Override `this` in the callback
* @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()
* @param [when] {String} "after" to slot into after subscribers
* @return {EventHandle}
* @protected
*/
_on: function(fn, context, args, when) {
if (!fn) {
this.log('Invalid callback for CE: ' + this.type);
}
var s = new Y.Subscriber(fn, context, args, when);
if (this.fireOnce && this.fired) {
if (this.async) {
setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0);
} else {
this._notify(s, this.firedWith);
}
}
if (when == AFTER) {
this.afters[s.id] = s;
this.afterCount++;
} else {
this.subscribers[s.id] = s;
this.subCount++;
}
return new Y.EventHandle(this, s);
},
/**
* Listen for this event
* @method subscribe
* @param {Function} fn The function to execute.
* @return {EventHandle} Unsubscribe handle.
* @deprecated use on.
*/
subscribe: function(fn, context) {
Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated');
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null;
return this._on(fn, context, a, true);
},
/**
* Listen for this event
* @method on
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} An object with a detach method to detch the handler(s).
*/
on: function(fn, context) {
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null;
if (this.host) {
this.host._monitor('attach', this.type, {
args: arguments
});
}
return this._on(fn, context, a, true);
},
/**
* Listen for this event after the normal subscribers have been notified and
* the default behavior has been applied. If a normal subscriber prevents the
* default behavior, it also prevents after listeners from firing.
* @method after
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} handle Unsubscribe handle.
*/
after: function(fn, context) {
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null;
return this._on(fn, context, a, AFTER);
},
/**
* Detach listeners.
* @method detach
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int} returns the number of subscribers unsubscribed.
*/
detach: function(fn, context) {
// unsubscribe handle
if (fn && fn.detach) {
return fn.detach();
}
var i, s,
found = 0,
subs = Y.merge(this.subscribers, this.afters);
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s);
found++;
}
}
}
return found;
},
/**
* Detach listeners.
* @method unsubscribe
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int|undefined} returns the number of subscribers unsubscribed.
* @deprecated use detach.
*/
unsubscribe: function() {
return this.detach.apply(this, arguments);
},
/**
* Notify a single subscriber
* @method _notify
* @param {Subscriber} s the subscriber.
* @param {Array} args the arguments array to apply to the listener.
* @protected
*/
_notify: function(s, args, ef) {
this.log(this.type + '->' + 'sub: ' + s.id);
var ret;
ret = s.notify(args, this);
if (false === ret || this.stopped > 1) {
this.log(this.type + ' cancelled by subscriber');
return false;
}
return true;
},
/**
* Logger abstraction to centralize the application of the silent flag
* @method log
* @param {string} msg message to log.
* @param {string} cat log category.
*/
log: function(msg, cat) {
if (!this.silent) {
Y.log(this.id + ': ' + msg, cat || 'info', 'event');
}
},
/**
* Notifies the subscribers. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters:
* <ul>
* <li>The type of event</li>
* <li>All of the arguments fire() was executed with as an array</li>
* <li>The custom object (if any) that was passed into the subscribe()
* method</li>
* </ul>
* @method fire
* @param {Object*} arguments an arbitrary set of parameters to pass to
* the handler.
* @return {boolean} false if one of the subscribers returned false,
* true otherwise.
*
*/
fire: function() {
if (this.fireOnce && this.fired) {
this.log('fireOnce event: ' + this.type + ' already fired');
return true;
} else {
var args = Y.Array(arguments, 0, true);
// this doesn't happen if the event isn't published
// this.host._monitor('fire', this.type, args);
this.fired = true;
this.firedWith = args;
if (this.emitFacade) {
return this.fireComplex(args);
} else {
return this.fireSimple(args);
}
}
},
/**
* Set up for notifying subscribers of non-emitFacade events.
*
* @method fireSimple
* @param args {Array} Arguments passed to fire()
* @return Boolean false if a subscriber returned false
* @protected
*/
fireSimple: function(args) {
this.stopped = 0;
this.prevented = 0;
if (this.hasSubs()) {
// this._procSubs(Y.merge(this.subscribers, this.afters), args);
var subs = this.getSubs();
this._procSubs(subs[0], args);
this._procSubs(subs[1], args);
}
this._broadcast(args);
return this.stopped ? false : true;
},
// Requires the event-custom-complex module for full funcitonality.
fireComplex: function(args) {
Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type);
args[0] = args[0] || {};
return this.fireSimple(args);
},
/**
* Notifies a list of subscribers.
*
* @method _procSubs
* @param subs {Array} List of subscribers
* @param args {Array} Arguments passed to fire()
* @param ef {}
* @return Boolean false if a subscriber returns false or stops the event
* propagation via e.stopPropagation(),
* e.stopImmediatePropagation(), or e.halt()
* @private
*/
_procSubs: function(subs, args, ef) {
var s, i;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
if (s && s.fn) {
if (false === this._notify(s, args, ef)) {
this.stopped = 2;
}
if (this.stopped == 2) {
return false;
}
}
}
}
return true;
},
/**
* Notifies the YUI instance if the event is configured with broadcast = 1,
* and both the YUI instance and Y.Global if configured with broadcast = 2.
*
* @method _broadcast
* @param args {Array} Arguments sent to fire()
* @private
*/
_broadcast: function(args) {
if (!this.stopped && this.broadcast) {
var a = Y.Array(args);
a.unshift(this.type);
if (this.host !== Y) {
Y.fire.apply(Y, a);
}
if (this.broadcast == 2) {
Y.Global.fire.apply(Y.Global, a);
}
}
},
/**
* Removes all listeners
* @method unsubscribeAll
* @return {int} The number of listeners unsubscribed.
* @deprecated use detachAll.
*/
unsubscribeAll: function() {
return this.detachAll.apply(this, arguments);
},
/**
* Removes all listeners
* @method detachAll
* @return {int} The number of listeners unsubscribed.
*/
detachAll: function() {
return this.detach();
},
/**
* Deletes the subscriber from the internal store of on() and after()
* subscribers.
*
* @method _delete
* @param subscriber object.
* @private
*/
_delete: function(s) {
if (s) {
if (this.subscribers[s.id]) {
delete this.subscribers[s.id];
this.subCount--;
}
if (this.afters[s.id]) {
delete this.afters[s.id];
this.afterCount--;
}
}
if (this.host) {
this.host._monitor('detach', this.type, {
ce: this,
sub: s
});
}
if (s) {
// delete s.fn;
// delete s.context;
s.deleted = true;
}
}
};
/**
* Stores the subscriber information to be used when the event fires.
* @param {Function} fn The wrapped function to execute.
* @param {Object} context The value of the keyword 'this' in the listener.
* @param {Array} args* 0..n additional arguments to supply the listener.
*
* @class Subscriber
* @constructor
*/
Y.Subscriber = function(fn, context, args) {
/**
* The callback that will be execute when the event fires
* This is wrapped by Y.rbind if obj was supplied.
* @property fn
* @type Function
*/
this.fn = fn;
/**
* Optional 'this' keyword for the listener
* @property context
* @type Object
*/
this.context = context;
/**
* Unique subscriber id
* @property id
* @type String
*/
this.id = Y.stamp(this);
/**
* Additional arguments to propagate to the subscriber
* @property args
* @type Array
*/
this.args = args;
/**
* Custom events for a given fire transaction.
* @property events
* @type {EventTarget}
*/
// this.events = null;
/**
* This listener only reacts to the event once
* @property once
*/
// this.once = false;
};
Y.Subscriber.prototype = {
constructor: Y.Subscriber,
_notify: function(c, args, ce) {
if (this.deleted && !this.postponed) {
if (this.postponed) {
delete this.fn;
delete this.context;
} else {
delete this.postponed;
return null;
}
}
var a = this.args, ret;
switch (ce.signature) {
case 0:
ret = this.fn.call(c, ce.type, args, c);
break;
case 1:
ret = this.fn.call(c, args[0] || null, c);
break;
default:
if (a || args) {
args = args || [];
a = (a) ? args.concat(a) : args;
ret = this.fn.apply(c, a);
} else {
ret = this.fn.call(c);
}
}
if (this.once) {
ce._delete(this);
}
return ret;
},
/**
* Executes the subscriber.
* @method notify
* @param args {Array} Arguments array for the subscriber.
* @param ce {CustomEvent} The custom event that sent the notification.
*/
notify: function(args, ce) {
var c = this.context,
ret = true;
if (!c) {
c = (ce.contextFn) ? ce.contextFn() : ce.context;
}
// only catch errors if we will not re-throw them.
if (Y.config.throwFail) {
ret = this._notify(c, args, ce);
} else {
try {
ret = this._notify(c, args, ce);
} catch (e) {
Y.error(this + ' failed: ' + e.message, e);
}
}
return ret;
},
/**
* Returns true if the fn and obj match this objects properties.
* Used by the unsubscribe method to match the right subscriber.
*
* @method contains
* @param {Function} fn the function to execute.
* @param {Object} context optional 'this' keyword for the listener.
* @return {boolean} true if the supplied arguments match this
* subscriber's signature.
*/
contains: function(fn, context) {
if (context) {
return ((this.fn == fn) && this.context == context);
} else {
return (this.fn == fn);
}
}
};
/**
* Return value from all subscribe operations
* @class EventHandle
* @constructor
* @param {CustomEvent} evt the custom event.
* @param {Subscriber} sub the subscriber.
*/
Y.EventHandle = function(evt, sub) {
/**
* The custom event
*
* @property evt
* @type CustomEvent
*/
this.evt = evt;
/**
* The subscriber object
*
* @property sub
* @type Subscriber
*/
this.sub = sub;
};
Y.EventHandle.prototype = {
batch: function(f, c) {
f.call(c || this, this);
if (Y.Lang.isArray(this.evt)) {
Y.Array.each(this.evt, function(h) {
h.batch.call(c || h, f);
});
}
},
/**
* Detaches this subscriber
* @method detach
* @return {int} the number of detached listeners
*/
detach: function() {
var evt = this.evt, detached = 0, i;
if (evt) {
// Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event');
if (Y.Lang.isArray(evt)) {
for (i = 0; i < evt.length; i++) {
detached += evt[i].detach();
}
} else {
evt._delete(this.sub);
detached = 1;
}
}
return detached;
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('attach', 'detach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
return this.evt.monitor.apply(this.evt, arguments);
}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* EventTarget provides the implementation for any object to
* publish, subscribe and fire to custom events, and also
* alows other EventTargets to target the object with events
* sourced from the other object.
* EventTarget is designed to be used with Y.augment to wrap
* EventCustom in an interface that allows events to be listened to
* and fired by name. This makes it possible for implementing code to
* subscribe to an event that either has not been created yet, or will
* not be created at all.
* @class EventTarget
* @param opts a configuration object
* @config emitFacade {boolean} if true, all events will emit event
* facade payloads by default (default false)
* @config prefix {String} the prefix to apply to non-prefixed event names
*/
var L = Y.Lang,
PREFIX_DELIMITER = ':',
CATEGORY_DELIMITER = '|',
AFTER_PREFIX = '~AFTER~',
YArray = Y.Array,
_wildType = Y.cached(function(type) {
return type.replace(/(.*)(:)(.*)/, "*$2$3");
}),
/**
* If the instance has a prefix attribute and the
* event type is not prefixed, the instance prefix is
* applied to the supplied type.
* @method _getType
* @private
*/
_getType = Y.cached(function(type, pre) {
if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) {
return type;
}
return pre + PREFIX_DELIMITER + type;
}),
/**
* Returns an array with the detach key (if provided),
* and the prefixed event name from _getType
* Y.on('detachcategory| menu:click', fn)
* @method _parseType
* @private
*/
_parseType = Y.cached(function(type, pre) {
var t = type, detachcategory, after, i;
if (!L.isString(t)) {
return t;
}
i = t.indexOf(AFTER_PREFIX);
if (i > -1) {
after = true;
t = t.substr(AFTER_PREFIX.length);
// Y.log(t);
}
i = t.indexOf(CATEGORY_DELIMITER);
if (i > -1) {
detachcategory = t.substr(0, (i));
t = t.substr(i+1);
if (t == '*') {
t = null;
}
}
// detach category, full type with instance prefix, is this an after listener, short type
return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];
}),
ET = function(opts) {
// Y.log('EventTarget constructor executed: ' + this._yuid);
var o = (L.isObject(opts)) ? opts : {};
this._yuievt = this._yuievt || {
id: Y.guid(),
events: {},
targets: {},
config: o,
chain: ('chain' in o) ? o.chain : Y.config.chain,
bubbling: false,
defaults: {
context: o.context || this,
host: this,
emitFacade: o.emitFacade,
fireOnce: o.fireOnce,
queuable: o.queuable,
monitored: o.monitored,
broadcast: o.broadcast,
defaultTargetOnly: o.defaultTargetOnly,
bubbles: ('bubbles' in o) ? o.bubbles : true
}
};
};
ET.prototype = {
constructor: ET,
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>on</code> except the
* listener is immediatelly detached when it is executed.
* @method once
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
once: function() {
var handle = this.on.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>after</code> except the
* listener is immediatelly detached when it is executed.
* @method onceAfter
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
onceAfter: function() {
var handle = this.after.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Takes the type parameter passed to 'on' and parses out the
* various pieces that could be included in the type. If the
* event type is passed without a prefix, it will be expanded
* to include the prefix one is supplied or the event target
* is configured with a default prefix.
* @method parseType
* @param {String} type the type
* @param {String} [pre=this._yuievt.config.prefix] the prefix
* @since 3.3.0
* @return {Array} an array containing:
* * the detach category, if supplied,
* * the prefixed event type,
* * whether or not this is an after listener,
* * the supplied event type
*/
parseType: function(type, pre) {
return _parseType(type, pre || this._yuievt.config.prefix);
},
/**
* Subscribe a callback function to a custom event fired by this object or
* from an object that bubbles its events to this object.
*
* Callback functions for events published with `emitFacade = true` will
* receive an `EventFacade` as the first argument (typically named "e").
* These callbacks can then call `e.preventDefault()` to disable the
* behavior published to that event's `defaultFn`. See the `EventFacade`
* API for all available properties and methods. Subscribers to
* non-`emitFacade` events will receive the arguments passed to `fire()`
* after the event name.
*
* To subscribe to multiple events at once, pass an object as the first
* argument, where the key:value pairs correspond to the eventName:callback,
* or pass an array of event names as the first argument to subscribe to
* all listed events with the same callback.
*
* Returning `false` from a callback is supported as an alternative to
* calling `e.preventDefault(); e.stopPropagation();`. However, it is
* recommended to use the event methods whenever possible.
*
* @method on
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
on: function(type, fn, context) {
var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce,
detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,
Node = Y.Node, n, domevent, isArr;
// full name, args, detachcategory, after
this._monitor('attach', parts[1], {
args: arguments,
category: parts[0],
after: parts[2]
});
if (L.isObject(type)) {
if (L.isFunction(type)) {
return Y.Do.before.apply(Y.Do, arguments);
}
f = fn;
c = context;
args = YArray(arguments, 0, true);
ret = [];
if (L.isArray(type)) {
isArr = true;
}
after = type._after;
delete type._after;
Y.each(type, function(v, k) {
if (L.isObject(v)) {
f = v.fn || ((L.isFunction(v)) ? v : f);
c = v.context || c;
}
var nv = (after) ? AFTER_PREFIX : '';
args[0] = nv + ((isArr) ? v : k);
args[1] = f;
args[2] = c;
ret.push(this.on.apply(this, args));
}, this);
return (this._yuievt.chain) ? this : new Y.EventHandle(ret);
}
detachcategory = parts[0];
after = parts[2];
shorttype = parts[3];
// extra redirection so we catch adaptor events too. take a look at this.
if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {
args = YArray(arguments, 0, true);
args.splice(2, 0, Node.getDOMNode(this));
// Y.log("Node detected, redirecting with these args: " + args);
return Y.on.apply(Y, args);
}
type = parts[1];
if (Y.instanceOf(this, YUI)) {
adapt = Y.Env.evt.plugins[type];
args = YArray(arguments, 0, true);
args[0] = shorttype;
if (Node) {
n = args[2];
if (Y.instanceOf(n, Y.NodeList)) {
n = Y.NodeList.getDOMNodes(n);
} else if (Y.instanceOf(n, Node)) {
n = Node.getDOMNode(n);
}
domevent = (shorttype in Node.DOM_EVENTS);
// Captures both DOM events and event plugins.
if (domevent) {
args[2] = n;
}
}
// check for the existance of an event adaptor
if (adapt) {
Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event');
handle = adapt.on.apply(Y, args);
} else if ((!type) || domevent) {
handle = Y.Event._attach(args);
}
}
if (!handle) {
ce = this._yuievt.events[type] || this.publish(type);
handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true);
}
if (detachcategory) {
store[detachcategory] = store[detachcategory] || {};
store[detachcategory][type] = store[detachcategory][type] || [];
store[detachcategory][type].push(handle);
}
return (this._yuievt.chain) ? this : handle;
},
/**
* subscribe to an event
* @method subscribe
* @deprecated use on
*/
subscribe: function() {
Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated');
return this.on.apply(this, arguments);
},
/**
* Detach one or more listeners the from the specified event
* @method detach
* @param type {string|Object} Either the handle to the subscriber or the
* type of event. If the type
* is not specified, it will attempt to remove
* the listener from all hosted events.
* @param fn {Function} The subscribed function to unsubscribe, if not
* supplied, all subscribers will be removed.
* @param context {Object} The custom object passed to subscribe. This is
* optional, but if supplied will be used to
* disambiguate multiple listeners that are the same
* (e.g., you subscribe many object using a function
* that lives on the prototype)
* @return {EventTarget} the host
*/
detach: function(type, fn, context) {
var evts = this._yuievt.events, i,
Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node));
// detachAll disabled on the Y instance.
if (!type && (this !== Y)) {
for (i in evts) {
if (evts.hasOwnProperty(i)) {
evts[i].detach(fn, context);
}
}
if (isNode) {
Y.Event.purgeElement(Node.getDOMNode(this));
}
return this;
}
var parts = _parseType(type, this._yuievt.config.prefix),
detachcategory = L.isArray(parts) ? parts[0] : null,
shorttype = (parts) ? parts[3] : null,
adapt, store = Y.Env.evt.handles, detachhost, cat, args,
ce,
keyDetacher = function(lcat, ltype, host) {
var handles = lcat[ltype], ce, i;
if (handles) {
for (i = handles.length - 1; i >= 0; --i) {
ce = handles[i].evt;
if (ce.host === host || ce.el === host) {
handles[i].detach();
}
}
}
};
if (detachcategory) {
cat = store[detachcategory];
type = parts[1];
detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;
if (cat) {
if (type) {
keyDetacher(cat, type, detachhost);
} else {
for (i in cat) {
if (cat.hasOwnProperty(i)) {
keyDetacher(cat, i, detachhost);
}
}
}
return this;
}
// If this is an event handle, use it to detach
} else if (L.isObject(type) && type.detach) {
type.detach();
return this;
// extra redirection so we catch adaptor events too. take a look at this.
} else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {
args = YArray(arguments, 0, true);
args[2] = Node.getDOMNode(this);
Y.detach.apply(Y, args);
return this;
}
adapt = Y.Env.evt.plugins[shorttype];
// The YUI instance handles DOM events and adaptors
if (Y.instanceOf(this, YUI)) {
args = YArray(arguments, 0, true);
// use the adaptor specific detach code if
if (adapt && adapt.detach) {
adapt.detach.apply(Y, args);
return this;
// DOM event fork
} else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {
args[0] = type;
Y.Event.detach.apply(Y.Event, args);
return this;
}
}
// ce = evts[type];
ce = evts[parts[1]];
if (ce) {
ce.detach(fn, context);
}
return this;
},
/**
* detach a listener
* @method unsubscribe
* @deprecated use detach
*/
unsubscribe: function() {
Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated');
return this.detach.apply(this, arguments);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method detachAll
* @param type {String} The type, or name of the event
*/
detachAll: function(type) {
return this.detach(type);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method unsubscribeAll
* @param type {String} The type, or name of the event
* @deprecated use detachAll
*/
unsubscribeAll: function() {
Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated');
return this.detachAll.apply(this, arguments);
},
/**
* Creates a new custom event of the specified type. If a custom event
* by that name already exists, it will not be re-created. In either
* case the custom event is returned.
*
* @method publish
*
* @param type {String} the type, or name of the event
* @param opts {object} optional config params. Valid properties are:
*
* <ul>
* <li>
* 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)
* </li>
* <li>
* 'bubbles': whether or not this event bubbles (true)
* Events can only bubble if emitFacade is true.
* </li>
* <li>
* 'context': the default execution context for the listeners (this)
* </li>
* <li>
* 'defaultFn': the default function to execute when this event fires if preventDefault was not called
* </li>
* <li>
* 'emitFacade': whether or not this event emits a facade (false)
* </li>
* <li>
* 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'
* </li>
* <li>
* 'fireOnce': if an event is configured to fire once, new subscribers after
* the fire will be notified immediately.
* </li>
* <li>
* 'async': fireOnce event listeners will fire synchronously if the event has already
* fired unless async is true.
* </li>
* <li>
* 'preventable': whether or not preventDefault() has an effect (true)
* </li>
* <li>
* 'preventedFn': a function that is executed when preventDefault is called
* </li>
* <li>
* 'queuable': whether or not this event can be queued during bubbling (false)
* </li>
* <li>
* 'silent': if silent is true, debug messages are not provided for this event.
* </li>
* <li>
* 'stoppedFn': a function that is executed when stopPropagation is called
* </li>
*
* <li>
* 'monitored': specifies whether or not this event should send notifications about
* when the event has been attached, detached, or published.
* </li>
* <li>
* 'type': the event type (valid option if not provided as the first parameter to publish)
* </li>
* </ul>
*
* @return {CustomEvent} the custom event
*
*/
publish: function(type, opts) {
var events, ce, ret, defaults,
edata = this._yuievt,
pre = edata.config.prefix;
if (L.isObject(type)) {
ret = {};
Y.each(type, function(v, k) {
ret[k] = this.publish(k, v || opts);
}, this);
return ret;
}
type = (pre) ? _getType(type, pre) : type;
this._monitor('publish', type, {
args: arguments
});
events = edata.events;
ce = events[type];
if (ce) {
// ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event');
if (opts) {
ce.applyConfig(opts, true);
}
} else {
defaults = edata.defaults;
// apply defaults
ce = new Y.CustomEvent(type,
(opts) ? Y.merge(defaults, opts) : defaults);
events[type] = ce;
}
// make sure we turn the broadcast flag off if this
// event was published as a result of bubbling
// if (opts instanceof Y.CustomEvent) {
// events[type].broadcast = false;
// }
return events[type];
},
/**
* This is the entry point for the event monitoring system.
* You can monitor 'attach', 'detach', 'fire', and 'publish'.
* When configured, these events generate an event. click ->
* click_attach, click_detach, click_publish -- these can
* be subscribed to like other events to monitor the event
* system. Inividual published events can have monitoring
* turned on or off (publish can't be turned off before it
* it published) by setting the events 'monitor' config.
*
* @method _monitor
* @param what {String} 'attach', 'detach', 'fire', or 'publish'
* @param type {String} Name of the event being monitored
* @param o {Object} Information about the event interaction, such as
* fire() args, subscription category, publish config
* @private
*/
_monitor: function(what, type, o) {
var monitorevt, ce = this.getEvent(type);
if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
monitorevt = type + '_' + what;
// Y.log('monitoring: ' + monitorevt);
o.monitored = what;
this.fire.call(this, monitorevt, o);
}
},
/**
* Fire a custom event by name. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters.
*
* If the custom event object hasn't been created, then the event hasn't
* been published and it has no subscribers. For performance sake, we
* immediate exit in this case. This means the event won't bubble, so
* if the intention is that a bubble target be notified, the event must
* be published on this object first.
*
* The first argument is the event type, and any additional arguments are
* passed to the listeners as parameters. If the first of these is an
* object literal, and the event is configured to emit an event facade,
* that object is mixed into the event facade and the facade is provided
* in place of the original object.
*
* @method fire
* @param type {String|Object} The type of the event, or an object that contains
* a 'type' property.
* @param arguments {Object*} an arbitrary set of parameters to pass to
* the handler. If the first of these is an object literal and the event is
* configured to emit an event facade, the event facade will replace that
* parameter after the properties the object literal contains are copied to
* the event facade.
* @return {EventTarget} the event host
*
*/
fire: function(type) {
var typeIncluded = L.isString(type),
t = (typeIncluded) ? type : (type && type.type),
ce, ret, pre = this._yuievt.config.prefix, ce2,
args = (typeIncluded) ? YArray(arguments, 1, true) : arguments;
t = (pre) ? _getType(t, pre) : t;
this._monitor('fire', t, {
args: args
});
ce = this.getEvent(t, true);
ce2 = this.getSibling(t, ce);
if (ce2 && !ce) {
ce = this.publish(t);
}
// this event has not been published or subscribed to
if (!ce) {
if (this._yuievt.hasTargets) {
return this.bubble({ type: t }, args, this);
}
// otherwise there is nothing to be done
ret = true;
} else {
ce.sibling = ce2;
ret = ce.fire.apply(ce, args);
}
return (this._yuievt.chain) ? this : ret;
},
getSibling: function(type, ce) {
var ce2;
// delegate to *:type events if there are subscribers
if (type.indexOf(PREFIX_DELIMITER) > -1) {
type = _wildType(type);
// console.log(type);
ce2 = this.getEvent(type, true);
if (ce2) {
// console.log("GOT ONE: " + type);
ce2.applyConfig(ce);
ce2.bubbles = false;
ce2.broadcast = 0;
// ret = ce2.fire.apply(ce2, a);
}
}
return ce2;
},
/**
* Returns the custom event of the provided type has been created, a
* falsy value otherwise
* @method getEvent
* @param type {String} the type, or name of the event
* @param prefixed {String} if true, the type is prefixed already
* @return {CustomEvent} the custom event or null
*/
getEvent: function(type, prefixed) {
var pre, e;
if (!prefixed) {
pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
}
e = this._yuievt.events;
return e[type] || null;
},
/**
* Subscribe to a custom event hosted by this object. The
* supplied callback will execute after any listeners add
* via the subscribe method, and after the default function,
* if configured for the event, has executed.
*
* @method after
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
after: function(type, fn) {
var a = YArray(arguments, 0, true);
switch (L.type(type)) {
case 'function':
return Y.Do.after.apply(Y.Do, arguments);
case 'array':
// YArray.each(a[0], function(v) {
// v = AFTER_PREFIX + v;
// });
// break;
case 'object':
a[0]._after = true;
break;
default:
a[0] = AFTER_PREFIX + type;
}
return this.on.apply(this, a);
},
/**
* Executes the callback before a DOM event, custom event
* or method. If the first argument is a function, it
* is assumed the target is a method. For DOM and custom
* events, this is an alias for Y.on.
*
* For DOM and custom events:
* type, callback, context, 0-n arguments
*
* For methods:
* callback, object (method host), methodName, context, 0-n arguments
*
* @method before
* @return detach handle
*/
before: function() {
return this.on.apply(this, arguments);
}
};
Y.EventTarget = ET;
// make Y an event target
Y.mix(Y, ET.prototype);
ET.call(Y, { bubbles: false });
YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();
/**
* Hosts YUI page level events. This is where events bubble to
* when the broadcast config is set to 2. This property is
* only available if the custom event module is loaded.
* @property Global
* @type EventTarget
* @for YUI
*/
Y.Global = YUI.Env.globalEvents;
// @TODO implement a global namespace function on Y.Global?
/**
`Y.on()` can do many things:
<ul>
<li>Subscribe to custom events `publish`ed and `fire`d from Y</li>
<li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and
`fire`d from any object in the YUI instance sandbox</li>
<li>Subscribe to DOM events</li>
<li>Subscribe to the execution of a method on any object, effectively
treating that method as an event</li>
</ul>
For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument.
Y.on('io:complete', function () {
Y.MyApp.updateStatus('Transaction complete');
});
To subscribe to DOM events, pass the name of a DOM event as the first argument
and a CSS selector string as the third argument after the callback function.
Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,
array, or simply omitted (the default is the `window` object).
Y.on('click', function (e) {
e.preventDefault();
// proceed with ajax form submission
var url = this.get('action');
...
}, '#my-form');
The `this` object in DOM event callbacks will be the `Node` targeted by the CSS
selector or other identifier.
`on()` subscribers for DOM events or custom events `publish`ed with a
`defaultFn` can prevent the default behavior with `e.preventDefault()` from the
event object passed as the first parameter to the subscription callback.
To subscribe to the execution of an object method, pass arguments corresponding to the call signature for
<a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>.
NOTE: The formal parameter list below is for events, not for function
injection. See `Y.Do.before` for that signature.
@method on
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@see Do.before
@for YUI
**/
/**
Listen for an event one time. Equivalent to `on()`, except that
the listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see on
@method once
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Listen for an event one time. Equivalent to `once()`, except, like `after()`,
the subscription callback executes after all `on()` subscribers and the event's
`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase
subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`
subscribers will execute.
The listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see once
@method onceAfter
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Like `on()`, this method creates a subscription to a custom event or to the
execution of a method on an object.
For events, `after()` subscribers are executed after the event's
`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
NOTE: The subscription signature shown is for events, not for function
injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a>
for that signature.
@see on
@see Do.after
@method after
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [args*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
}, '@VERSION@' ,{requires:['oop']});
|
app/javascript/mastodon/features/ui/components/confirmation_modal.js | MastodonCloud/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, FormattedMessage } from 'react-intl';
import Button from '../../../components/button';
@injectIntl
export default class ConfirmationModal extends React.PureComponent {
static propTypes = {
message: PropTypes.node.isRequired,
confirm: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
componentDidMount() {
this.button.focus();
}
handleClick = () => {
this.props.onClose();
this.props.onConfirm();
}
handleCancel = () => {
this.props.onClose();
}
setRef = (c) => {
this.button = c;
}
render () {
const { message, confirm } = this.props;
return (
<div className='modal-root__modal confirmation-modal'>
<div className='confirmation-modal__container'>
{message}
</div>
<div className='confirmation-modal__action-bar'>
<Button onClick={this.handleCancel} className='confirmation-modal__cancel-button'>
<FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' />
</Button>
<Button text={confirm} onClick={this.handleClick} ref={this.setRef} />
</div>
</div>
);
}
}
|
ajax/libs/yasqe/2.3.7/yasqe.bundled.min.js | maruilian11/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASQE=e()}}(function(){var e;return function t(e,i,r){function n(s,a){if(!i[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=i[s]={exports:{}};e[s][0].call(p.exports,function(t){var i=e[s][1][t];return n(i?i:t)},p,p.exports,t,e,i,r)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e,t){t.exports=e("./main.js")},{"./main.js":30}],2:[function(e){"use strict";var t=e("jquery");t.deparam=function(e,i){var r={},n={"true":!0,"false":!1,"null":null};t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=r,p=0,c=l.split("]["),d=c.length-1;if(/\[/.test(c[0])&&/\]$/.test(c[d])){c[d]=c[d].replace(/\]$/,"");c=c.shift().split("[").concat(c);d=c.length-1}else d=0;if(2===a.length){s=decodeURIComponent(a[1]);i&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==n[s]?n[s]:s);if(d)for(;d>=p;p++){l=""===c[p]?u.length:c[p];u=u[l]=d>p?u[l]||(c[p+1]&&isNaN(c[p+1])?{}:[]):s}else t.isArray(r[l])?r[l].push(s):r[l]=void 0!==r[l]?[r[l],s]:s}else l&&(r[l]=i?void 0:"")});return r}},{jquery:15}],3:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("codemirror")):"function"==typeof e&&e.amd?e(["codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,i="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",n=r+"|_",o="("+n+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+n+"|[0-9])("+n+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,p="("+r+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",f="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",h="("+d+"|"+f+")";if("sparql11"==u){e="("+n+"|:|[0-9]|"+h+")(("+o+"|\\.|:|"+h+")*("+o+"|:|"+h+"))?";t="_:("+n+"|[0-9])(("+o+"|\\.)*"+o+")?"}else{e="("+n+"|[0-9])((("+o+")|\\.)*("+o+"))?";t="_:"+e}var E="("+p+")?:",m=E+e,g="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",N="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",T="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",L="\\+"+x,I="\\+"+N,y="\\+"+T,A="-"+x,S="-"+N,C="-"+T,R="\\\\[tbnrf\\\\\"']",b=c+"{4}",O="(\\\\u"+b+"|\\\\U00(10|0"+c+")"+b+")",P="'(([^\\x27\\x5C\\x0A\\x0D])|"+R+"|"+O+")*'",D='"(([^\\x22\\x5C\\x0A\\x0D])|'+R+"|"+O+')*"',w="'''(('|'')?([^'\\\\]|"+R+"|"+O+"))*'''",_='"""(("|"")?([^"\\\\]|'+R+"|"+O+'))*"""',M="[\\x20\\x09\\x0D\\x0A]",k="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",G="("+M+"|("+k+"))*",B="\\("+G+"\\)",U="\\["+G+"\\]",V={terminal:[{name:"WS",regex:new RegExp("^"+M+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+k),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+i),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+g),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+T),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+N),style:"number"},{name:"INTEGER",regex:new RegExp("^"+x),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+y),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+L),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+A),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+w),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+_),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+P),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+D),style:"string"},{name:"NIL",regex:new RegExp("^"+B),style:"punc"},{name:"ANON",regex:new RegExp("^"+U),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+E),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return V}function i(e){var t=[],i=o[e];if(void 0!=i)for(var r in i)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,i=0;i<f.length;++i){t=e.match(f[i].regex,!0,!1);if(t)return{cat:f[i].name,style:f[i].style,text:t[0]}}t=e.match(s,!0,!1);if(t)return{cat:e.current().toUpperCase(),style:"keyword",text:t[0]};t=e.match(a,!0,!1);if(t)return{cat:e.current(),style:"punc",text:t[0]};t=e.match(/^.[A-Za-z0-9]*/,!0,!1);return{cat:"<invalid_token>",style:"error",text:t[0]}}function n(){var i=e.column();t.errorStartPos=i;t.errorEndPos=i+c.text.length}function l(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e||"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e)&&(t.queryType=e)}function u(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=r();if("<invalid_token>"==c.cat){if(1==t.OK){t.OK=!1;n()}t.complete=!1;return c.style}if("WS"==c.cat||"COMMENT"==c.cat){t.possibleCurrent=t.possibleNext;return c.style}for(var d,h=!1,E=c.cat;t.stack.length>0&&E&&t.OK&&!h;){d=t.stack.pop();if(o[d]){var m=o[d][E];if(void 0!=m&&p(d)){for(var g=m.length-1;g>=0;--g)t.stack.push(m[g]);u(d)}else{t.OK=!1;t.complete=!1;n();t.stack.push(d)}}else if(d==E){h=!0;l(d);for(var v=!0,x=t.stack.length;x>0;--x){var N=o[t.stack[x-1]];N&&N.$||(v=!1)}t.complete=v;if(t.storeProperty&&"punc"!=E.cat){t.lastProperty=c.text;t.storeProperty=!1}}else{t.OK=!1;t.complete=!1;n()}}if(!h&&t.OK){t.OK=!1;t.complete=!1;n()}t.possibleCurrent=t.possibleNext;t.possibleNext=i(t.stack[t.stack.length-1]);return c.style}function n(t,i){var r=0,n=t.stack.length-1;if(/^[\}\]\)]/.test(i)){for(var o=i.substr(0,1);n>=0;--n)if(t.stack[n]==o){--n;break}}else{var s=h[t.stack[n]];if(s){r+=s;--n}}for(;n>=0;--n){var s=E[t.stack[n]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",p="sparql11",c=!0,d=t(),f=d.terminal,h={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},E={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1};
return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:i(p),possibleNext:i(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:n,electricChars:"}])"}});e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:14}],4:[function(e,t){var i=t.exports=function(){this.words=0;this.prefixes=0;this.children=[]};i.prototype={insert:function(e,t){if(0!=e.length){var r,n,o=this;void 0===t&&(t=0);if(t!==e.length){o.prefixes++;r=e[t];void 0===o.children[r]&&(o.children[r]=new i);n=o.children[r];n.insert(e,t+1)}else o.words++}},remove:function(e,t){if(0!=e.length){var i,r,n=this;void 0===t&&(t=0);if(void 0!==n)if(t!==e.length){n.prefixes--;i=e[t];r=n.children[i];r.remove(e,t+1)}else n.words--}},update:function(e,t){if(0!=e.length&&0!=t.length){this.remove(e);this.insert(t)}},countWord:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.words;i=e[t];r=n.children[i];void 0!==r&&(o=r.countWord(e,t+1));return o},countPrefix:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.prefixes;var i=e[t];r=n.children[i];void 0!==r&&(o=r.countPrefix(e,t+1));return o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,i,r=this,n=[];void 0===e&&(e="");if(void 0===r)return[];r.words>0&&n.push(e);for(t in r.children){i=r.children[t];n=n.concat(i.getAllWords(e+t))}return n},autoComplete:function(e,t){var i,r,n=this;if(0==e.length)return void 0===t?n.getAllWords(e):[];void 0===t&&(t=0);i=e[t];r=n.children[i];return void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],5:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e){var t=e.getWrapperElement();e.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:t.style.width,height:t.style.height};t.style.width="";t.style.height="auto";t.className+=" CodeMirror-fullscreen";document.documentElement.style.overflow="hidden";e.refresh()}function i(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var i=e.state.fullScreenRestore;t.style.width=i.width;t.style.height=i.height;window.scrollTo(i.scrollLeft,i.scrollTop);e.refresh()}e.defineOption("fullScreen",!1,function(r,n,o){o==e.Init&&(o=!1);!o!=!n&&(n?t(r):i(r))})})},{"../../lib/codemirror":14}],6:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){function t(e,t,r,n){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=i(e,s(t.line,l+(p>0?1:0)),p,c||null,n);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function i(e,t,i,r,n){for(var o=n&&n.maxScanLineLength||1e4,l=n&&n.maxScanLines||1e3,u=[],p=n&&n.bracketRegex?n.bracketRegex:/[(){}[\]]/,c=i>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=i){var f=e.getLine(d);if(f){var h=i>0?0:f.length-1,E=i>0?f.length:-1;if(!(f.length>o)){d==t.line&&(h=t.ch-(0>i?1:0));for(;h!=E;h+=i){var m=f.charAt(h);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var g=a[m];if(">"==g.charAt(1)==i>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}}return d-i==(i>0?e.lastLine():e.firstLine())?!1:null}function r(e,i,r){for(var n=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=n){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c}));p.to&&e.getLine(p.to.line).length<=n&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!i)return d;setTimeout(d,800)}}function n(e){e.operation(function(){if(l){l();l=null}l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,i,r){r&&r!=e.Init&&t.off("cursorActivity",n);if(i){t.state.matchBrackets="object"==typeof i?i:{};t.on("cursorActivity",n)}});e.defineExtension("matchBrackets",function(){r(this,!0)});e.defineExtension("findMatchingBracket",function(e,i,r){return t(this,e,i,r)});e.defineExtension("scanForBracket",function(e,t,r,n){return i(this,e,t,r,n)})})},{"../../lib/codemirror":14}],7:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.registerHelper("fold","brace",function(t,i){function r(r){for(var n=i.ch,l=0;;){var u=0>=n?-1:a.lastIndexOf(r,n-1);if(-1!=u){if(1==l&&u<i.ch)break;o=t.getTokenTypeAt(e.Pos(s,u+1));if(!/^(comment|string)/.test(o))return u+1;n=u-1}else{if(1==l)break;l=1;n=a.length}}}var n,o,s=i.line,a=t.getLine(s),l="{",u="}",n=r("{");if(null==n){l="[",u="]";n=r("[")}if(null!=n){var p,c,d=1,f=t.lastLine();e:for(var h=s;f>=h;++h)for(var E=t.getLine(h),m=h==s?n:0;;){var g=E.indexOf(l,m),v=E.indexOf(u,m);0>g&&(g=E.length);0>v&&(v=E.length);m=Math.min(g,v);if(m==E.length)break;if(t.getTokenTypeAt(e.Pos(h,m+1))==o)if(m==g)++d;else if(!--d){p=h;c=m;break e}++m}if(null!=p&&(s!=p||c!=n))return{from:e.Pos(s,n),to:e.Pos(p,c)}}});e.registerHelper("fold","import",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var n=i,o=Math.min(t.lastLine(),i+10);o>=n;++n){var s=t.getLine(n),a=s.indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(n,a)}}}var n,i=i.line,o=r(i);if(!o||r(i-1)||(n=r(i-2))&&n.end.line==i-1)return null;for(var s=o.end;;){var a=r(s.line+1);if(null==a)break;s=a.end}return{from:t.clipPos(e.Pos(i,o.startCh+1)),to:s}});e.registerHelper("fold","include",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var i=i.line,n=r(i);if(null==n||null!=r(i-1))return null;for(var o=i;;){var s=r(o+1);if(null==s)break;++o}return{from:e.Pos(i,n+1),to:t.clipPos(e.Pos(o))}})})},{"../../lib/codemirror":14}],8:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(t,n,o,s){function a(e){var i=l(t,n);if(!i||i.to.line-i.from.line<u)return null;for(var r=t.findMarksAt(i.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==s){if(!e)return null;i.cleared=!0;r[o].clear()}return i}if(o&&o.call){var l=o;o=null}else var l=r(t,o,"rangeFinder");"number"==typeof n&&(n=e.Pos(n,0));var u=r(t,o,"minFoldSize"),p=a(!0);if(r(t,o,"scanUp"))for(;!p&&n.line>t.firstLine();){n=e.Pos(n.line-1,0);p=a(!1)}if(p&&!p.cleared&&"unfold"!==s){var c=i(t,o);e.on(c,"mousedown",function(t){d.clear();e.e_preventDefault(t)});var d=t.markText(p.from,p.to,{replacedWith:c,clearOnEnter:!0,__isFold:!0});d.on("clear",function(i,r){e.signal(t,"unfold",t,i,r)});e.signal(t,"fold",t,p.from,p.to)}}function i(e,t){var i=r(e,t,"widget");if("string"==typeof i){var n=document.createTextNode(i);i=document.createElement("span");i.appendChild(n);i.className="CodeMirror-foldmarker"}return i}function r(e,t,i){if(t&&void 0!==t[i])return t[i];var r=e.options.foldOptions;return r&&void 0!==r[i]?r[i]:n[i]}e.newFoldFunction=function(e,i){return function(r,n){t(r,n,{rangeFinder:e,widget:i})}};e.defineExtension("foldCode",function(e,i,r){t(this,e,i,r)});e.defineExtension("isFolded",function(e){for(var t=this.findMarksAt(e),i=0;i<t.length;++i)if(t[i].__isFold)return!0});e.commands.toggleFold=function(e){e.foldCode(e.getCursor())};e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")};e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")};e.commands.foldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"fold")})};e.commands.unfoldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"unfold")})};e.registerHelper("fold","combine",function(){var e=Array.prototype.slice.call(arguments,0);return function(t,i){for(var r=0;r<e.length;++r){var n=e[r](t,i);if(n)return n}}});e.registerHelper("fold","auto",function(e,t){for(var i=e.getHelpers(t,"fold"),r=0;r<i.length;r++){var n=i[r](e,t);if(n)return n}});var n={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};e.defineOption("foldOptions",null);e.defineExtension("foldOption",function(e,t){return r(this,e,t)})})},{"../../lib/codemirror":14}],9:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror"),t("./foldcode")):"function"==typeof e&&e.amd?e(["../../lib/codemirror","./foldcode"],n):n(CodeMirror)})(function(e){"use strict";function t(e){this.options=e;this.from=this.to=0}function i(e){e===!0&&(e={});null==e.gutter&&(e.gutter="CodeMirror-foldgutter");null==e.indicatorOpen&&(e.indicatorOpen="CodeMirror-foldgutter-open");null==e.indicatorFolded&&(e.indicatorFolded="CodeMirror-foldgutter-folded");return e}function r(e,t){for(var i=e.findMarksAt(c(t)),r=0;r<i.length;++r)if(i[r].__isFold&&i[r].find().from.line==t)return!0}function n(e){if("string"==typeof e){var t=document.createElement("div");t.className=e+" CodeMirror-guttermarker-subtle";return t}return e.cloneNode(!0)}function o(e,t,i){var o=e.state.foldGutter.options,s=t,a=e.foldOption(o,"minFoldSize"),l=e.foldOption(o,"rangeFinder");e.eachLine(t,i,function(t){var i=null;if(r(e,s))i=n(o.indicatorFolded);else{var u=c(s,0),p=l&&l(e,u);p&&p.to.line-p.from.line>=a&&(i=n(o.indicatorOpen))}e.setGutterMarker(t,o.gutter,i);++s})}function s(e){var t=e.getViewport(),i=e.state.foldGutter;if(i){e.operation(function(){o(e,t.from,t.to)});i.from=t.from;i.to=t.to}}function a(e,t,i){var r=e.state.foldGutter.options;i==r.gutter&&e.foldCode(c(t,0),r.rangeFinder)}function l(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;t.from=t.to=0;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){s(e)},i.foldOnChangeTimeSpan||600)}function u(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){var i=e.getViewport();t.from==t.to||i.from-t.to>20||t.from-i.to>20?s(e):e.operation(function(){if(i.from<t.from){o(e,i.from,t.from);t.from=i.from}if(i.to>t.to){o(e,t.to,i.to);t.to=i.to}})},i.updateViewportTimeSpan||400)}function p(e,t){var i=e.state.foldGutter,r=t.line;r>=i.from&&r<i.to&&o(e,r,r+1)}e.defineOption("foldGutter",!1,function(r,n,o){if(o&&o!=e.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",a);r.off("change",l);r.off("viewportChange",u);r.off("fold",p);r.off("unfold",p);r.off("swapDoc",s)}if(n){r.state.foldGutter=new t(i(n));s(r);r.on("gutterClick",a);r.on("change",l);r.on("viewportChange",u);r.on("fold",p);r.on("unfold",p);r.on("swapDoc",s)}});var c=e.Pos})},{"../../lib/codemirror":14,"./foldcode":8}],10:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){return e.line-t.line||e.ch-t.ch}function i(e,t,i,r){this.line=t;this.ch=i;this.cm=e;this.text=e.getLine(t);this.min=r?r.from:e.firstLine();this.max=r?r.to-1:e.lastLine()}function r(e,t){var i=e.cm.getTokenTypeAt(d(e.line,t));return i&&/\btag\b/.test(i)}function n(e){if(!(e.line>=e.max)){e.ch=0;e.text=e.cm.getLine(++e.line);return!0}}function o(e){if(!(e.line<=e.min)){e.text=e.cm.getLine(--e.line);e.ch=e.text.length;return!0}}function s(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(n(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),o=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return o?"selfClose":"regular"}e.ch=t+1}}function a(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){E.lastIndex=t;e.ch=t;var i=E.exec(e.text);if(i&&i.index==t)return i}else e.ch=t}}function l(e){for(;;){E.lastIndex=e.ch;var t=E.exec(e.text);if(!t){if(n(e))continue;return}if(r(e,t.index+1)){e.ch=t.index+t[0].length;return t}e.ch=t.index+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),n=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return n?"selfClose":"regular"}e.ch=t}}function p(e,t){for(var i=[];;){var r,n=l(e),o=e.line,a=e.ch-(n?n[0].length:0);if(!n||!(r=s(e)))return;if("selfClose"!=r)if(n[1]){for(var u=i.length-1;u>=0;--u)if(i[u]==n[2]){i.length=u;break}if(0>u&&(!t||t==n[2]))return{tag:n[2],from:d(o,a),to:d(e.line,e.ch)}}else i.push(n[2])}}function c(e,t){for(var i=[];;){var r=u(e);if(!r)return;if("selfClose"!=r){var n=e.line,o=e.ch,s=a(e);if(!s)return;if(s[1])i.push(s[2]);else{for(var l=i.length-1;l>=0;--l)if(i[l]==s[2]){i.length=l;break}if(0>l&&(!t||t==s[2]))return{tag:s[2],from:d(e.line,e.ch),to:d(n,o)}}}else a(e)}}var d=e.Pos,f="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",h=f+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",E=new RegExp("<(/?)(["+f+"]["+h+"]*)","g");e.registerHelper("fold","xml",function(e,t){for(var r=new i(e,t.line,0);;){var n,o=l(r);if(!o||r.line!=t.line||!(n=s(r)))return;if(!o[1]&&"selfClose"!=n){var t=d(r.line,r.ch),a=p(r,o[2]);return a&&{from:t,to:a.from}}}});e.findMatchingTag=function(e,r,n){var o=new i(e,r.line,r.ch,n);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=s(o),u=l&&d(o.line,o.ch),f=l&&a(o);if(l&&f&&!(t(o,r)>0)){var h={from:d(o.line,o.ch),to:u,tag:f[2]};if("selfClose"==l)return{open:h,close:null,at:"open"};if(f[1])return{open:c(o,f[2]),close:h,at:"close"};o=new i(e,u.line,u.ch,n);return{open:h,close:p(o,f[2]),at:"open"}}}};e.findEnclosingTag=function(e,t,r){for(var n=new i(e,t.line,t.ch,r);;){var o=c(n);if(!o)break;var s=new i(e,t.line,t.ch,r),a=p(s,o.tag);if(a)return{open:o,close:a}}};e.scanForClosingTag=function(e,t,r,n){var o=new i(e,t.line,t.ch,n?{from:0,to:n}:null);return p(o,r)}})},{"../../lib/codemirror":14}],11:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){this.cm=e;this.options=this.buildOptions(t);this.widget=this.onClose=null}function i(e){return"string"==typeof e?e:e.text}function r(e,t){function i(e,i){var n;n="string"!=typeof i?function(e){return i(e,t)}:r.hasOwnProperty(i)?r[i]:i;o[e]=n}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},n=e.options.customKeys,o=n?{}:r;if(n)for(var s in n)n.hasOwnProperty(s)&&i(s,n[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&i(s,a[s]);return o}function n(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t;this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints";this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var f=p.appendChild(document.createElement("li")),h=c[d],E=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(E=h.className+" "+E);f.className=E;h.render?h.render(f,o,h):f.appendChild(document.createTextNode(h.displayText||i(h)));f.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),g=m.left,v=m.bottom,x=!0;p.style.left=g+"px";p.style.top=v+"px";var N=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),T=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var L=p.getBoundingClientRect(),I=L.bottom-T;if(I>0){var y=L.bottom-L.top,A=m.top-(m.bottom-L.top);if(A-y>0){p.style.top=(v=m.top-y)+"px";x=!1}else if(y>T){p.style.height=T-5+"px";p.style.top=(v=m.bottom-L.top)+"px";var S=u.getCursor();if(o.from.ch!=S.ch){m=u.cursorCoords(S);p.style.left=(g=m.left)+"px";L=p.getBoundingClientRect()}}}var C=L.right-N;if(C>0){if(L.right-L.left>N){p.style.width=N-5+"px";C-=L.right-L.left-N}p.style.left=(g=m.left-C)+"px"}u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o}));if(t.options.closeOnUnfocus){var R;u.on("blur",this.onBlur=function(){R=setTimeout(function(){t.close()},100)});u.on("focus",this.onFocus=function(){clearTimeout(R)})}var b=u.getScrollInfo();u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),i=u.getWrapperElement().getBoundingClientRect(),r=v+b.top-e.top,n=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);x||(n+=p.offsetHeight);if(n<=i.top||n>=i.bottom)return t.close();p.style.top=r+"px";p.style.left=g+b.left-e.left+"px"});e.on(p,"dblclick",function(e){var t=n(p,e.target||e.srcElement);if(t&&null!=t.hintId){l.changeActive(t.hintId);l.pick()}});e.on(p,"click",function(e){var i=n(p,e.target||e.srcElement);if(i&&null!=i.hintId){l.changeActive(i.hintId);t.options.completeOnSingleClick&&l.pick()}});e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)});e.signal(o,"select",c[0],p.firstChild);return!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,i){if(!t)return e.showHint(i);i&&i.async&&(t.async=!0);var r={hint:t};if(i)for(var n in i)r[n]=i[n];return e.showHint(r)};e.defineExtension("showHint",function(i){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,i),n=r.options.hint;if(n){e.signal(this,"startCompletion",this);if(!n.async)return r.showHints(n(this,r.options));n(this,function(e){r.showHints(e)},r.options);return void 0}}});t.prototype={close:function(){if(this.active()){this.cm.state.completionActive=null;this.widget&&this.widget.close();this.onClose&&this.onClose();e.signal(this.cm,"endCompletion",this.cm)}},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var n=t.list[r];n.hint?n.hint(this.cm,t,n):this.cm.replaceRange(i(n),n.from||t.from,n.to||t.to,"complete");e.signal(t,"pick",n);this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e);return void 0},showWidget:function(t){function i(){if(!l){l=!0;p.close();p.cm.off("cursorActivity",a);t&&e.signal(t,"close")}}function r(){if(!l){e.signal(t,"update");var i=p.options.hint;i.async?i(p.cm,n,p.options):n(i(p.cm,p.options))}}function n(e){t=e;if(!l){if(!t||!t.list.length)return i();p.widget&&p.widget.close();p.widget=new o(p,t)}}function s(){if(u){E(u);u=0}}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);if(e.line!=d.line||t.length-e.ch!=f-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1)))p.close();else{u=h(r);p.widget&&p.widget.close()}}this.widget=new o(this,t);e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),f=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},E=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a);this.onClose=i},buildOptions:function(e){var t=this.cm.options.hintOptions,i={};for(var r in l)i[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(i[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}};o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null;this.hints.parentNode.removeChild(this.hints);this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;if(this.completion.options.closeOnUnfocus){e.off("blur",this.onBlur);e.off("focus",this.onFocus)}e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,i){t>=this.data.list.length?t=i?this.data.list.length-1:0:0>t&&(t=i?0:this.data.list.length-1);if(this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,"");r=this.hints.childNodes[this.selectedHint=t];r.className+=" "+a;r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3);e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}};e.registerHelper("hint","auto",function(t,i){var r,n=t.getHelpers(t.getCursor(),"hint");if(n.length)for(var o=0;o<n.length;o++){var s=n[o](t,i);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,i)});e.registerHelper("hint","fromList",function(t,i){for(var r=t.getCursor(),n=t.getTokenAt(r),o=[],s=0;s<i.words.length;s++){var a=i.words[s];a.slice(0,n.string.length)==n.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,n.start),to:e.Pos(r.line,n.end)}:void 0});e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{"../../lib/codemirror":14}],12:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.runMode=function(t,i,r,n){var o=e.getMode(e.defaults,i),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=n&&n.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="";r=function(e,t){if("\n"!=e){for(var i="",r=0;;){var n=e.indexOf(" ",r);if(-1==n){i+=e.slice(r);p+=e.length-r;break}p+=n-r;i+=e.slice(r,n);var o=l-p%l;p+=o;for(var s=0;o>s;++s)i+=" ";r=n+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-");c.appendChild(document.createTextNode(i))}else u.appendChild(document.createTextNode(i))}else{u.appendChild(document.createTextNode(a?"\r":e));p=0}}}for(var c=e.splitLines(t),d=n&&n.state||e.startState(o),f=0,h=c.length;h>f;++f){f&&r("\n");var E=new e.StringStream(c[f]);!E.string&&o.blankLine&&o.blankLine(d);for(;!E.eol();){var m=o.token(E,d);r(E.current(),m,f,E.start,d);E.start=E.pos}}}})},{"../../lib/codemirror":14}],13:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t,n,o){this.atOccurrence=!1;this.doc=e;null==o&&"string"==typeof t&&(o=!1);n=n?e.clipPos(n):r(0,0);this.pos={from:n,to:n};if("string"!=typeof t){t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g"));this.matches=function(i,n){if(i){t.lastIndex=0;for(var o,s,a=e.getLine(n.line).slice(0,n.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;o=u;s=o.index;l=o.index+(o[0].length||1);if(l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(n.line).length&&p++)}else{t.lastIndex=n.ch;var a=e.getLine(n.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(n.line,s),to:r(n.line,s+p),match:o}:void 0}}else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(n,o){if(n){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1){p=i(l,u,p);return{from:r(o.line,p),to:r(o.line,p+s.length)}}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1){p=i(l,u,p)+o.ch;return{from:r(o.line,p),to:r(o.line,p+s.length)}}}}:function(){};else{var u=s.split("\n");this.matches=function(t,i){var n=l.length-1;if(t){if(i.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(i.line).slice(0,u[n].length))!=l[l.length-1])return;for(var o=r(i.line,u[n].length),s=i.line-1,p=n-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(i.line+(l.length-1)>e.lastLine())){var c=e.getLine(i.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var f=r(i.line,d),s=i.line+1,p=1;n>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,u[n].length))==l[n])return{from:f,to:r(s,u[n].length)}}}}}}}function i(e,t,i){if(e.length==t.length)return i;for(var r=Math.min(i,e.length);;){var n=e.slice(0,r).toLowerCase().length;if(i>n)++r;else{if(!(n>i))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);i.pos={from:t,to:t};i.atOccurrence=!1;return!1}for(var i=this,n=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,n)){this.atOccurrence=!0;return this.pos.match||!0}if(e){if(!n.line)return t(0);n=r(n.line-1,this.doc.getLine(n.line-1).length)}else{var o=this.doc.lineCount();if(n.line==o-1)return t(o);n=r(n.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var i=e.splitLines(t);this.doc.replaceRange(i,this.pos.from,this.pos.to);this.pos.to=r(this.pos.from.line+i.length-1,i[i.length-1].length+(1==i.length?this.pos.from.ch:0))}}};e.defineExtension("getSearchCursor",function(e,i,r){return new t(this.doc,e,i,r)});e.defineDocExtension("getSearchCursor",function(e,i,r){return new t(this,e,i,r)});e.defineExtension("selectMatches",function(t,i){for(var r,n=[],o=this.getSearchCursor(t,this.getCursor("from"),i);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)n.push({anchor:o.from(),head:o.to()});n.length&&this.setSelections(n,0)})})},{"../../lib/codemirror":14}],14:[function(t,i,r){(function(t){if("object"==typeof r&&"object"==typeof i)i.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}})(function(){"use strict";function e(i,r){if(!(this instanceof e))return new e(i,r);this.options=r=r?yo(r):{};yo(Us,r,!1);f(r);var n=r.value;"string"==typeof n&&(n=new ua(n,r.mode));this.doc=n;var o=this.display=new t(i,n);o.wrapper.CodeMirror=this;u(this);a(this);r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");r.autofocus&&!Es&&Oi(this);g(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new go,keySeq:null};ns&&11>os&&setTimeout(Ao(bi,this,!0),20);wi(this);Go();ni(this);this.curOp.forceUpdate=!0;Gn(this,n);r.autofocus&&!Es||wo()==o.input?setTimeout(Ao(rr,this),20):nr(this);for(var s in Vs)Vs.hasOwnProperty(s)&&Vs[s](this,r[s],Fs);L(this);for(var l=0;l<qs.length;++l)qs[l](this);si(this);ss&&r.lineWrapping&&"optimizelegibility"==getComputedStyle(o.lineDiv).textRendering&&(o.lineDiv.style.textRendering="auto")}function t(e,t){var i=this,r=i.input=bo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ss?r.style.width="1000px":r.setAttribute("wrap","off");hs&&(r.style.border="1px solid black");r.setAttribute("autocorrect","off");r.setAttribute("autocapitalize","off");r.setAttribute("spellcheck","false");i.inputDiv=bo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");i.scrollbarFiller=bo("div",null,"CodeMirror-scrollbar-filler");i.scrollbarFiller.setAttribute("not-content","true");i.gutterFiller=bo("div",null,"CodeMirror-gutter-filler");i.gutterFiller.setAttribute("not-content","true");i.lineDiv=bo("div",null,"CodeMirror-code");i.selectionDiv=bo("div",null,null,"position: relative; z-index: 1");i.cursorDiv=bo("div",null,"CodeMirror-cursors");i.measure=bo("div",null,"CodeMirror-measure");i.lineMeasure=bo("div",null,"CodeMirror-measure");i.lineSpace=bo("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none");i.mover=bo("div",[bo("div",[i.lineSpace],"CodeMirror-lines")],null,"position: relative");i.sizer=bo("div",[i.mover],"CodeMirror-sizer");i.sizerWidth=null;i.heightForcer=bo("div",null,null,"position: absolute; height: "+xa+"px; width: 1px;");i.gutters=bo("div",null,"CodeMirror-gutters");i.lineGutter=null;i.scroller=bo("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll");i.scroller.setAttribute("tabIndex","-1");i.wrapper=bo("div",[i.inputDiv,i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror");if(ns&&8>os){i.gutters.style.zIndex=-1;i.scroller.style.paddingRight=0}hs&&(r.style.width="0px");ss||(i.scroller.draggable=!0);if(cs){i.inputDiv.style.height="1px";i.inputDiv.style.position="absolute"}e&&(e.appendChild?e.appendChild(i.wrapper):e(i.wrapper));i.viewFrom=i.viewTo=t.first;i.reportedViewFrom=i.reportedViewTo=t.first;i.view=[];i.renderedView=null;i.externalMeasured=null;i.viewOffset=0;i.lastWrapHeight=i.lastWrapWidth=0;i.updateLineNumbers=null;i.nativeBarWidth=i.barHeight=i.barWidth=0;i.scrollbarsClipped=!1;i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null;i.prevInput="";i.alignWidgets=!1;i.pollingFast=!1;i.poll=new go;i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null;i.inaccurateSelection=!1;i.maxLine=null;i.maxLineLength=0;i.maxLineChanged=!1;i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null;i.shift=!1;i.selForContextMenu=null}function i(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption);r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null)});e.doc.frontier=e.doc.first;yt(e,100);e.state.modeGen++;e.curOp&&xi(e)}function n(e){if(e.options.lineWrapping){_a(e.display.wrapper,"CodeMirror-wrap");e.display.sizer.style.minWidth="";e.display.sizerWidth=null}else{wa(e.display.wrapper,"CodeMirror-wrap");d(e)}s(e);xi(e);qt(e);setTimeout(function(){v(e)},100)}function o(e){var t=ii(e.display),i=e.options.lineWrapping,r=i&&Math.max(5,e.display.scroller.clientWidth/ri(e.display)-3);return function(n){if(un(e.doc,n))return 0;var o=0;if(n.widgets)for(var s=0;s<n.widgets.length;s++)n.widgets[s].height&&(o+=n.widgets[s].height);return i?o+(Math.ceil(n.text.length/r)||1)*t:o+t}}function s(e){var t=e.doc,i=o(e);t.iter(function(e){var t=i(e);t!=e.height&&Fn(e,t)})}function a(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-");qt(e)}function l(e){u(e);xi(e);setTimeout(function(){T(e)
},20)}function u(e){var t=e.display.gutters,i=e.options.gutters;Oo(t);for(var r=0;r<i.length;++r){var n=i[r],o=t.appendChild(bo("div",null,"CodeMirror-gutter "+n));if("CodeMirror-linenumbers"==n){e.display.lineGutter=o;o.style.width=(e.display.lineNumWidth||1)+"px"}}t.style.display=r?"":"none";p(e)}function p(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function c(e){if(0==e.height)return 0;for(var t,i=e.text.length,r=e;t=tn(r);){var n=t.find(0,!0);r=n.from.line;i+=n.from.ch-n.to.ch}r=e;for(;t=rn(r);){var n=t.find(0,!0);i-=r.text.length-n.from.ch;r=n.to.line;i+=r.text.length-n.to.ch}return i}function d(e){var t=e.display,i=e.doc;t.maxLine=Bn(i,i.first);t.maxLineLength=c(t.maxLine);t.maxLineChanged=!0;i.iter(function(e){var i=c(e);if(i>t.maxLineLength){t.maxLineLength=i;t.maxLine=e}})}function f(e){var t=To(e.gutters,"CodeMirror-linenumbers");if(-1==t&&e.lineNumbers)e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]);else if(t>-1&&!e.lineNumbers){e.gutters=e.gutters.slice(0);e.gutters.splice(t,1)}}function h(e){var t=e.display,i=t.gutters.offsetWidth,r=Math.round(e.doc.height+bt(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?i:0,docHeight:r,scrollHeight:r+Pt(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:i}}function E(e,t,i){this.cm=i;var r=this.vert=bo("div",[bo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),n=this.horiz=bo("div",[bo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");e(r);e(n);Ea(r,"scroll",function(){r.clientHeight&&t(r.scrollTop,"vertical")});Ea(n,"scroll",function(){n.clientWidth&&t(n.scrollLeft,"horizontal")});this.checkedOverlay=!1;ns&&8>os&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function m(){}function g(t){if(t.display.scrollbars){t.display.scrollbars.clear();t.display.scrollbars.addClass&&wa(t.display.wrapper,t.display.scrollbars.addClass)}t.display.scrollbars=new e.scrollbarModel[t.options.scrollbarStyle](function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller);Ea(e,"mousedown",function(){t.state.focused&&setTimeout(Ao(Oi,t),0)});e.setAttribute("not-content","true")},function(e,i){"horizontal"==i?zi(t,e):qi(t,e)},t);t.display.scrollbars.addClass&&_a(t.display.wrapper,t.display.scrollbars.addClass)}function v(e,t){t||(t=h(e));var i=e.display.barWidth,r=e.display.barHeight;x(e,t);for(var n=0;4>n&&i!=e.display.barWidth||r!=e.display.barHeight;n++){i!=e.display.barWidth&&e.options.lineWrapping&&P(e);x(e,h(e));i=e.display.barWidth;r=e.display.barHeight}}function x(e,t){var i=e.display,r=i.scrollbars.update(t);i.sizer.style.paddingRight=(i.barWidth=r.right)+"px";i.sizer.style.paddingBottom=(i.barHeight=r.bottom)+"px";if(r.right&&r.bottom){i.scrollbarFiller.style.display="block";i.scrollbarFiller.style.height=r.bottom+"px";i.scrollbarFiller.style.width=r.right+"px"}else i.scrollbarFiller.style.display="";if(r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter){i.gutterFiller.style.display="block";i.gutterFiller.style.height=r.bottom+"px";i.gutterFiller.style.width=t.gutterWidth+"px"}else i.gutterFiller.style.display=""}function N(e,t,i){var r=i&&null!=i.top?Math.max(0,i.top):e.scroller.scrollTop;r=Math.floor(r-Rt(e));var n=i&&null!=i.bottom?i.bottom:r+e.wrapper.clientHeight,o=jn(t,r),s=jn(t,n);if(i&&i.ensure){var a=i.ensure.from.line,l=i.ensure.to.line;if(o>a){o=a;s=jn(t,Wn(Bn(t,a))+e.wrapper.clientHeight)}else if(Math.min(l,t.lastLine())>=s){o=jn(t,Wn(Bn(t,l))-e.wrapper.clientHeight);s=l}}return{from:o,to:Math.max(s,o+1)}}function T(e){var t=e.display,i=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=y(t)-t.scroller.scrollLeft+e.doc.scrollLeft,n=t.gutters.offsetWidth,o=r+"px",s=0;s<i.length;s++)if(!i[s].hidden){e.options.fixedGutter&&i[s].gutter&&(i[s].gutter.style.left=o);var a=i[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+n+"px")}}function L(e){if(!e.options.lineNumbers)return!1;var t=e.doc,i=I(e.options,t.first+t.size-1),r=e.display;if(i.length!=r.lineNumChars){var n=r.measure.appendChild(bo("div",[bo("div",i)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=n.firstChild.offsetWidth,s=n.offsetWidth-o;r.lineGutter.style.width="";r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-s);r.lineNumWidth=r.lineNumInnerWidth+s;r.lineNumChars=r.lineNumInnerWidth?i.length:-1;r.lineGutter.style.width=r.lineNumWidth+"px";p(e);return!0}return!1}function I(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function y(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function A(e,t,i){var r=e.display;this.viewport=t;this.visible=N(r,e.doc,t);this.editorIsHidden=!r.wrapper.offsetWidth;this.wrapperHeight=r.wrapper.clientHeight;this.wrapperWidth=r.wrapper.clientWidth;this.oldDisplayWidth=Dt(e);this.force=i;this.dims=w(e)}function S(e){var t=e.display;if(!t.scrollbarsClipped&&t.scroller.offsetWidth){t.nativeBarWidth=t.scroller.offsetWidth-t.scroller.clientWidth;t.heightForcer.style.height=Pt(e)+"px";t.sizer.style.marginBottom=-t.nativeBarWidth+"px";t.sizer.style.borderRightWidth=Pt(e)+"px";t.scrollbarsClipped=!0}}function C(e,t){var i=e.display,r=e.doc;if(t.editorIsHidden){Ti(e);return!1}if(!t.force&&t.visible.from>=i.viewFrom&&t.visible.to<=i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo)&&i.renderedView==i.view&&0==Ai(e))return!1;if(L(e)){Ti(e);t.dims=w(e)}var n=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),s=Math.min(n,t.visible.to+e.options.viewportMargin);i.viewFrom<o&&o-i.viewFrom<20&&(o=Math.max(r.first,i.viewFrom));i.viewTo>s&&i.viewTo-s<20&&(s=Math.min(n,i.viewTo));if(Ls){o=an(e.doc,o);s=ln(e.doc,s)}var a=o!=i.viewFrom||s!=i.viewTo||i.lastWrapHeight!=t.wrapperHeight||i.lastWrapWidth!=t.wrapperWidth;yi(e,o,s);i.viewOffset=Wn(Bn(e.doc,i.viewFrom));e.display.mover.style.top=i.viewOffset+"px";var l=Ai(e);if(!a&&0==l&&!t.force&&i.renderedView==i.view&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo))return!1;var u=wo();l>4&&(i.lineDiv.style.display="none");_(e,i.updateLineNumbers,t.dims);l>4&&(i.lineDiv.style.display="");i.renderedView=i.view;u&&wo()!=u&&u.offsetHeight&&u.focus();Oo(i.cursorDiv);Oo(i.selectionDiv);i.gutters.style.height=0;if(a){i.lastWrapHeight=t.wrapperHeight;i.lastWrapWidth=t.wrapperWidth;yt(e,400)}i.updateLineNumbers=null;return!0}function R(e,t){for(var i=t.force,r=t.viewport,n=!0;;n=!1){if(n&&e.options.lineWrapping&&t.oldDisplayWidth!=Dt(e))i=!0;else{i=!1;r&&null!=r.top&&(r={top:Math.min(e.doc.height+bt(e.display)-wt(e),r.top)});t.visible=N(e.display,e.doc,r);if(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break}if(!C(e,t))break;P(e);var o=h(e);Nt(e);O(e,o);v(e,o)}po(e,"update",e);if(e.display.viewFrom!=e.display.reportedViewFrom||e.display.viewTo!=e.display.reportedViewTo){po(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo);e.display.reportedViewFrom=e.display.viewFrom;e.display.reportedViewTo=e.display.viewTo}}function b(e,t){var i=new A(e,t);if(C(e,i)){P(e);R(e,i);var r=h(e);Nt(e);O(e,r);v(e,r)}}function O(e,t){e.display.sizer.style.minHeight=t.docHeight+"px";var i=t.docHeight+e.display.barHeight;e.display.heightForcer.style.top=i+"px";e.display.gutters.style.height=Math.max(i+Pt(e),t.clientHeight)+"px"}function P(e){for(var t=e.display,i=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var n,o=t.view[r];if(!o.hidden){if(ns&&8>os){var s=o.node.offsetTop+o.node.offsetHeight;n=s-i;i=s}else{var a=o.node.getBoundingClientRect();n=a.bottom-a.top}var l=o.line.height-n;2>n&&(n=ii(t));if(l>.001||-.001>l){Fn(o.line,n);D(o.line);if(o.rest)for(var u=0;u<o.rest.length;u++)D(o.rest[u])}}}}function D(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function w(e){for(var t=e.display,i={},r={},n=t.gutters.clientLeft,o=t.gutters.firstChild,s=0;o;o=o.nextSibling,++s){i[e.options.gutters[s]]=o.offsetLeft+o.clientLeft+n;r[e.options.gutters[s]]=o.clientWidth}return{fixedPos:y(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:i,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function _(e,t,i){function r(t){var i=t.nextSibling;ss&&ms&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t);return i}for(var n=e.display,o=e.options.lineNumbers,s=n.lineDiv,a=s.firstChild,l=n.view,u=n.viewFrom,p=0;p<l.length;p++){var c=l[p];if(c.hidden);else if(c.node){for(;a!=c.node;)a=r(a);var d=o&&null!=t&&u>=t&&c.lineNumber;if(c.changes){To(c.changes,"gutter")>-1&&(d=!1);M(e,c,u,i)}if(d){Oo(c.lineNumber);c.lineNumber.appendChild(document.createTextNode(I(e.options,u)))}a=c.node.nextSibling}else{var f=j(e,c,u,i);s.insertBefore(f,a)}u+=c.size}for(;a;)a=r(a)}function M(e,t,i,r){for(var n=0;n<t.changes.length;n++){var o=t.changes[n];"text"==o?U(e,t):"gutter"==o?F(e,t,i,r):"class"==o?V(t):"widget"==o&&H(t,r)}t.changes=null}function k(e){if(e.node==e.text){e.node=bo("div",null,null,"position: relative");e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text);e.node.appendChild(e.text);ns&&8>os&&(e.node.style.zIndex=2)}return e.node}function G(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;t&&(t+=" CodeMirror-linebackground");if(e.background)if(t)e.background.className=t;else{e.background.parentNode.removeChild(e.background);e.background=null}else if(t){var i=k(e);e.background=i.insertBefore(bo("div",null,t),i.firstChild)}}function B(e,t){var i=e.display.externalMeasured;if(i&&i.line==t.line){e.display.externalMeasured=null;t.measure=i.measure;return i.built}return An(e,t)}function U(e,t){var i=t.text.className,r=B(e,t);t.text==t.node&&(t.node=r.pre);t.text.parentNode.replaceChild(r.pre,t.text);t.text=r.pre;if(r.bgClass!=t.bgClass||r.textClass!=t.textClass){t.bgClass=r.bgClass;t.textClass=r.textClass;V(t)}else i&&(t.text.className=i)}function V(e){G(e);e.line.wrapClass?k(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function F(e,t,i,r){if(t.gutter){t.node.removeChild(t.gutter);t.gutter=null}var n=t.line.gutterMarkers;if(e.options.lineNumbers||n){var o=k(t),s=t.gutter=o.insertBefore(bo("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),t.text);t.line.gutterClass&&(s.className+=" "+t.line.gutterClass);!e.options.lineNumbers||n&&n["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(bo("div",I(e.options,i),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px")));if(n)for(var a=0;a<e.options.gutters.length;++a){var l=e.options.gutters[a],u=n.hasOwnProperty(l)&&n[l];u&&s.appendChild(bo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function H(e,t){e.alignable&&(e.alignable=null);for(var i,r=e.node.firstChild;r;r=i){var i=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}W(e,t)}function j(e,t,i,r){var n=B(e,t);t.text=t.node=n.pre;n.bgClass&&(t.bgClass=n.bgClass);n.textClass&&(t.textClass=n.textClass);V(t);F(e,t,i,r);W(t,r);return t.node}function W(e,t){q(e.line,e,t,!0);if(e.rest)for(var i=0;i<e.rest.length;i++)q(e.rest[i],e,t,!1)}function q(e,t,i,r){if(e.widgets)for(var n=k(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=bo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||l.setAttribute("cm-ignore-events","true");z(a,l,t,i);r&&a.above?n.insertBefore(l,t.gutter||t.text):n.appendChild(l);po(a,"redraw")}}function z(e,t,i,r){if(e.noHScroll){(i.alignable||(i.alignable=[])).push(t);var n=r.wrapperWidth;t.style.left=r.fixedPos+"px";if(!e.coverGutter){n-=r.gutterTotalWidth;t.style.paddingLeft=r.gutterTotalWidth+"px"}t.style.width=n+"px"}if(e.coverGutter){t.style.zIndex=5;t.style.position="relative";e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px")}}function X(e){return Is(e.line,e.ch)}function Y(e,t){return ys(e,t)<0?t:e}function K(e,t){return ys(e,t)<0?e:t}function $(e,t){this.ranges=e;this.primIndex=t}function Q(e,t){this.anchor=e;this.head=t}function Z(e,t){var i=e[t];e.sort(function(e,t){return ys(e.from(),t.from())});t=To(e,i);for(var r=1;r<e.length;r++){var n=e[r],o=e[r-1];if(ys(o.to(),n.from())>=0){var s=K(o.from(),n.from()),a=Y(o.to(),n.to()),l=o.empty()?n.from()==n.head:o.from()==o.head;t>=r&&--t;e.splice(--r,2,new Q(l?a:s,l?s:a))}}return new $(e,t)}function J(e,t){return new $([new Q(e,t||e)],0)}function et(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function tt(e,t){if(t.line<e.first)return Is(e.first,0);var i=e.first+e.size-1;return t.line>i?Is(i,Bn(e,i).text.length):it(t,Bn(e,t.line).text.length)}function it(e,t){var i=e.ch;return null==i||i>t?Is(e.line,t):0>i?Is(e.line,0):e}function rt(e,t){return t>=e.first&&t<e.first+e.size}function nt(e,t){for(var i=[],r=0;r<t.length;r++)i[r]=tt(e,t[r]);return i}function ot(e,t,i,r){if(e.cm&&e.cm.display.shift||e.extend){var n=t.anchor;if(r){var o=ys(i,n)<0;if(o!=ys(r,n)<0){n=i;i=r}else o!=ys(i,r)<0&&(i=r)}return new Q(n,i)}return new Q(r||i,i)}function st(e,t,i,r){dt(e,new $([ot(e,e.sel.primary(),t,i)],0),r)}function at(e,t,i){for(var r=[],n=0;n<e.sel.ranges.length;n++)r[n]=ot(e,e.sel.ranges[n],t[n],null);var o=Z(r,e.sel.primIndex);dt(e,o,i)}function lt(e,t,i,r){var n=e.sel.ranges.slice(0);n[t]=i;dt(e,Z(n,e.sel.primIndex),r)}function ut(e,t,i,r){dt(e,J(t,i),r)}function pt(e,t){var i={ranges:t.ranges,update:function(t){this.ranges=[];for(var i=0;i<t.length;i++)this.ranges[i]=new Q(tt(e,t[i].anchor),tt(e,t[i].head))}};ga(e,"beforeSelectionChange",e,i);e.cm&&ga(e.cm,"beforeSelectionChange",e.cm,i);return i.ranges!=t.ranges?Z(i.ranges,i.ranges.length-1):t}function ct(e,t,i){var r=e.history.done,n=No(r);if(n&&n.ranges){r[r.length-1]=t;ft(e,t,i)}else dt(e,t,i)}function dt(e,t,i){ft(e,t,i);Zn(e,e.sel,e.cm?e.cm.curOp.id:0/0,i)}function ft(e,t,i){(Eo(e,"beforeSelectionChange")||e.cm&&Eo(e.cm,"beforeSelectionChange"))&&(t=pt(e,t));var r=i&&i.bias||(ys(t.primary().head,e.sel.primary().head)<0?-1:1);ht(e,mt(e,t,r,!0));i&&i.scroll===!1||!e.cm||yr(e.cm)}function ht(e,t){if(!t.equals(e.sel)){e.sel=t;if(e.cm){e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0;ho(e.cm)}po(e,"cursorActivity",e)}}function Et(e){ht(e,mt(e,e.sel,null,!1),Ta)}function mt(e,t,i,r){for(var n,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=gt(e,s.anchor,i,r),l=gt(e,s.head,i,r);if(n||a!=s.anchor||l!=s.head){n||(n=t.ranges.slice(0,o));n[o]=new Q(a,l)}}return n?Z(n,t.primIndex):t}function gt(e,t,i,r){var n=!1,o=t,s=i||1;e.cantEdit=!1;e:for(;;){var a=Bn(e,o.line);if(a.markedSpans)for(var l=0;l<a.markedSpans.length;++l){var u=a.markedSpans[l],p=u.marker;if((null==u.from||(p.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(p.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r){ga(p,"beforeCursorEnter");if(p.explicitlyCleared){if(a.markedSpans){--l;continue}break}}if(!p.atomic)continue;var c=p.find(0>s?-1:1);if(0==ys(c,o)){c.ch+=s;c.ch<0?c=c.line>e.first?tt(e,Is(c.line-1)):null:c.ch>a.text.length&&(c=c.line<e.first+e.size-1?Is(c.line+1,0):null);if(!c){if(n){if(!r)return gt(e,t,i,!0);e.cantEdit=!0;return Is(e.first,0)}n=!0;c=t;s=-s}}o=c;continue e}}return o}}function vt(e){for(var t=e.display,i=e.doc,r={},n=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),s=0;s<i.sel.ranges.length;s++){var a=i.sel.ranges[s],l=a.empty();(l||e.options.showCursorWhenSelecting)&&Tt(e,a,n);l||Lt(e,a,o)}if(e.options.moveInputWithCursor){var u=Qt(e,i.sel.primary().head,"div"),p=t.wrapper.getBoundingClientRect(),c=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+c.top-p.top));r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+c.left-p.left))}return r}function xt(e,t){Po(e.display.cursorDiv,t.cursors);Po(e.display.selectionDiv,t.selection);if(null!=t.teTop){e.display.inputDiv.style.top=t.teTop+"px";e.display.inputDiv.style.left=t.teLeft+"px"}}function Nt(e){xt(e,vt(e))}function Tt(e,t,i){var r=Qt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),n=i.appendChild(bo("div"," ","CodeMirror-cursor"));n.style.left=r.left+"px";n.style.top=r.top+"px";n.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px";if(r.other){var o=i.appendChild(bo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="";o.style.left=r.other.left+"px";o.style.top=r.other.top+"px";o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function Lt(e,t,i){function r(e,t,i,r){0>t&&(t=0);t=Math.round(t);r=Math.round(r);a.appendChild(bo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==i?p-e:i)+"px; height: "+(r-t)+"px"))}function n(t,i,n){function o(i,r){return $t(e,Is(t,i),"div",c,r)}var a,l,c=Bn(s,t),d=c.text.length;Ho(qn(c),i||0,null==n?d:n,function(e,t,s){var c,f,h,E=o(e,"left");if(e==t){c=E;f=h=E.left}else{c=o(t-1,"right");if("rtl"==s){var m=E;E=c;c=m}f=E.left;h=c.right}null==i&&0==e&&(f=u);if(c.top-E.top>3){r(f,E.top,null,E.bottom);f=u;E.bottom<c.top&&r(f,E.bottom,null,c.top)}null==n&&t==d&&(h=p);(!a||E.top<a.top||E.top==a.top&&E.left<a.left)&&(a=E);(!l||c.bottom>l.bottom||c.bottom==l.bottom&&c.right>l.right)&&(l=c);u+1>f&&(f=u);r(f,c.top,h-f,c.bottom)});return{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=Ot(e.display),u=l.left,p=Math.max(o.sizerWidth,Dt(e)-o.sizer.offsetLeft)-l.right,c=t.from(),d=t.to();if(c.line==d.line)n(c.line,c.ch,d.ch);else{var f=Bn(s,c.line),h=Bn(s,d.line),E=on(f)==on(h),m=n(c.line,c.ch,E?f.text.length+1:null).end,g=n(d.line,E?0:null,d.ch).start;if(E)if(m.top<g.top-2){r(m.right,m.top,null,m.bottom);r(u,g.top,g.left,g.bottom)}else r(m.right,m.top,g.left-m.right,m.bottom);m.bottom<g.top&&r(u,m.bottom,null,g.top)}i.appendChild(a)}function It(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var i=!0;t.cursorDiv.style.visibility="";e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(i=!i)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function yt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,Ao(At,e))}function At(e){var t=e.doc;t.frontier<t.first&&(t.frontier=t.first);if(!(t.frontier>=e.display.viewTo)){var i=+new Date+e.options.workTime,r=Xs(t.mode,Ct(e,t.frontier)),n=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(t.frontier>=e.display.viewFrom){var s=o.styles,a=Tn(e,o,r,!0);o.styles=a.styles;var l=o.styleClasses,u=a.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var p=!s||s.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),c=0;!p&&c<s.length;++c)p=s[c]!=o.styles[c];p&&n.push(t.frontier);o.stateAfter=Xs(t.mode,r)}else{In(e,o.text,r);o.stateAfter=t.frontier%5==0?Xs(t.mode,r):null}++t.frontier;if(+new Date>i){yt(e,e.options.workDelay);return!0}});n.length&&fi(e,function(){for(var t=0;t<n.length;t++)Ni(e,n[t],"text")})}}function St(e,t,i){for(var r,n,o=e.doc,s=i?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=Bn(o,a-1);if(l.stateAfter&&(!i||a<=o.frontier))return a;var u=ya(l.text,null,e.options.tabSize);if(null==n||r>u){n=a-1;r=u}}return n}function Ct(e,t,i){var r=e.doc,n=e.display;if(!r.mode.startState)return!0;var o=St(e,t,i),s=o>r.first&&Bn(r,o-1).stateAfter;s=s?Xs(r.mode,s):Ys(r.mode);r.iter(o,t,function(i){In(e,i.text,s);var a=o==t-1||o%5==0||o>=n.viewFrom&&o<n.viewTo;i.stateAfter=a?Xs(r.mode,s):null;++o});i&&(r.frontier=o);return s}function Rt(e){return e.lineSpace.offsetTop}function bt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function Ot(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Po(e.measure,bo("pre","x")),i=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(i.paddingLeft),right:parseInt(i.paddingRight)};isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r);return r}function Pt(e){return xa-e.display.nativeBarWidth}function Dt(e){return e.display.scroller.clientWidth-Pt(e)-e.display.barWidth}function wt(e){return e.display.scroller.clientHeight-Pt(e)-e.display.barHeight}function _t(e,t,i){var r=e.options.lineWrapping,n=r&&Dt(e);if(!t.measure.heights||r&&t.measure.width!=n){var o=t.measure.heights=[];if(r){t.measure.width=n;for(var s=t.text.firstChild.getClientRects(),a=0;a<s.length-1;a++){var l=s[a],u=s[a+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-i.top)}}o.push(i.bottom-i.top)}}function Mt(e,t,i){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(Hn(e.rest[r])>i)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function kt(e,t){t=on(t);var i=Hn(t),r=e.display.externalMeasured=new gi(e.doc,t,i);r.lineN=i;var n=r.built=An(e,r);r.text=n.pre;Po(e.display.lineMeasure,n.pre);return r}function Gt(e,t,i,r){return Vt(e,Ut(e,t),i,r)}function Bt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[Li(e,t)];var i=e.display.externalMeasured;return i&&t>=i.lineN&&t<i.lineN+i.size?i:void 0}function Ut(e,t){var i=Hn(t),r=Bt(e,i);r&&!r.text?r=null:r&&r.changes&&M(e,r,i,w(e));r||(r=kt(e,t));var n=Mt(r,t,i);return{line:t,view:r,rect:null,map:n.map,cache:n.cache,before:n.before,hasHeights:!1}}function Vt(e,t,i,r,n){t.before&&(i=-1);var o,s=i+(r||"");if(t.cache.hasOwnProperty(s))o=t.cache[s];else{t.rect||(t.rect=t.view.text.getBoundingClientRect());if(!t.hasHeights){_t(e,t.view,t.rect);t.hasHeights=!0}o=Ft(e,t,i,r);o.bogus||(t.cache[s]=o)}return{left:o.left,right:o.right,top:n?o.rtop:o.top,bottom:n?o.rbottom:o.bottom}}function Ft(e,t,i,r){for(var n,o,s,a,l=t.map,u=0;u<l.length;u+=3){var p=l[u],c=l[u+1];if(p>i){o=0;s=1;a="left"}else if(c>i){o=i-p;s=o+1}else if(u==l.length-3||i==c&&l[u+3]>i){s=c-p;o=s-1;i>=c&&(a="right")}if(null!=o){n=l[u+2];p==c&&r==(n.insertLeft?"left":"right")&&(a=r);if("left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;){n=l[(u-=3)+2];a="left"}if("right"==r&&o==c-p)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;){n=l[(u+=3)+2];a="right"}break}}var d;if(3==n.nodeType){for(var u=0;4>u;u++){for(;o&&Ro(t.line.text.charAt(p+o));)--o;for(;c>p+s&&Ro(t.line.text.charAt(p+s));)++s;if(ns&&9>os&&0==o&&s==c-p)d=n.parentNode.getBoundingClientRect();else if(ns&&e.options.lineWrapping){var f=Ca(n,o,s).getClientRects();d=f.length?f["right"==r?f.length-1:0]:Rs}else d=Ca(n,o,s).getBoundingClientRect()||Rs;if(d.left||d.right||0==o)break;s=o;o-=1;a="right"}ns&&11>os&&(d=Ht(e.display.measure,d))}else{o>0&&(a=r="right");var f;d=e.options.lineWrapping&&(f=n.getClientRects()).length>1?f["right"==r?f.length-1:0]:n.getBoundingClientRect()}if(ns&&9>os&&!o&&(!d||!d.left&&!d.right)){var h=n.parentNode.getClientRects()[0];d=h?{left:h.left,right:h.left+ri(e.display),top:h.top,bottom:h.bottom}:Rs}for(var E=d.top-t.rect.top,m=d.bottom-t.rect.top,g=(E+m)/2,v=t.view.measure.heights,u=0;u<v.length-1&&!(g<v[u]);u++);var x=u?v[u-1]:0,N=v[u],T={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:x,bottom:N};d.left||d.right||(T.bogus=!0);if(!e.options.singleCursorHeightPerLine){T.rtop=E;T.rbottom=m}return T}function Ht(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Fo(e))return t;var i=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*i,right:t.right*i,top:t.top*r,bottom:t.bottom*r}}function jt(e){if(e.measure){e.measure.cache={};e.measure.heights=null;if(e.rest)for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}}function Wt(e){e.display.externalMeasure=null;Oo(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)jt(e.display.view[t])}function qt(e){Wt(e);e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null;e.options.lineWrapping||(e.display.maxLineChanged=!0);e.display.lineNumChars=null}function zt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Xt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function Yt(e,t,i,r){if(t.widgets)for(var n=0;n<t.widgets.length;++n)if(t.widgets[n].above){var o=dn(t.widgets[n]);i.top+=o;i.bottom+=o}if("line"==r)return i;r||(r="local");var s=Wn(t);"local"==r?s+=Rt(e.display):s-=e.display.viewOffset;if("page"==r||"window"==r){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==r?0:Xt());var l=a.left+("window"==r?0:zt());i.left+=l;i.right+=l}i.top+=s;i.bottom+=s;return i}function Kt(e,t,i){if("div"==i)return t;var r=t.left,n=t.top;if("page"==i){r-=zt();n-=Xt()}else if("local"==i||!i){var o=e.display.sizer.getBoundingClientRect();r+=o.left;n+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:r-s.left,top:n-s.top}}function $t(e,t,i,r,n){r||(r=Bn(e.doc,t.line));return Yt(e,r,Gt(e,r,t.ch,n),i)}function Qt(e,t,i,r,n,o){function s(t,s){var a=Vt(e,n,t,s?"right":"left",o);s?a.left=a.right:a.right=a.left;return Yt(e,r,a,i)}function a(e,t){var i=l[t],r=i.level%2;if(e==jo(i)&&t&&i.level<l[t-1].level){i=l[--t];e=Wo(i)-(i.level%2?0:1);r=!0}else if(e==Wo(i)&&t<l.length-1&&i.level<l[t+1].level){i=l[++t];e=jo(i)-i.level%2;r=!1}return r&&e==i.to&&e>i.from?s(e-1):s(e,r)}r=r||Bn(e.doc,t.line);n||(n=Ut(e,r));var l=qn(r),u=t.ch;if(!l)return s(u);var p=Qo(l,u),c=a(u,p);null!=Ha&&(c.other=a(u,Ha));return c}function Zt(e,t){var i=0,t=tt(e.doc,t);e.options.lineWrapping||(i=ri(e.display)*t.ch);var r=Bn(e.doc,t.line),n=Wn(r)+Rt(e.display);return{left:i,right:i,top:n,bottom:n+r.height}}function Jt(e,t,i,r){var n=Is(e,t);n.xRel=r;i&&(n.outside=!0);return n}function ei(e,t,i){var r=e.doc;i+=e.display.viewOffset;if(0>i)return Jt(r.first,0,!0,-1);var n=jn(r,i),o=r.first+r.size-1;if(n>o)return Jt(r.first+r.size-1,Bn(r,o).text.length,!0,1);0>t&&(t=0);for(var s=Bn(r,n);;){var a=ti(e,s,n,t,i),l=rn(s),u=l&&l.find(0,!0);if(!l||!(a.ch>u.from.ch||a.ch==u.from.ch&&a.xRel>0))return a;n=Hn(s=u.to.line)}}function ti(e,t,i,r,n){function o(r){var n=Qt(e,Is(i,r),"line",t,u);a=!0;if(s>n.bottom)return n.left-l;if(s<n.top)return n.left+l;a=!1;return n.left}var s=n-Wn(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Ut(e,t),p=qn(t),c=t.text.length,d=qo(t),f=zo(t),h=o(d),E=a,m=o(f),g=a;if(r>m)return Jt(i,f,g,1);for(;;){if(p?f==d||f==Jo(t,d,1):1>=f-d){for(var v=h>r||m-r>=r-h?d:f,x=r-(v==d?h:m);Ro(t.text.charAt(v));)++v;var N=Jt(i,v,v==d?E:g,-1>x?-1:x>1?1:0);return N}var T=Math.ceil(c/2),L=d+T;if(p){L=d;for(var I=0;T>I;++I)L=Jo(t,L,1)}var y=o(L);if(y>r){f=L;m=y;(g=a)&&(m+=1e3);c=T}else{d=L;h=y;E=a;c-=T}}}function ii(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==As){As=bo("pre");for(var t=0;49>t;++t){As.appendChild(document.createTextNode("x"));As.appendChild(bo("br"))}As.appendChild(document.createTextNode("x"))}Po(e.measure,As);var i=As.offsetHeight/50;i>3&&(e.cachedTextHeight=i);Oo(e.measure);return i||1}function ri(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=bo("span","xxxxxxxxxx"),i=bo("pre",[t]);Po(e.measure,i);var r=t.getBoundingClientRect(),n=(r.right-r.left)/10;n>2&&(e.cachedCharWidth=n);return n||10}function ni(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Os};bs?bs.ops.push(e.curOp):e.curOp.ownsGroup=bs={ops:[e.curOp],delayedCallbacks:[]}}function oi(e){var t=e.delayedCallbacks,i=0;do{for(;i<t.length;i++)t[i]();for(var r=0;r<e.ops.length;r++){var n=e.ops[r];if(n.cursorActivityHandlers)for(;n.cursorActivityCalled<n.cursorActivityHandlers.length;)n.cursorActivityHandlers[n.cursorActivityCalled++](n.cm)}}while(i<t.length)}function si(e){var t=e.curOp,i=t.ownsGroup;if(i)try{oi(i)}finally{bs=null;for(var r=0;r<i.ops.length;r++)i.ops[r].cm.curOp=null;ai(i)}}function ai(e){for(var t=e.ops,i=0;i<t.length;i++)li(t[i]);for(var i=0;i<t.length;i++)ui(t[i]);for(var i=0;i<t.length;i++)pi(t[i]);for(var i=0;i<t.length;i++)ci(t[i]);for(var i=0;i<t.length;i++)di(t[i])}function li(e){var t=e.cm,i=t.display;S(t);e.updateMaxLine&&d(t);e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<i.viewFrom||e.scrollToPos.to.line>=i.viewTo)||i.maxLineChanged&&t.options.lineWrapping;e.update=e.mustUpdate&&new A(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function ui(e){e.updatedDisplay=e.mustUpdate&&C(e.cm,e.update)}function pi(e){var t=e.cm,i=t.display;e.updatedDisplay&&P(t);e.barMeasure=h(t);if(i.maxLineChanged&&!t.options.lineWrapping){e.adjustWidthTo=Gt(t,i.maxLine,i.maxLine.text.length).left+3;t.display.sizerWidth=e.adjustWidthTo;e.barMeasure.scrollWidth=Math.max(i.scroller.clientWidth,i.sizer.offsetLeft+e.adjustWidthTo+Pt(t)+t.display.barWidth);e.maxScrollLeft=Math.max(0,i.sizer.offsetLeft+e.adjustWidthTo-Dt(t))}(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=vt(t))}function ci(e){var t=e.cm;if(null!=e.adjustWidthTo){t.display.sizer.style.minWidth=e.adjustWidthTo+"px";e.maxScrollLeft<t.doc.scrollLeft&&zi(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0);t.display.maxLineChanged=!1}e.newSelectionNodes&&xt(t,e.newSelectionNodes);e.updatedDisplay&&O(t,e.barMeasure);(e.updatedDisplay||e.startHeight!=t.doc.height)&&v(t,e.barMeasure);e.selectionChanged&&It(t);t.state.focused&&e.updateInput&&bi(t,e.typing)}function di(e){var t=e.cm,i=t.display,r=t.doc;e.updatedDisplay&&R(t,e.update);null==i.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(i.wheelStartX=i.wheelStartY=null);if(null!=e.scrollTop&&(i.scroller.scrollTop!=e.scrollTop||e.forceScroll)){r.scrollTop=Math.max(0,Math.min(i.scroller.scrollHeight-i.scroller.clientHeight,e.scrollTop));i.scrollbars.setScrollTop(r.scrollTop);i.scroller.scrollTop=r.scrollTop}if(null!=e.scrollLeft&&(i.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){r.scrollLeft=Math.max(0,Math.min(i.scroller.scrollWidth-Dt(t),e.scrollLeft));i.scrollbars.setScrollLeft(r.scrollLeft);i.scroller.scrollLeft=r.scrollLeft;T(t)}if(e.scrollToPos){var n=Nr(t,tt(r,e.scrollToPos.from),tt(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&xr(t,n)}var o=e.maybeHiddenMarkers,s=e.maybeUnhiddenMarkers;if(o)for(var a=0;a<o.length;++a)o[a].lines.length||ga(o[a],"hide");if(s)for(var a=0;a<s.length;++a)s[a].lines.length&&ga(s[a],"unhide");i.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop);e.changeObjs&&ga(t,"changes",t,e.changeObjs)}function fi(e,t){if(e.curOp)return t();ni(e);try{return t()}finally{si(e)}}function hi(e,t){return function(){if(e.curOp)return t.apply(e,arguments);ni(e);try{return t.apply(e,arguments)}finally{si(e)}}}function Ei(e){return function(){if(this.curOp)return e.apply(this,arguments);ni(this);try{return e.apply(this,arguments)}finally{si(this)}}}function mi(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);ni(t);try{return e.apply(this,arguments)}finally{si(t)}}}function gi(e,t,i){this.line=t;this.rest=sn(t);this.size=this.rest?Hn(No(this.rest))-i+1:1;this.node=this.text=null;this.hidden=un(e,t)}function vi(e,t,i){for(var r,n=[],o=t;i>o;o=r){var s=new gi(e.doc,Bn(e.doc,o),o);r=o+s.size;n.push(s)}return n}function xi(e,t,i,r){null==t&&(t=e.doc.first);null==i&&(i=e.doc.first+e.doc.size);r||(r=0);var n=e.display;r&&i<n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>t)&&(n.updateLineNumbers=t);e.curOp.viewChanged=!0;if(t>=n.viewTo)Ls&&an(e.doc,t)<n.viewTo&&Ti(e);else if(i<=n.viewFrom)if(Ls&&ln(e.doc,i+r)>n.viewFrom)Ti(e);
else{n.viewFrom+=r;n.viewTo+=r}else if(t<=n.viewFrom&&i>=n.viewTo)Ti(e);else if(t<=n.viewFrom){var o=Ii(e,i,i+r,1);if(o){n.view=n.view.slice(o.index);n.viewFrom=o.lineN;n.viewTo+=r}else Ti(e)}else if(i>=n.viewTo){var o=Ii(e,t,t,-1);if(o){n.view=n.view.slice(0,o.index);n.viewTo=o.lineN}else Ti(e)}else{var s=Ii(e,t,t,-1),a=Ii(e,i,i+r,1);if(s&&a){n.view=n.view.slice(0,s.index).concat(vi(e,s.lineN,a.lineN)).concat(n.view.slice(a.index));n.viewTo+=r}else Ti(e)}var l=n.externalMeasured;l&&(i<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(n.externalMeasured=null))}function Ni(e,t,i){e.curOp.viewChanged=!0;var r=e.display,n=e.display.externalMeasured;n&&t>=n.lineN&&t<n.lineN+n.size&&(r.externalMeasured=null);if(!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[Li(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==To(s,i)&&s.push(i)}}}function Ti(e){e.display.viewFrom=e.display.viewTo=e.doc.first;e.display.view=[];e.display.viewOffset=0}function Li(e,t){if(t>=e.display.viewTo)return null;t-=e.display.viewFrom;if(0>t)return null;for(var i=e.display.view,r=0;r<i.length;r++){t-=i[r].size;if(0>t)return r}}function Ii(e,t,i,r){var n,o=Li(e,t),s=e.display.view;if(!Ls||i==e.doc.first+e.doc.size)return{index:o,lineN:i};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(r>0){if(o==s.length-1)return null;n=l+s[o].size-t;o++}else n=l-t;t+=n;i+=n}for(;an(e.doc,i)!=i;){if(o==(0>r?0:s.length-1))return null;i+=r*s[o-(0>r?1:0)].size;o+=r}return{index:o,lineN:i}}function yi(e,t,i){var r=e.display,n=r.view;if(0==n.length||t>=r.viewTo||i<=r.viewFrom){r.view=vi(e,t,i);r.viewFrom=t}else{r.viewFrom>t?r.view=vi(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(Li(e,t)));r.viewFrom=t;r.viewTo<i?r.view=r.view.concat(vi(e,r.viewTo,i)):r.viewTo>i&&(r.view=r.view.slice(0,Li(e,i)))}r.viewTo=i}function Ai(e){for(var t=e.display.view,i=0,r=0;r<t.length;r++){var n=t[r];n.hidden||n.node&&!n.changes||++i}return i}function Si(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){Ri(e);e.state.focused&&Si(e)})}function Ci(e){function t(){var r=Ri(e);if(r||i){e.display.pollingFast=!1;Si(e)}else{i=!0;e.display.poll.set(60,t)}}var i=!1;e.display.pollingFast=!0;e.display.poll.set(20,t)}function Ri(e){var t=e.display.input,i=e.display.prevInput,r=e.doc;if(!e.state.focused||Ba(t)&&!i||Di(e)||e.options.disableInput||e.state.keySeq)return!1;if(e.state.pasteIncoming&&e.state.fakedLastChar){t.value=t.value.substring(0,t.value.length-1);e.state.fakedLastChar=!1}var n=t.value;if(n==i&&!e.somethingSelected())return!1;if(ns&&os>=9&&e.display.inputHasSelection===n||ms&&/[\uf700-\uf7ff]/.test(n)){bi(e);return!1}var o=!e.curOp;o&&ni(e);e.display.shift=!1;8203!=n.charCodeAt(0)||r.sel!=e.display.selForContextMenu||i||(i="");for(var s=0,a=Math.min(i.length,n.length);a>s&&i.charCodeAt(s)==n.charCodeAt(s);)++s;var l=n.slice(s),u=Ga(l),p=null;e.state.pasteIncoming&&r.sel.ranges.length>1&&(Ps&&Ps.join("\n")==l?p=r.sel.ranges.length%Ps.length==0&&Lo(Ps,Ga):u.length==r.sel.ranges.length&&(p=Lo(u,function(e){return[e]})));for(var c=r.sel.ranges.length-1;c>=0;c--){var d=r.sel.ranges[c],f=d.from(),h=d.to();s<i.length?f=Is(f.line,f.ch-(i.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(h=Is(h.line,Math.min(Bn(r,h.line).text.length,h.ch+No(u).length)));var E=e.curOp.updateInput,m={from:f,to:h,text:p?p[c%p.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};dr(e.doc,m);po(e,"inputRead",e,m);if(l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!c||r.sel.ranges[c-1].head.line!=d.head.line)){var g=e.getModeAt(d.head),v=Bs(m);if(g.electricChars){for(var x=0;x<g.electricChars.length;x++)if(l.indexOf(g.electricChars.charAt(x))>-1){Sr(e,v.line,"smart");break}}else g.electricInput&&g.electricInput.test(Bn(r,v.line).text.slice(0,v.ch))&&Sr(e,v.line,"smart")}}yr(e);e.curOp.updateInput=E;e.curOp.typing=!0;n.length>1e3||n.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=n;o&&si(e);e.state.pasteIncoming=e.state.cutIncoming=!1;return!0}function bi(e,t){if(!e.display.contextMenuPending){var i,r,n=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=n.sel.primary();i=Ua&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var s=i?"-":r||e.getSelection();e.display.input.value=s;e.state.focused&&Sa(e.display.input);ns&&os>=9&&(e.display.inputHasSelection=s)}else if(!t){e.display.prevInput=e.display.input.value="";ns&&os>=9&&(e.display.inputHasSelection=null)}e.display.inaccurateSelection=i}}function Oi(e){"nocursor"==e.options.readOnly||Es&&wo()==e.display.input||e.display.input.focus()}function Pi(e){if(!e.state.focused){Oi(e);rr(e)}}function Di(e){return e.options.readOnly||e.doc.cantEdit}function wi(e){function t(t){fo(e,t)||ha(t)}function i(t){if(e.somethingSelected()){Ps=e.getSelections();if(r.inaccurateSelection){r.prevInput="";r.inaccurateSelection=!1;r.input.value=Ps.join("\n");Sa(r.input)}}else{for(var i=[],n=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:Is(s,0),head:Is(s+1,0)};n.push(a);i.push(e.getRange(a.anchor,a.head))}if("cut"==t.type)e.setSelections(n,null,Ta);else{r.prevInput="";r.input.value=i.join("\n");Sa(r.input)}Ps=i}"cut"==t.type&&(e.state.cutIncoming=!0)}var r=e.display;Ea(r.scroller,"mousedown",hi(e,Gi));ns&&11>os?Ea(r.scroller,"dblclick",hi(e,function(t){if(!fo(e,t)){var i=ki(e,t);if(i&&!Hi(e,t)&&!Mi(e.display,t)){da(t);var r=e.findWordAt(i);st(e.doc,r.anchor,r.head)}}})):Ea(r.scroller,"dblclick",function(t){fo(e,t)||da(t)});Ea(r.lineSpace,"selectstart",function(e){Mi(r,e)||da(e)});Ns||Ea(r.scroller,"contextmenu",function(t){or(e,t)});Ea(r.scroller,"scroll",function(){if(r.scroller.clientHeight){qi(e,r.scroller.scrollTop);zi(e,r.scroller.scrollLeft,!0);ga(e,"scroll",e)}});Ea(r.scroller,"mousewheel",function(t){Xi(e,t)});Ea(r.scroller,"DOMMouseScroll",function(t){Xi(e,t)});Ea(r.wrapper,"scroll",function(){r.wrapper.scrollTop=r.wrapper.scrollLeft=0});Ea(r.input,"keyup",function(t){tr.call(e,t)});Ea(r.input,"input",function(){ns&&os>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null);Ri(e)});Ea(r.input,"keydown",hi(e,Ji));Ea(r.input,"keypress",hi(e,ir));Ea(r.input,"focus",Ao(rr,e));Ea(r.input,"blur",Ao(nr,e));if(e.options.dragDrop){Ea(r.scroller,"dragstart",function(t){Wi(e,t)});Ea(r.scroller,"dragenter",t);Ea(r.scroller,"dragover",t);Ea(r.scroller,"drop",hi(e,ji))}Ea(r.scroller,"paste",function(t){if(!Mi(r,t)){e.state.pasteIncoming=!0;Oi(e);Ci(e)}});Ea(r.input,"paste",function(){if(ss&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=r.input.selectionStart,i=r.input.selectionEnd;r.input.value+="$";r.input.selectionEnd=i;r.input.selectionStart=t;e.state.fakedLastChar=!0}e.state.pasteIncoming=!0;Ci(e)});Ea(r.input,"cut",i);Ea(r.input,"copy",i);cs&&Ea(r.sizer,"mouseup",function(){wo()==r.input&&r.input.blur();Oi(e)})}function _i(e){var t=e.display;if(t.lastWrapHeight!=t.wrapper.clientHeight||t.lastWrapWidth!=t.wrapper.clientWidth){t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null;t.scrollbarsClipped=!1;e.setSize()}}function Mi(e,t){for(var i=lo(t);i!=e.wrapper;i=i.parentNode)if(!i||1==i.nodeType&&"true"==i.getAttribute("cm-ignore-events")||i.parentNode==e.sizer&&i!=e.mover)return!0}function ki(e,t,i,r){var n=e.display;if(!i&&"true"==lo(t).getAttribute("not-content"))return null;var o,s,a=n.lineSpace.getBoundingClientRect();try{o=t.clientX-a.left;s=t.clientY-a.top}catch(t){return null}var l,u=ei(e,o,s);if(r&&1==u.xRel&&(l=Bn(e.doc,u.line).text).length==u.ch){var p=ya(l,l.length,e.options.tabSize)-l.length;u=Is(u.line,Math.max(0,Math.round((o-Ot(e.display).left)/ri(e.display))-p))}return u}function Gi(e){if(!fo(this,e)){var t=this,i=t.display;i.shift=e.shiftKey;if(Mi(i,e)){if(!ss){i.scroller.draggable=!1;setTimeout(function(){i.scroller.draggable=!0},100)}}else if(!Hi(t,e)){var r=ki(t,e);window.focus();switch(uo(e)){case 1:r?Bi(t,e,r):lo(e)==i.scroller&&da(e);break;case 2:ss&&(t.state.lastMiddleDown=+new Date);r&&st(t.doc,r);setTimeout(Ao(Oi,t),20);da(e);break;case 3:Ns&&or(t,e)}}}}function Bi(e,t,i){setTimeout(Ao(Pi,e),0);var r,n=+new Date;if(Cs&&Cs.time>n-400&&0==ys(Cs.pos,i))r="triple";else if(Ss&&Ss.time>n-400&&0==ys(Ss.pos,i)){r="double";Cs={time:n,pos:i}}else{r="single";Ss={time:n,pos:i}}var o,s=e.doc.sel,a=ms?t.metaKey:t.ctrlKey;e.options.dragDrop&&ka&&!Di(e)&&"single"==r&&(o=s.contains(i))>-1&&!s.ranges[o].empty()?Ui(e,t,i,a):Vi(e,t,i,r,a)}function Ui(e,t,i,r){var n=e.display,o=hi(e,function(s){ss&&(n.scroller.draggable=!1);e.state.draggingText=!1;ma(document,"mouseup",o);ma(n.scroller,"drop",o);if(Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10){da(s);r||st(e.doc,i);Oi(e);ns&&9==os&&setTimeout(function(){document.body.focus();Oi(e)},20)}});ss&&(n.scroller.draggable=!0);e.state.draggingText=o;n.scroller.dragDrop&&n.scroller.dragDrop();Ea(document,"mouseup",o);Ea(n.scroller,"drop",o)}function Vi(e,t,i,r,n){function o(t){if(0!=ys(m,t)){m=t;if("rect"==r){for(var n=[],o=e.options.tabSize,s=ya(Bn(u,i.line).text,i.ch,o),a=ya(Bn(u,t.line).text,t.ch,o),l=Math.min(s,a),f=Math.max(s,a),h=Math.min(i.line,t.line),E=Math.min(e.lastLine(),Math.max(i.line,t.line));E>=h;h++){var g=Bn(u,h).text,v=vo(g,l,o);l==f?n.push(new Q(Is(h,v),Is(h,v))):g.length>v&&n.push(new Q(Is(h,v),Is(h,vo(g,f,o))))}n.length||n.push(new Q(i,i));dt(u,Z(d.ranges.slice(0,c).concat(n),c),{origin:"*mouse",scroll:!1});e.scrollIntoView(t)}else{var x=p,N=x.anchor,T=t;if("single"!=r){if("double"==r)var L=e.findWordAt(t);else var L=new Q(Is(t.line,0),tt(u,Is(t.line+1,0)));if(ys(L.anchor,N)>0){T=L.head;N=K(x.from(),L.anchor)}else{T=L.anchor;N=Y(x.to(),L.head)}}var n=d.ranges.slice(0);n[c]=new Q(tt(u,N),T);dt(u,Z(n,c),La)}}}function s(t){var i=++v,n=ki(e,t,!0,"rect"==r);if(n)if(0!=ys(n,m)){Pi(e);o(n);var a=N(l,u);(n.line>=a.to||n.line<a.from)&&setTimeout(hi(e,function(){v==i&&s(t)}),150)}else{var p=t.clientY<g.top?-20:t.clientY>g.bottom?20:0;p&&setTimeout(hi(e,function(){if(v==i){l.scroller.scrollTop+=p;s(t)}}),50)}}function a(t){v=1/0;da(t);Oi(e);ma(document,"mousemove",x);ma(document,"mouseup",T);u.history.lastSelOrigin=null}var l=e.display,u=e.doc;da(t);var p,c,d=u.sel,f=d.ranges;if(n&&!t.shiftKey){c=u.sel.contains(i);p=c>-1?f[c]:new Q(i,i)}else p=u.sel.primary();if(t.altKey){r="rect";n||(p=new Q(i,i));i=ki(e,t,!0,!0);c=-1}else if("double"==r){var h=e.findWordAt(i);p=e.display.shift||u.extend?ot(u,p,h.anchor,h.head):h}else if("triple"==r){var E=new Q(Is(i.line,0),tt(u,Is(i.line+1,0)));p=e.display.shift||u.extend?ot(u,p,E.anchor,E.head):E}else p=ot(u,p,i);if(n)if(-1==c){c=f.length;dt(u,Z(f.concat([p]),c),{scroll:!1,origin:"*mouse"})}else if(f.length>1&&f[c].empty()&&"single"==r){dt(u,Z(f.slice(0,c).concat(f.slice(c+1)),0));d=u.sel}else lt(u,c,p,La);else{c=0;dt(u,new $([p],0),La);d=u.sel}var m=i,g=l.wrapper.getBoundingClientRect(),v=0,x=hi(e,function(e){uo(e)?s(e):a(e)}),T=hi(e,a);Ea(document,"mousemove",x);Ea(document,"mouseup",T)}function Fi(e,t,i,r,n){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&da(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!Eo(e,i))return ao(t);s-=l.top-a.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var p=a.gutters.childNodes[u];if(p&&p.getBoundingClientRect().right>=o){var c=jn(e.doc,s),d=e.options.gutters[u];n(e,i,e,c,d,t);return ao(t)}}}function Hi(e,t){return Fi(e,t,"gutterClick",!0,po)}function ji(e){var t=this;if(!fo(t,e)&&!Mi(t.display,e)){da(e);ns&&(Ds=+new Date);var i=ki(t,e,!0),r=e.dataTransfer.files;if(i&&!Di(t))if(r&&r.length&&window.FileReader&&window.File)for(var n=r.length,o=Array(n),s=0,a=function(e,r){var a=new FileReader;a.onload=hi(t,function(){o[r]=a.result;if(++s==n){i=tt(t.doc,i);var e={from:i,to:i,text:Ga(o.join("\n")),origin:"paste"};dr(t.doc,e);ct(t.doc,J(i,Bs(e)))}});a.readAsText(e)},l=0;n>l;++l)a(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(i)>-1){t.state.draggingText(e);setTimeout(Ao(Oi,t),20);return}try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(ms?e.metaKey:e.ctrlKey))var u=t.listSelections();ft(t.doc,J(i,i));if(u)for(var l=0;l<u.length;++l)vr(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste");Oi(t)}}catch(e){}}}}function Wi(e,t){if(ns&&(!e.state.draggingText||+new Date-Ds<100))ha(t);else if(!fo(e,t)&&!Mi(e.display,t)){t.dataTransfer.setData("Text",e.getSelection());if(t.dataTransfer.setDragImage&&!ps){var i=bo("img",null,null,"position: fixed; left: 0; top: 0;");i.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(us){i.width=i.height=1;e.display.wrapper.appendChild(i);i._top=i.offsetTop}t.dataTransfer.setDragImage(i,0,0);us&&i.parentNode.removeChild(i)}}}function qi(e,t){if(!(Math.abs(e.doc.scrollTop-t)<2)){e.doc.scrollTop=t;ts||b(e,{top:t});e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t);e.display.scrollbars.setScrollTop(t);ts&&b(e);yt(e,100)}}function zi(e,t,i){if(!(i?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)){t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth);e.doc.scrollLeft=t;T(e);e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t);e.display.scrollbars.setScrollLeft(t)}}function Xi(e,t){var i=Ms(t),r=i.x,n=i.y,o=e.display,s=o.scroller;if(r&&s.scrollWidth>s.clientWidth||n&&s.scrollHeight>s.clientHeight){if(n&&ms&&ss)e:for(var a=t.target,l=o.view;a!=s;a=a.parentNode)for(var u=0;u<l.length;u++)if(l[u].node==a){e.display.currentWheelTarget=a;break e}if(!r||ts||us||null==_s){if(n&&null!=_s){var p=n*_s,c=e.doc.scrollTop,d=c+o.wrapper.clientHeight;0>p?c=Math.max(0,c+p-50):d=Math.min(e.doc.height,d+p+50);b(e,{top:c,bottom:d})}if(20>ws)if(null==o.wheelStartX){o.wheelStartX=s.scrollLeft;o.wheelStartY=s.scrollTop;o.wheelDX=r;o.wheelDY=n;setTimeout(function(){if(null!=o.wheelStartX){var e=s.scrollLeft-o.wheelStartX,t=s.scrollTop-o.wheelStartY,i=t&&o.wheelDY&&t/o.wheelDY||e&&o.wheelDX&&e/o.wheelDX;o.wheelStartX=o.wheelStartY=null;if(i){_s=(_s*ws+i)/(ws+1);++ws}}},200)}else{o.wheelDX+=r;o.wheelDY+=n}}else{n&&qi(e,Math.max(0,Math.min(s.scrollTop+n*_s,s.scrollHeight-s.clientHeight)));zi(e,Math.max(0,Math.min(s.scrollLeft+r*_s,s.scrollWidth-s.clientWidth)));da(t);o.wheelStartX=null}}}function Yi(e,t,i){if("string"==typeof t){t=Ks[t];if(!t)return!1}e.display.pollingFast&&Ri(e)&&(e.display.pollingFast=!1);var r=e.display.shift,n=!1;try{Di(e)&&(e.state.suppressEdits=!0);i&&(e.display.shift=!1);n=t(e)!=Na}finally{e.display.shift=r;e.state.suppressEdits=!1}return n}function Ki(e,t,i){for(var r=0;r<e.state.keyMaps.length;r++){var n=Qs(t,e.state.keyMaps[r],i,e);if(n)return n}return e.options.extraKeys&&Qs(t,e.options.extraKeys,i,e)||Qs(t,e.options.keyMap,i,e)}function $i(e,t,i,r){var n=e.state.keySeq;if(n){if(Zs(t))return"handled";ks.set(50,function(){if(e.state.keySeq==n){e.state.keySeq=null;bi(e)}});t=n+" "+t}var o=Ki(e,t,r);"multi"==o&&(e.state.keySeq=t);"handled"==o&&po(e,"keyHandled",e,t,i);if("handled"==o||"multi"==o){da(i);It(e)}if(n&&!o&&/\'$/.test(t)){da(i);return!0}return!!o}function Qi(e,t){var i=Js(t,!0);return i?t.shiftKey&&!e.state.keySeq?$i(e,"Shift-"+i,t,function(t){return Yi(e,t,!0)})||$i(e,i,t,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Yi(e,t):void 0}):$i(e,i,t,function(t){return Yi(e,t)}):!1}function Zi(e,t,i){return $i(e,"'"+i+"'",t,function(t){return Yi(e,t,!0)})}function Ji(e){var t=this;Pi(t);if(!fo(t,e)){ns&&11>os&&27==e.keyCode&&(e.returnValue=!1);var i=e.keyCode;t.display.shift=16==i||e.shiftKey;var r=Qi(t,e);if(us){Gs=r?i:null;!r&&88==i&&!Ua&&(ms?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")}18!=i||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||er(t)}}function er(e){function t(e){if(18==e.keyCode||!e.altKey){wa(i,"CodeMirror-crosshair");ma(document,"keyup",t);ma(document,"mouseover",t)}}var i=e.display.lineDiv;_a(i,"CodeMirror-crosshair");Ea(document,"keyup",t);Ea(document,"mouseover",t)}function tr(e){16==e.keyCode&&(this.doc.sel.shift=!1);fo(this,e)}function ir(e){var t=this;if(!(fo(t,e)||e.ctrlKey&&!e.altKey||ms&&e.metaKey)){var i=e.keyCode,r=e.charCode;if(us&&i==Gs){Gs=null;da(e)}else if(!(us&&(!e.which||e.which<10)||cs)||!Qi(t,e)){var n=String.fromCharCode(null==r?i:r);if(!Zi(t,e,n)){ns&&os>=9&&(t.display.inputHasSelection=null);Ci(t)}}}}function rr(e){if("nocursor"!=e.options.readOnly){if(!e.state.focused){ga(e,"focus",e);e.state.focused=!0;_a(e.display.wrapper,"CodeMirror-focused");if(!e.curOp&&e.display.selForContextMenu!=e.doc.sel){bi(e);ss&&setTimeout(Ao(bi,e,!0),0)}}Si(e);It(e)}}function nr(e){if(e.state.focused){ga(e,"blur",e);e.state.focused=!1;wa(e.display.wrapper,"CodeMirror-focused")}clearInterval(e.display.blinker);setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function or(e,t){function i(){if(null!=n.input.selectionStart){var t=e.somethingSelected(),i=n.input.value=""+(t?n.input.value:"");n.prevInput=t?"":"";n.input.selectionStart=1;n.input.selectionEnd=i.length;n.selForContextMenu=e.doc.sel}}function r(){n.contextMenuPending=!1;n.inputDiv.style.position="relative";n.input.style.cssText=l;ns&&9>os&&n.scrollbars.setScrollTop(n.scroller.scrollTop=s);Si(e);if(null!=n.input.selectionStart){(!ns||ns&&9>os)&&i();var t=0,r=function(){n.selForContextMenu==e.doc.sel&&0==n.input.selectionStart?hi(e,Ks.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(r,500):bi(e)};n.detectingSelectAll=setTimeout(r,200)}}if(!fo(e,t,"contextmenu")){var n=e.display;if(!Mi(n,t)&&!sr(e,t)){var o=ki(e,t),s=n.scroller.scrollTop;if(o&&!us){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&hi(e,dt)(e.doc,J(o),Ta);var l=n.input.style.cssText;n.inputDiv.style.position="absolute";n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(ns?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(ss)var u=window.scrollY;Oi(e);ss&&window.scrollTo(null,u);bi(e);e.somethingSelected()||(n.input.value=n.prevInput=" ");n.contextMenuPending=!0;n.selForContextMenu=e.doc.sel;clearTimeout(n.detectingSelectAll);ns&&os>=9&&i();if(Ns){ha(t);var p=function(){ma(window,"mouseup",p);setTimeout(r,20)};Ea(window,"mouseup",p)}else setTimeout(r,50)}}}}function sr(e,t){return Eo(e,"gutterContextMenu")?Fi(e,t,"gutterContextMenu",!1,ga):!1}function ar(e,t){if(ys(e,t.from)<0)return e;if(ys(e,t.to)<=0)return Bs(t);var i=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;e.line==t.to.line&&(r+=Bs(t).ch-t.to.ch);return Is(i,r)}function lr(e,t){for(var i=[],r=0;r<e.sel.ranges.length;r++){var n=e.sel.ranges[r];i.push(new Q(ar(n.anchor,t),ar(n.head,t)))}return Z(i,e.sel.primIndex)}function ur(e,t,i){return e.line==t.line?Is(i.line,e.ch-t.ch+i.ch):Is(i.line+(e.line-t.line),e.ch)}function pr(e,t,i){for(var r=[],n=Is(e.first,0),o=n,s=0;s<t.length;s++){var a=t[s],l=ur(a.from,n,o),u=ur(Bs(a),n,o);n=a.to;o=u;if("around"==i){var p=e.sel.ranges[s],c=ys(p.head,p.anchor)<0;r[s]=new Q(c?u:l,c?l:u)}else r[s]=new Q(l,l)}return new $(r,e.sel.primIndex)}function cr(e,t,i){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};i&&(r.update=function(t,i,r,n){t&&(this.from=tt(e,t));i&&(this.to=tt(e,i));r&&(this.text=r);void 0!==n&&(this.origin=n)});ga(e,"beforeChange",e,r);e.cm&&ga(e.cm,"beforeChange",e.cm,r);return r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function dr(e,t,i){if(e.cm){if(!e.cm.curOp)return hi(e.cm,dr)(e,t,i);if(e.cm.state.suppressEdits)return}if(Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange")){t=cr(e,t,!0);if(!t)return}var r=Ts&&!i&&Yr(e,t.from,t.to);if(r)for(var n=r.length-1;n>=0;--n)fr(e,{from:r[n].from,to:r[n].to,text:n?[""]:t.text});else fr(e,t)}function fr(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ys(t.from,t.to)){var i=lr(e,t);$n(e,t,i,e.cm?e.cm.curOp.id:0/0);mr(e,t,i,qr(e,t));var r=[];kn(e,function(e,i){if(!i&&-1==To(r,e.history)){so(e.history,t);r.push(e.history)}mr(e,t,null,qr(e,t))})}}function hr(e,t,i){if(!e.cm||!e.cm.state.suppressEdits){for(var r,n=e.history,o=e.sel,s="undo"==t?n.done:n.undone,a="undo"==t?n.undone:n.done,l=0;l<s.length;l++){r=s[l];if(i?r.ranges&&!r.equals(e.sel):!r.ranges)break}if(l!=s.length){n.lastOrigin=n.lastSelOrigin=null;for(;;){r=s.pop();if(!r.ranges)break;Jn(r,a);if(i&&!r.equals(e.sel)){dt(e,r,{clearRedo:!1});return}o=r}var u=[];Jn(o,a);a.push({changes:u,generation:n.generation});n.generation=r.generation||++n.maxGeneration;for(var p=Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var c=r.changes[l];c.origin=t;if(p&&!cr(e,c,!1)){s.length=0;return}u.push(Xn(e,c));var d=l?lr(e,c):No(s);mr(e,c,d,Xr(e,c));!l&&e.cm&&e.cm.scrollIntoView({from:c.from,to:Bs(c)});var f=[];kn(e,function(e,t){if(!t&&-1==To(f,e.history)){so(e.history,c);f.push(e.history)}mr(e,c,null,Xr(e,c))})}}}}function Er(e,t){if(0!=t){e.first+=t;e.sel=new $(Lo(e.sel.ranges,function(e){return new Q(Is(e.anchor.line+t,e.anchor.ch),Is(e.head.line+t,e.head.ch))}),e.sel.primIndex);if(e.cm){xi(e.cm,e.first,e.first-t,t);for(var i=e.cm.display,r=i.viewFrom;r<i.viewTo;r++)Ni(e.cm,r,"gutter")}}}function mr(e,t,i,r){if(e.cm&&!e.cm.curOp)return hi(e.cm,mr)(e,t,i,r);if(t.to.line<e.first)Er(e,t.text.length-1-(t.to.line-t.from.line));else if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var n=t.text.length-1-(e.first-t.from.line);Er(e,n);t={from:Is(e.first,0),to:Is(t.to.line+n,t.to.ch),text:[No(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:Is(o,Bn(e,o).text.length),text:[t.text[0]],origin:t.origin});t.removed=Un(e,t.from,t.to);i||(i=lr(e,t));e.cm?gr(e.cm,t,r):wn(e,t,r);ft(e,i,Ta)}}function gr(e,t,i){var r=e.doc,n=e.display,s=t.from,a=t.to,l=!1,u=s.line;if(!e.options.lineWrapping){u=Hn(on(Bn(r,s.line)));r.iter(u,a.line+1,function(e){if(e==n.maxLine){l=!0;return!0}})}r.sel.contains(t.from,t.to)>-1&&ho(e);wn(r,t,i,o(e));if(!e.options.lineWrapping){r.iter(u,s.line+t.text.length,function(e){var t=c(e);if(t>n.maxLineLength){n.maxLine=e;n.maxLineLength=t;n.maxLineChanged=!0;l=!1}});l&&(e.curOp.updateMaxLine=!0)}r.frontier=Math.min(r.frontier,s.line);yt(e,400);var p=t.text.length-(a.line-s.line)-1;t.full?xi(e):s.line!=a.line||1!=t.text.length||Dn(e.doc,t)?xi(e,s.line,a.line+1,p):Ni(e,s.line,"text");var d=Eo(e,"changes"),f=Eo(e,"change");if(f||d){var h={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};f&&po(e,"change",e,h);d&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function vr(e,t,i,r,n){r||(r=i);if(ys(r,i)<0){var o=r;r=i;i=o}"string"==typeof t&&(t=Ga(t));dr(e,{from:i,to:r,text:t,origin:n})}function xr(e,t){if(!fo(e,"scrollCursorIntoView")){var i=e.display,r=i.sizer.getBoundingClientRect(),n=null;t.top+r.top<0?n=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(n=!1);if(null!=n&&!fs){var o=bo("div","",null,"position: absolute; top: "+(t.top-i.viewOffset-Rt(e.display))+"px; height: "+(t.bottom-t.top+Pt(e)+i.barHeight)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o);o.scrollIntoView(n);e.display.lineSpace.removeChild(o)}}}function Nr(e,t,i,r){null==r&&(r=0);for(var n=0;5>n;n++){var o=!1,s=Qt(e,t),a=i&&i!=t?Qt(e,i):s,l=Lr(e,Math.min(s.left,a.left),Math.min(s.top,a.top)-r,Math.max(s.left,a.left),Math.max(s.bottom,a.bottom)+r),u=e.doc.scrollTop,p=e.doc.scrollLeft;if(null!=l.scrollTop){qi(e,l.scrollTop);Math.abs(e.doc.scrollTop-u)>1&&(o=!0)}if(null!=l.scrollLeft){zi(e,l.scrollLeft);Math.abs(e.doc.scrollLeft-p)>1&&(o=!0)}if(!o)break}return s}function Tr(e,t,i,r,n){var o=Lr(e,t,i,r,n);null!=o.scrollTop&&qi(e,o.scrollTop);null!=o.scrollLeft&&zi(e,o.scrollLeft)}function Lr(e,t,i,r,n){var o=e.display,s=ii(e.display);0>i&&(i=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=wt(e),u={};n-i>l&&(n=i+l);var p=e.doc.height+bt(o),c=s>i,d=n>p-s;if(a>i)u.scrollTop=c?0:i;else if(n>a+l){var f=Math.min(i,(d?p:n)-l);f!=a&&(u.scrollTop=f)}var h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,E=Dt(e)-(e.options.fixedGutter?o.gutters.offsetWidth:0),m=r-t>E;m&&(r=t+E);10>t?u.scrollLeft=0:h>t?u.scrollLeft=Math.max(0,t-(m?0:10)):r>E+h-3&&(u.scrollLeft=r+(m?0:10)-E);return u}function Ir(e,t,i){(null!=t||null!=i)&&Ar(e);null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t);null!=i&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+i)}function yr(e){Ar(e);var t=e.getCursor(),i=t,r=t;if(!e.options.lineWrapping){i=t.ch?Is(t.line,t.ch-1):t;r=Is(t.line,t.ch+1)}e.curOp.scrollToPos={from:i,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function Ar(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var i=Zt(e,t.from),r=Zt(e,t.to),n=Lr(e,Math.min(i.left,r.left),Math.min(i.top,r.top)-t.margin,Math.max(i.right,r.right),Math.max(i.bottom,r.bottom)+t.margin);e.scrollTo(n.scrollLeft,n.scrollTop)}}function Sr(e,t,i,r){var n,o=e.doc;null==i&&(i="add");"smart"==i&&(o.mode.indent?n=Ct(e,t):i="prev");var s=e.options.tabSize,a=Bn(o,t),l=ya(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,p=a.text.match(/^\s*/)[0];if(r||/\S/.test(a.text)){if("smart"==i){u=o.mode.indent(n,a.text.slice(p.length),a.text);if(u==Na||u>150){if(!r)return;i="prev"}}}else{u=0;i="not"}"prev"==i?u=t>o.first?ya(Bn(o,t-1).text,null,s):0:"add"==i?u=l+e.options.indentUnit:"subtract"==i?u=l-e.options.indentUnit:"number"==typeof i&&(u=l+i);u=Math.max(0,u);var c="",d=0;if(e.options.indentWithTabs)for(var f=Math.floor(u/s);f;--f){d+=s;c+=" "}u>d&&(c+=xo(u-d));if(c!=p)vr(o,c,Is(t,0),Is(t,p.length),"+input");else for(var f=0;f<o.sel.ranges.length;f++){var h=o.sel.ranges[f];if(h.head.line==t&&h.head.ch<p.length){var d=Is(t,p.length);lt(o,f,new Q(d,d));break}}a.stateAfter=null}function Cr(e,t,i,r){var n=t,o=t;"number"==typeof t?o=Bn(e,et(e,t)):n=Hn(t);if(null==n)return null;r(o,n)&&e.cm&&Ni(e.cm,n,i);return o}function Rr(e,t){for(var i=e.doc.sel.ranges,r=[],n=0;n<i.length;n++){for(var o=t(i[n]);r.length&&ys(o.from,No(r).to)<=0;){var s=r.pop();if(ys(s.from,o.from)<0){o.from=s.from;break}}r.push(o)}fi(e,function(){for(var t=r.length-1;t>=0;t--)vr(e.doc,"",r[t].from,r[t].to,"+delete");yr(e)})}function br(e,t,i,r,n){function o(){var t=a+i;if(t<e.first||t>=e.first+e.size)return c=!1;a=t;return p=Bn(e,t)}function s(e){var t=(n?Jo:es)(p,l,i,!0);if(null==t){if(e||!o())return c=!1;l=n?(0>i?zo:qo)(p):0>i?p.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=i,p=Bn(e,a),c=!0;if("char"==r)s();else if("column"==r)s(!0);else if("word"==r||"group"==r)for(var d=null,f="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),E=!0;!(0>i)||s(!E);E=!1){var m=p.text.charAt(l)||"\n",g=So(m,h)?"w":f&&"\n"==m?"n":!f||/\s/.test(m)?null:"p";!f||E||g||(g="s");if(d&&d!=g){if(0>i){i=1;s()}break}g&&(d=g);if(i>0&&!s(!E))break}var v=gt(e,Is(a,l),u,!0);c||(v.hitSide=!0);return v}function Or(e,t,i,r){var n,o=e.doc,s=t.left;if("page"==r){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);n=t.top+i*(a-(0>i?1.5:.5)*ii(e.display))}else"line"==r&&(n=i>0?t.bottom+3:t.top-3);for(;;){var l=ei(e,s,n);if(!l.outside)break;if(0>i?0>=n:n>=o.height){l.hitSide=!0;break}n+=5*i}return l}function Pr(t,i,r,n){e.defaults[t]=i;r&&(Vs[t]=n?function(e,t,i){i!=Fs&&r(e,t,i)}:r)}function Dr(e){for(var t,i,r,n,o=e.split(/-(?!$)/),e=o[o.length-1],s=0;s<o.length-1;s++){var a=o[s];if(/^(cmd|meta|m)$/i.test(a))n=!0;else if(/^a(lt)?$/i.test(a))t=!0;else if(/^(c|ctrl|control)$/i.test(a))i=!0;else{if(!/^s(hift)$/i.test(a))throw new Error("Unrecognized modifier name: "+a);r=!0}}t&&(e="Alt-"+e);i&&(e="Ctrl-"+e);n&&(e="Cmd-"+e);r&&(e="Shift-"+e);return e}function wr(e){return"string"==typeof e?$s[e]:e}function _r(e,t,i,r,n){if(r&&r.shared)return Mr(e,t,i,r,n);if(e.cm&&!e.cm.curOp)return hi(e.cm,_r)(e,t,i,r,n);var o=new ta(e,n),s=ys(t,i);r&&yo(r,o,!1);if(s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith){o.collapsed=!0;o.widgetNode=bo("span",[o.replacedWith],"CodeMirror-widget");r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true");r.insertLeft&&(o.widgetNode.insertLeft=!0)}if(o.collapsed){if(nn(e,t.line,t,i,o)||t.line!=i.line&&nn(e,i.line,t,i,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");Ls=!0}o.addToHistory&&$n(e,{from:t,to:i,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;e.iter(l,i.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&on(e)==u.display.maxLine&&(a=!0);o.collapsed&&l!=t.line&&Fn(e,0);Hr(e,new Ur(o,l==t.line?t.ch:null,l==i.line?i.ch:null));++l});o.collapsed&&e.iter(t.line,i.line+1,function(t){un(e,t)&&Fn(t,0)});o.clearOnEnter&&Ea(o,"beforeCursorEnter",function(){o.clear()});if(o.readOnly){Ts=!0;(e.history.done.length||e.history.undone.length)&&e.clearHistory()}if(o.collapsed){o.id=++ia;o.atomic=!0}if(u){a&&(u.curOp.updateMaxLine=!0);if(o.collapsed)xi(u,t.line,i.line+1);else if(o.className||o.title||o.startStyle||o.endStyle||o.css)for(var p=t.line;p<=i.line;p++)Ni(u,p,"text");o.atomic&&Et(u.doc);po(u,"markerAdded",u,o)}return o}function Mr(e,t,i,r,n){r=yo(r);r.shared=!1;var o=[_r(e,t,i,r,n)],s=o[0],a=r.widgetNode;kn(e,function(e){a&&(r.widgetNode=a.cloneNode(!0));o.push(_r(e,tt(e,t),tt(e,i),r,n));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=No(o)});return new ra(o,s)}function kr(e){return e.findMarks(Is(e.first,0),e.clipPos(Is(e.lastLine())),function(e){return e.parent})}function Gr(e,t){for(var i=0;i<t.length;i++){var r=t[i],n=r.find(),o=e.clipPos(n.from),s=e.clipPos(n.to);if(ys(o,s)){var a=_r(e,o,s,r.primary,r.primary.type);r.markers.push(a);a.parent=r}}}function Br(e){for(var t=0;t<e.length;t++){var i=e[t],r=[i.primary.doc];kn(i.primary.doc,function(e){r.push(e)});for(var n=0;n<i.markers.length;n++){var o=i.markers[n];if(-1==To(r,o.doc)){o.parent=null;i.markers.splice(n--,1)}}}}function Ur(e,t,i){this.marker=e;this.from=t;this.to=i}function Vr(e,t){if(e)for(var i=0;i<e.length;++i){var r=e[i];if(r.marker==t)return r}}function Fr(e,t){for(var i,r=0;r<e.length;++r)e[r]!=t&&(i||(i=[])).push(e[r]);return i}function Hr(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t];t.marker.attachLine(e)}function jr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);if(a||o.from==t&&"bookmark"==s.type&&(!i||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Ur(s,o.from,l?null:o.to))}}return r}function Wr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);if(a||o.from==t&&"bookmark"==s.type&&(!i||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Ur(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function qr(e,t){if(t.full)return null;var i=rt(e,t.from.line)&&Bn(e,t.from.line).markedSpans,r=rt(e,t.to.line)&&Bn(e,t.to.line).markedSpans;if(!i&&!r)return null;var n=t.from.ch,o=t.to.ch,s=0==ys(t.from,t.to),a=jr(i,n,s),l=Wr(r,o,s),u=1==t.text.length,p=No(t.text).length+(u?n:0);if(a)for(var c=0;c<a.length;++c){var d=a[c];if(null==d.to){var f=Vr(l,d.marker);f?u&&(d.to=null==f.to?null:f.to+p):d.to=n}}if(l)for(var c=0;c<l.length;++c){var d=l[c];null!=d.to&&(d.to+=p);if(null==d.from){var f=Vr(a,d.marker);if(!f){d.from=p;u&&(a||(a=[])).push(d)}}else{d.from+=p;u&&(a||(a=[])).push(d)}}a&&(a=zr(a));l&&l!=a&&(l=zr(l));var h=[a];if(!u){var E,m=t.text.length-2;if(m>0&&a)for(var c=0;c<a.length;++c)null==a[c].to&&(E||(E=[])).push(new Ur(a[c].marker,null,null));for(var c=0;m>c;++c)h.push(E);h.push(l)}return h}function zr(e){for(var t=0;t<e.length;++t){var i=e[t];null!=i.from&&i.from==i.to&&i.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function Xr(e,t){var i=io(e,t),r=qr(e,t);
if(!i)return r;if(!r)return i;for(var n=0;n<i.length;++n){var o=i[n],s=r[n];if(o&&s)e:for(var a=0;a<s.length;++a){for(var l=s[a],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else s&&(i[n]=s)}return i}function Yr(e,t,i){var r=null;e.iter(t.line,i.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var i=e.markedSpans[t].marker;!i.readOnly||r&&-1!=To(r,i)||(r||(r=[])).push(i)}});if(!r)return null;for(var n=[{from:t,to:i}],o=0;o<r.length;++o)for(var s=r[o],a=s.find(0),l=0;l<n.length;++l){var u=n[l];if(!(ys(u.to,a.from)<0||ys(u.from,a.to)>0)){var p=[l,1],c=ys(u.from,a.from),d=ys(u.to,a.to);(0>c||!s.inclusiveLeft&&!c)&&p.push({from:u.from,to:a.from});(d>0||!s.inclusiveRight&&!d)&&p.push({from:a.to,to:u.to});n.splice.apply(n,p);l+=p.length-1}}return n}function Kr(e){var t=e.markedSpans;if(t){for(var i=0;i<t.length;++i)t[i].marker.detachLine(e);e.markedSpans=null}}function $r(e,t){if(t){for(var i=0;i<t.length;++i)t[i].marker.attachLine(e);e.markedSpans=t}}function Qr(e){return e.inclusiveLeft?-1:0}function Zr(e){return e.inclusiveRight?1:0}function Jr(e,t){var i=e.lines.length-t.lines.length;if(0!=i)return i;var r=e.find(),n=t.find(),o=ys(r.from,n.from)||Qr(e)-Qr(t);if(o)return-o;var s=ys(r.to,n.to)||Zr(e)-Zr(t);return s?s:t.id-e.id}function en(e,t){var i,r=Ls&&e.markedSpans;if(r)for(var n,o=0;o<r.length;++o){n=r[o];n.marker.collapsed&&null==(t?n.from:n.to)&&(!i||Jr(i,n.marker)<0)&&(i=n.marker)}return i}function tn(e){return en(e,!0)}function rn(e){return en(e,!1)}function nn(e,t,i,r,n){var o=Bn(e,t),s=Ls&&o.markedSpans;if(s)for(var a=0;a<s.length;++a){var l=s[a];if(l.marker.collapsed){var u=l.marker.find(0),p=ys(u.from,i)||Qr(l.marker)-Qr(n),c=ys(u.to,r)||Zr(l.marker)-Zr(n);if(!(p>=0&&0>=c||0>=p&&c>=0)&&(0>=p&&(ys(u.to,i)>0||l.marker.inclusiveRight&&n.inclusiveLeft)||p>=0&&(ys(u.from,r)<0||l.marker.inclusiveLeft&&n.inclusiveRight)))return!0}}}function on(e){for(var t;t=tn(e);)e=t.find(-1,!0).line;return e}function sn(e){for(var t,i;t=rn(e);){e=t.find(1,!0).line;(i||(i=[])).push(e)}return i}function an(e,t){var i=Bn(e,t),r=on(i);return i==r?t:Hn(r)}function ln(e,t){if(t>e.lastLine())return t;var i,r=Bn(e,t);if(!un(e,r))return t;for(;i=rn(r);)r=i.find(1,!0).line;return Hn(r)+1}function un(e,t){var i=Ls&&t.markedSpans;if(i)for(var r,n=0;n<i.length;++n){r=i[n];if(r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&pn(e,t,r))return!0}}}function pn(e,t,i){if(null==i.to){var r=i.marker.find(1,!0);return pn(e,r.line,Vr(r.line.markedSpans,i.marker))}if(i.marker.inclusiveRight&&i.to==t.text.length)return!0;for(var n,o=0;o<t.markedSpans.length;++o){n=t.markedSpans[o];if(n.marker.collapsed&&!n.marker.widgetNode&&n.from==i.to&&(null==n.to||n.to!=i.from)&&(n.marker.inclusiveLeft||i.marker.inclusiveRight)&&pn(e,t,n))return!0}}function cn(e,t,i){Wn(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&Ir(e,null,i)}function dn(e){if(null!=e.height)return e.height;if(!Do(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.display.gutters.offsetWidth+"px;");e.noHScroll&&(t+="width: "+e.cm.display.wrapper.clientWidth+"px;");Po(e.cm.display.measure,bo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function fn(e,t,i,r){var n=new na(e,i,r);n.noHScroll&&(e.display.alignWidgets=!0);Cr(e.doc,t,"widget",function(t){var i=t.widgets||(t.widgets=[]);null==n.insertAt?i.push(n):i.splice(Math.min(i.length-1,Math.max(0,n.insertAt)),0,n);n.line=t;if(!un(e.doc,t)){var r=Wn(t)<e.doc.scrollTop;Fn(t,t.height+dn(n));r&&Ir(e,null,n.height);e.curOp.forceUpdate=!0}return!0});return n}function hn(e,t,i,r){e.text=t;e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null);null!=e.order&&(e.order=null);Kr(e);$r(e,i);var n=r?r(e):1;n!=e.height&&Fn(e,n)}function En(e){e.parent=null;Kr(e)}function mn(e,t){if(e)for(;;){var i=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!i)break;e=e.slice(0,i.index)+e.slice(i.index+i[0].length);var r=i[1]?"bgClass":"textClass";null==t[r]?t[r]=i[2]:new RegExp("(?:^|s)"+i[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+i[2])}return e}function gn(t,i){if(t.blankLine)return t.blankLine(i);if(t.innerMode){var r=e.innerMode(t,i);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function vn(t,i,r,n){for(var o=0;10>o;o++){n&&(n[0]=e.innerMode(t,r).mode);var s=t.token(i,r);if(i.pos>i.start)return s}throw new Error("Mode "+t.name+" failed to advance stream.")}function xn(e,t,i,r){function n(e){return{start:c.start,end:c.pos,string:c.current(),type:o||null,state:e?Xs(s.mode,p):p}}var o,s=e.doc,a=s.mode;t=tt(s,t);var l,u=Bn(s,t.line),p=Ct(e,t.line,i),c=new ea(u.text,e.options.tabSize);r&&(l=[]);for(;(r||c.pos<t.ch)&&!c.eol();){c.start=c.pos;o=vn(a,c,p);r&&l.push(n(!0))}return r?l:n()}function Nn(e,t,i,r,n,o,s){var a=i.flattenSpans;null==a&&(a=e.options.flattenSpans);var l,u=0,p=null,c=new ea(t,e.options.tabSize),d=e.options.addModeClass&&[null];""==t&&mn(gn(i,r),o);for(;!c.eol();){if(c.pos>e.options.maxHighlightLength){a=!1;s&&In(e,t,r,c.pos);c.pos=t.length;l=null}else l=mn(vn(i,c,r,d),o);if(d){var f=d[0].name;f&&(l="m-"+(l?f+" "+l:f))}if(!a||p!=l){for(;u<c.start;){u=Math.min(c.start,u+5e4);n(u,p)}p=l}c.start=c.pos}for(;u<c.pos;){var h=Math.min(c.pos,u+5e4);n(h,p);u=h}}function Tn(e,t,i,r){var n=[e.state.modeGen],o={};Nn(e,t.text,e.doc.mode,i,function(e,t){n.push(e,t)},o,r);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;Nn(e,t.text,a.mode,!0,function(e,t){for(var i=l;e>u;){var r=n[l];r>e&&n.splice(l,1,e,n[l+1],r);l+=2;u=Math.min(e,r)}if(t)if(a.opaque){n.splice(i,l-i,e,"cm-overlay "+t);l=i+2}else for(;l>i;i+=2){var o=n[i+1];n[i+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:n,classes:o.bgClass||o.textClass?o:null}}function Ln(e,t,i){if(!t.styles||t.styles[0]!=e.state.modeGen){var r=Tn(e,t,t.stateAfter=Ct(e,Hn(t)));t.styles=r.styles;r.classes?t.styleClasses=r.classes:t.styleClasses&&(t.styleClasses=null);i===e.doc.frontier&&e.doc.frontier++}return t.styles}function In(e,t,i,r){var n=e.doc.mode,o=new ea(t,e.options.tabSize);o.start=o.pos=r||0;""==t&&gn(n,i);for(;!o.eol()&&o.pos<=e.options.maxHighlightLength;){vn(n,o,i);o.start=o.pos}}function yn(e,t){if(!e||/^\s*$/.test(e))return null;var i=t.addModeClass?aa:sa;return i[e]||(i[e]=e.replace(/\S+/g,"cm-$&"))}function An(e,t){var i=bo("span",null,null,ss?"padding-right: .1px":null),r={pre:bo("pre",[i]),content:i,col:0,pos:0,cm:e};t.measure={};for(var n=0;n<=(t.rest?t.rest.length:0);n++){var o,s=n?t.rest[n-1]:t.line;r.pos=0;r.addToken=Cn;(ns||ss)&&e.getOption("lineWrapping")&&(r.addToken=Rn(r.addToken));Vo(e.display.measure)&&(o=qn(s))&&(r.addToken=bn(r.addToken,o));r.map=[];var a=t!=e.display.externalMeasured&&Hn(s);Pn(s,r,Ln(e,s,a));if(s.styleClasses){s.styleClasses.bgClass&&(r.bgClass=Mo(s.styleClasses.bgClass,r.bgClass||""));s.styleClasses.textClass&&(r.textClass=Mo(s.styleClasses.textClass,r.textClass||""))}0==r.map.length&&r.map.push(0,0,r.content.appendChild(Uo(e.display.measure)));if(0==n){t.measure.map=r.map;t.measure.cache={}}else{(t.measure.maps||(t.measure.maps=[])).push(r.map);(t.measure.caches||(t.measure.caches=[])).push({})}}ss&&/\bcm-tab\b/.test(r.content.lastChild.className)&&(r.content.className="cm-tab-wrap-hack");ga(e,"renderLine",e,t.line,r.pre);r.pre.className&&(r.textClass=Mo(r.pre.className,r.textClass||""));return r}function Sn(e){var t=bo("span","•","cm-invalidchar");t.title="\\u"+e.charCodeAt(0).toString(16);return t}function Cn(e,t,i,r,n,o,s){if(t){var a=e.cm.options.specialChars,l=!1;if(a.test(t))for(var u=document.createDocumentFragment(),p=0;;){a.lastIndex=p;var c=a.exec(t),d=c?c.index-p:t.length-p;if(d){var f=document.createTextNode(t.slice(p,p+d));u.appendChild(ns&&9>os?bo("span",[f]):f);e.map.push(e.pos,e.pos+d,f);e.col+=d;e.pos+=d}if(!c)break;p+=d+1;if(" "==c[0]){var h=e.cm.options.tabSize,E=h-e.col%h,f=u.appendChild(bo("span",xo(E),"cm-tab"));e.col+=E}else{var f=e.cm.options.specialCharPlaceholder(c[0]);u.appendChild(ns&&9>os?bo("span",[f]):f);e.col+=1}e.map.push(e.pos,e.pos+1,f);e.pos++}else{e.col+=t.length;var u=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,u);ns&&9>os&&(l=!0);e.pos+=t.length}if(i||r||n||l||s){var m=i||"";r&&(m+=r);n&&(m+=n);var g=bo("span",[u],m,s);o&&(g.title=o);return e.content.appendChild(g)}e.content.appendChild(u)}}function Rn(e){function t(e){for(var t=" ",i=0;i<e.length-2;++i)t+=i%2?" ":" ";t+=" ";return t}return function(i,r,n,o,s,a){e(i,r.replace(/ {3,}/g,t),n,o,s,a)}}function bn(e,t){return function(i,r,n,o,s,a){n=n?n+" cm-force-border":"cm-force-border";for(var l=i.pos,u=l+r.length;;){for(var p=0;p<t.length;p++){var c=t[p];if(c.to>l&&c.from<=l)break}if(c.to>=u)return e(i,r,n,o,s,a);e(i,r.slice(0,c.to-l),n,o,null,a);o=null;r=r.slice(c.to-l);l=c.to}}}function On(e,t,i,r){var n=!r&&i.widgetNode;if(n){e.map.push(e.pos,e.pos+t,n);e.content.appendChild(n)}e.pos+=t}function Pn(e,t,i){var r=e.markedSpans,n=e.text,o=0;if(r)for(var s,a,l,u,p,c,d,f=n.length,h=0,E=1,m="",g=0;;){if(g==h){l=u=p=c=a="";d=null;g=1/0;for(var v=[],x=0;x<r.length;++x){var N=r[x],T=N.marker;if(N.from<=h&&(null==N.to||N.to>h)){if(null!=N.to&&g>N.to){g=N.to;u=""}T.className&&(l+=" "+T.className);T.css&&(a=T.css);T.startStyle&&N.from==h&&(p+=" "+T.startStyle);T.endStyle&&N.to==g&&(u+=" "+T.endStyle);T.title&&!c&&(c=T.title);T.collapsed&&(!d||Jr(d.marker,T)<0)&&(d=N)}else N.from>h&&g>N.from&&(g=N.from);"bookmark"==T.type&&N.from==h&&T.widgetNode&&v.push(T)}if(d&&(d.from||0)==h){On(t,(null==d.to?f+1:d.to)-h,d.marker,null==d.from);if(null==d.to)return}if(!d&&v.length)for(var x=0;x<v.length;++x)On(t,0,v[x])}if(h>=f)break;for(var L=Math.min(f,g);;){if(m){var I=h+m.length;if(!d){var y=I>L?m.slice(0,L-h):m;t.addToken(t,y,s?s+l:l,p,h+y.length==g?u:"",c,a)}if(I>=L){m=m.slice(L-h);h=L;break}h=I;p=""}m=n.slice(o,o=i[E++]);s=yn(i[E++],t.cm.options)}}else for(var E=1;E<i.length;E+=2)t.addToken(t,n.slice(o,o=i[E]),yn(i[E+1],t.cm.options))}function Dn(e,t){return 0==t.from.ch&&0==t.to.ch&&""==No(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function wn(e,t,i,r){function n(e){return i?i[e]:null}function o(e,i,n){hn(e,i,n,r);po(e,"change",e,t)}function s(e,t){for(var i=e,o=[];t>i;++i)o.push(new oa(u[i],n(i),r));return o}var a=t.from,l=t.to,u=t.text,p=Bn(e,a.line),c=Bn(e,l.line),d=No(u),f=n(u.length-1),h=l.line-a.line;if(t.full){e.insert(0,s(0,u.length));e.remove(u.length,e.size-u.length)}else if(Dn(e,t)){var E=s(0,u.length-1);o(c,c.text,f);h&&e.remove(a.line,h);E.length&&e.insert(a.line,E)}else if(p==c)if(1==u.length)o(p,p.text.slice(0,a.ch)+d+p.text.slice(l.ch),f);else{var E=s(1,u.length-1);E.push(new oa(d+p.text.slice(l.ch),f,r));o(p,p.text.slice(0,a.ch)+u[0],n(0));e.insert(a.line+1,E)}else if(1==u.length){o(p,p.text.slice(0,a.ch)+u[0]+c.text.slice(l.ch),n(0));e.remove(a.line+1,h)}else{o(p,p.text.slice(0,a.ch)+u[0],n(0));o(c,d+c.text.slice(l.ch),f);var E=s(1,u.length-1);h>1&&e.remove(a.line+1,h-1);e.insert(a.line+1,E)}po(e,"change",e,t)}function _n(e){this.lines=e;this.parent=null;for(var t=0,i=0;t<e.length;++t){e[t].parent=this;i+=e[t].height}this.height=i}function Mn(e){this.children=e;for(var t=0,i=0,r=0;r<e.length;++r){var n=e[r];t+=n.chunkSize();i+=n.height;n.parent=this}this.size=t;this.height=i;this.parent=null}function kn(e,t,i){function r(e,n,o){if(e.linked)for(var s=0;s<e.linked.length;++s){var a=e.linked[s];if(a.doc!=n){var l=o&&a.sharedHist;if(!i||l){t(a.doc,l);r(a.doc,e,l)}}}}r(e,null,!0)}function Gn(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t;t.cm=e;s(e);i(e);e.options.lineWrapping||d(e);e.options.mode=t.modeOption;xi(e)}function Bn(e,t){t-=e.first;if(0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var i=e;!i.lines;)for(var r=0;;++r){var n=i.children[r],o=n.chunkSize();if(o>t){i=n;break}t-=o}return i.lines[t]}function Un(e,t,i){var r=[],n=t.line;e.iter(t.line,i.line+1,function(e){var o=e.text;n==i.line&&(o=o.slice(0,i.ch));n==t.line&&(o=o.slice(t.ch));r.push(o);++n});return r}function Vn(e,t,i){var r=[];e.iter(t,i,function(e){r.push(e.text)});return r}function Fn(e,t){var i=t-e.height;if(i)for(var r=e;r;r=r.parent)r.height+=i}function Hn(e){if(null==e.parent)return null;for(var t=e.parent,i=To(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var n=0;r.children[n]!=t;++n)i+=r.children[n].chunkSize();return i+t.first}function jn(e,t){var i=e.first;e:do{for(var r=0;r<e.children.length;++r){var n=e.children[r],o=n.height;if(o>t){e=n;continue e}t-=o;i+=n.chunkSize()}return i}while(!e.lines);for(var r=0;r<e.lines.length;++r){var s=e.lines[r],a=s.height;if(a>t)break;t-=a}return i+r}function Wn(e){e=on(e);for(var t=0,i=e.parent,r=0;r<i.lines.length;++r){var n=i.lines[r];if(n==e)break;t+=n.height}for(var o=i.parent;o;i=o,o=i.parent)for(var r=0;r<o.children.length;++r){var s=o.children[r];if(s==i)break;t+=s.height}return t}function qn(e){var t=e.order;null==t&&(t=e.order=ja(e.text));return t}function zn(e){this.done=[];this.undone=[];this.undoDepth=1/0;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=e||1}function Xn(e,t){var i={from:X(t.from),to:Bs(t),text:Un(e,t.from,t.to)};eo(e,i,t.from.line,t.to.line+1);kn(e,function(e){eo(e,i,t.from.line,t.to.line+1)},!0);return i}function Yn(e){for(;e.length;){var t=No(e);if(!t.ranges)break;e.pop()}}function Kn(e,t){if(t){Yn(e.done);return No(e.done)}if(e.done.length&&!No(e.done).ranges)return No(e.done);if(e.done.length>1&&!e.done[e.done.length-2].ranges){e.done.pop();return No(e.done)}}function $n(e,t,i,r){var n=e.history;n.undone.length=0;var o,s=+new Date;if((n.lastOp==r||n.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&n.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=Kn(n,n.lastOp==r))){var a=No(o.changes);0==ys(t.from,t.to)&&0==ys(t.from,a.to)?a.to=Bs(t):o.changes.push(Xn(e,t))}else{var l=No(n.done);l&&l.ranges||Jn(e.sel,n.done);o={changes:[Xn(e,t)],generation:n.generation};n.done.push(o);for(;n.done.length>n.undoDepth;){n.done.shift();n.done[0].ranges||n.done.shift()}}n.done.push(i);n.generation=++n.maxGeneration;n.lastModTime=n.lastSelTime=s;n.lastOp=n.lastSelOp=r;n.lastOrigin=n.lastSelOrigin=t.origin;a||ga(e,"historyAdded")}function Qn(e,t,i,r){var n=t.charAt(0);return"*"==n||"+"==n&&i.ranges.length==r.ranges.length&&i.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Zn(e,t,i,r){var n=e.history,o=r&&r.origin;i==n.lastSelOp||o&&n.lastSelOrigin==o&&(n.lastModTime==n.lastSelTime&&n.lastOrigin==o||Qn(e,o,No(n.done),t))?n.done[n.done.length-1]=t:Jn(t,n.done);n.lastSelTime=+new Date;n.lastSelOrigin=o;n.lastSelOp=i;r&&r.clearRedo!==!1&&Yn(n.undone)}function Jn(e,t){var i=No(t);i&&i.ranges&&i.equals(e)||t.push(e)}function eo(e,t,i,r){var n=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,i),Math.min(e.first+e.size,r),function(i){i.markedSpans&&((n||(n=t["spans_"+e.id]={}))[o]=i.markedSpans);++o})}function to(e){if(!e)return null;for(var t,i=0;i<e.length;++i)e[i].marker.explicitlyCleared?t||(t=e.slice(0,i)):t&&t.push(e[i]);return t?t.length?t:null:e}function io(e,t){var i=t["spans_"+e.id];if(!i)return null;for(var r=0,n=[];r<t.text.length;++r)n.push(to(i[r]));return n}function ro(e,t,i){for(var r=0,n=[];r<e.length;++r){var o=e[r];if(o.ranges)n.push(i?$.prototype.deepCopy.call(o):o);else{var s=o.changes,a=[];n.push({changes:a});for(var l=0;l<s.length;++l){var u,p=s[l];a.push({from:p.from,to:p.to,text:p.text});if(t)for(var c in p)if((u=c.match(/^spans_(\d+)$/))&&To(t,Number(u[1]))>-1){No(a)[c]=p[c];delete p[c]}}}}return n}function no(e,t,i,r){if(i<e.line)e.line+=r;else if(t<e.line){e.line=t;e.ch=0}}function oo(e,t,i,r){for(var n=0;n<e.length;++n){var o=e[n],s=!0;if(o.ranges){if(!o.copied){o=e[n]=o.deepCopy();o.copied=!0}for(var a=0;a<o.ranges.length;a++){no(o.ranges[a].anchor,t,i,r);no(o.ranges[a].head,t,i,r)}}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(i<l.from.line){l.from=Is(l.from.line+r,l.from.ch);l.to=Is(l.to.line+r,l.to.ch)}else if(t<=l.to.line){s=!1;break}}if(!s){e.splice(0,n+1);n=0}}}}function so(e,t){var i=t.from.line,r=t.to.line,n=t.text.length-(r-i)-1;oo(e.done,i,r,n);oo(e.undone,i,r,n)}function ao(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function lo(e){return e.target||e.srcElement}function uo(e){var t=e.which;null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2));ms&&e.ctrlKey&&1==t&&(t=3);return t}function po(e,t){function i(e){return function(){e.apply(null,o)}}var r=e._handlers&&e._handlers[t];if(r){var n,o=Array.prototype.slice.call(arguments,2);if(bs)n=bs.delayedCallbacks;else if(va)n=va;else{n=va=[];setTimeout(co,0)}for(var s=0;s<r.length;++s)n.push(i(r[s]))}}function co(){var e=va;va=null;for(var t=0;t<e.length;++t)e[t]()}function fo(e,t,i){"string"==typeof t&&(t={type:t,preventDefault:function(){this.defaultPrevented=!0}});ga(e,i||t.type,e,t);return ao(t)||t.codemirrorIgnore}function ho(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var i=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==To(i,t[r])&&i.push(t[r])}function Eo(e,t){var i=e._handlers&&e._handlers[t];return i&&i.length>0}function mo(e){e.prototype.on=function(e,t){Ea(this,e,t)};e.prototype.off=function(e,t){ma(this,e,t)}}function go(){this.id=null}function vo(e,t,i){for(var r=0,n=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var s=o-r;if(o==e.length||n+s>=t)return r+Math.min(s,t-n);n+=o-r;n+=i-n%i;r=o+1;if(n>=t)return r}}function xo(e){for(;Aa.length<=e;)Aa.push(No(Aa)+" ");return Aa[e]}function No(e){return e[e.length-1]}function To(e,t){for(var i=0;i<e.length;++i)if(e[i]==t)return i;return-1}function Lo(e,t){for(var i=[],r=0;r<e.length;r++)i[r]=t(e[r],r);return i}function Io(e,t){var i;if(Object.create)i=Object.create(e);else{var r=function(){};r.prototype=e;i=new r}t&&yo(t,i);return i}function yo(e,t,i){t||(t={});for(var r in e)!e.hasOwnProperty(r)||i===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function Ao(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function So(e,t){return t?t.source.indexOf("\\w")>-1&&ba(e)?!0:t.test(e):ba(e)}function Co(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function Ro(e){return e.charCodeAt(0)>=768&&Oa.test(e)}function bo(e,t,i,r){var n=document.createElement(e);i&&(n.className=i);r&&(n.style.cssText=r);if("string"==typeof t)n.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)n.appendChild(t[o]);return n}function Oo(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Po(e,t){return Oo(e).appendChild(t)}function Do(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function wo(){return document.activeElement}function _o(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function Mo(e,t){for(var i=e.split(" "),r=0;r<i.length;r++)i[r]&&!_o(i[r]).test(t)&&(t+=" "+i[r]);return t}function ko(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),i=0;i<t.length;i++){var r=t[i].CodeMirror;r&&e(r)}}function Go(){if(!Ma){Bo();Ma=!0}}function Bo(){var e;Ea(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null;ko(_i)},100))});Ea(window,"blur",function(){ko(nr)})}function Uo(e){if(null==Pa){var t=bo("span","");Po(e,bo("span",[t,document.createTextNode("x")]));0!=e.firstChild.offsetHeight&&(Pa=t.offsetWidth<=1&&t.offsetHeight>2&&!(ns&&8>os))}return Pa?bo("span",""):bo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Vo(e){if(null!=Da)return Da;var t=Po(e,document.createTextNode("AخA")),i=Ca(t,0,1).getBoundingClientRect();if(!i||i.left==i.right)return!1;var r=Ca(t,1,2).getBoundingClientRect();return Da=r.right-i.right<3}function Fo(e){if(null!=Va)return Va;var t=Po(e,bo("span","x")),i=t.getBoundingClientRect(),r=Ca(t,0,1).getBoundingClientRect();return Va=Math.abs(i.left-r.left)>1}function Ho(e,t,i,r){if(!e)return r(t,i,"ltr");for(var n=!1,o=0;o<e.length;++o){var s=e[o];if(s.from<i&&s.to>t||t==i&&s.to==t){r(Math.max(s.from,t),Math.min(s.to,i),1==s.level?"rtl":"ltr");n=!0}}n||r(t,i,"ltr")}function jo(e){return e.level%2?e.to:e.from}function Wo(e){return e.level%2?e.from:e.to}function qo(e){var t=qn(e);return t?jo(t[0]):0}function zo(e){var t=qn(e);return t?Wo(No(t)):e.text.length}function Xo(e,t){var i=Bn(e.doc,t),r=on(i);r!=i&&(t=Hn(r));var n=qn(r),o=n?n[0].level%2?zo(r):qo(r):0;return Is(t,o)}function Yo(e,t){for(var i,r=Bn(e.doc,t);i=rn(r);){r=i.find(1,!0).line;t=null}var n=qn(r),o=n?n[0].level%2?qo(r):zo(r):r.text.length;return Is(null==t?Hn(r):t,o)}function Ko(e,t){var i=Xo(e,t.line),r=Bn(e.doc,i.line),n=qn(r);if(!n||0==n[0].level){var o=Math.max(0,r.text.search(/\S/)),s=t.line==i.line&&t.ch<=o&&t.ch;return Is(i.line,s?0:o)}return i}function $o(e,t,i){var r=e[0].level;return t==r?!0:i==r?!1:i>t}function Qo(e,t){Ha=null;for(var i,r=0;r<e.length;++r){var n=e[r];if(n.from<t&&n.to>t)return r;if(n.from==t||n.to==t){if(null!=i){if($o(e,n.level,e[i].level)){n.from!=n.to&&(Ha=i);return r}n.from!=n.to&&(Ha=r);return i}i=r}}return i}function Zo(e,t,i,r){if(!r)return t+i;do t+=i;while(t>0&&Ro(e.text.charAt(t)));return t}function Jo(e,t,i,r){var n=qn(e);if(!n)return es(e,t,i,r);for(var o=Qo(n,t),s=n[o],a=Zo(e,t,s.level%2?-i:i,r);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to){if(Qo(n,a)==o)return a;s=n[o+=i];return i>0==s.level%2?s.to:s.from}s=n[o+=i];if(!s)return null;a=i>0==s.level%2?Zo(e,s.to,-1,r):Zo(e,s.from,1,r)}}function es(e,t,i,r){var n=t+i;if(r)for(;n>0&&Ro(e.text.charAt(n));)n+=i;return 0>n||n>e.text.length?null:n}var ts=/gecko\/\d/i.test(navigator.userAgent),is=/MSIE \d/.test(navigator.userAgent),rs=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),ns=is||rs,os=ns&&(is?document.documentMode||6:rs[1]),ss=/WebKit\//.test(navigator.userAgent),as=ss&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ls=/Chrome\//.test(navigator.userAgent),us=/Opera\//.test(navigator.userAgent),ps=/Apple Computer/.test(navigator.vendor),cs=/KHTML\//.test(navigator.userAgent),ds=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),fs=/PhantomJS/.test(navigator.userAgent),hs=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),Es=hs||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),ms=hs||/Mac/.test(navigator.platform),gs=/win/i.test(navigator.platform),vs=us&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);vs&&(vs=Number(vs[1]));if(vs&&vs>=15){us=!1;ss=!0}var xs=ms&&(as||us&&(null==vs||12.11>vs)),Ns=ts||ns&&os>=9,Ts=!1,Ls=!1;E.prototype=yo({update:function(e){var t=e.scrollWidth>e.clientWidth+1,i=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(i){this.vert.style.display="block";this.vert.style.bottom=t?r+"px":"0";var n=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+n)+"px"}else{this.vert.style.display="";this.vert.firstChild.style.height="0"}if(t){this.horiz.style.display="block";this.horiz.style.right=i?r+"px":"0";this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(i?r:0);this.horiz.firstChild.style.width=e.scrollWidth-e.clientWidth+o+"px"}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0"}if(!this.checkedOverlay&&e.clientHeight>0){0==r&&this.overlayHack();this.checkedOverlay=!0}return{right:i?r:0,bottom:t?r:0}},setScrollLeft:function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e)},setScrollTop:function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e)},overlayHack:function(){var e=ms&&!ds?"12px":"18px";this.horiz.style.minHeight=this.vert.style.minWidth=e;var t=this,i=function(e){lo(e)!=t.vert&&lo(e)!=t.horiz&&hi(t.cm,Gi)(e)};Ea(this.vert,"mousedown",i);Ea(this.horiz,"mousedown",i)},clear:function(){var e=this.horiz.parentNode;e.removeChild(this.horiz);e.removeChild(this.vert)}},E.prototype);m.prototype=yo({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},m.prototype);e.scrollbarModel={"native":E,"null":m};var Is=e.Pos=function(e,t){if(!(this instanceof Is))return new Is(e,t);this.line=e;this.ch=t},ys=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};$.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var i=this.ranges[t],r=e.ranges[t];if(0!=ys(i.anchor,r.anchor)||0!=ys(i.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new Q(X(this.ranges[t].anchor),X(this.ranges[t].head));return new $(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var i=0;i<this.ranges.length;i++){var r=this.ranges[i];if(ys(t,r.from())>=0&&ys(e,r.to())<=0)return i}return-1}};Q.prototype={from:function(){return K(this.anchor,this.head)},to:function(){return Y(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var As,Ss,Cs,Rs={left:0,right:0,top:0,bottom:0},bs=null,Os=0,Ps=null,Ds=0,ws=0,_s=null;ns?_s=-.53:ts?_s=15:ls?_s=-.7:ps&&(_s=-1/3);var Ms=function(e){var t=e.wheelDeltaX,i=e.wheelDeltaY;null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail);null==i&&e.detail&&e.axis==e.VERTICAL_AXIS?i=e.detail:null==i&&(i=e.wheelDelta);return{x:t,y:i}};e.wheelEventPixels=function(e){var t=Ms(e);t.x*=_s;t.y*=_s;return t};var ks=new go,Gs=null,Bs=e.changeEnd=function(e){return e.text?Is(e.from.line+e.text.length-1,No(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus();Oi(this);Ci(this)},setOption:function(e,t){var i=this.options,r=i[e];if(i[e]!=t||"mode"==e){i[e]=t;Vs.hasOwnProperty(e)&&hi(this,Vs[e])(this,t,r)}},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](wr(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,i=0;i<t.length;++i)if(t[i]==e||t[i].name==e){t.splice(i,1);return!0}},addOverlay:Ei(function(t,i){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:i&&i.opaque});this.state.modeGen++;xi(this)}),removeOverlay:Ei(function(e){for(var t=this.state.overlays,i=0;i<t.length;++i){var r=t[i].modeSpec;if(r==e||"string"==typeof e&&r.name==e){t.splice(i,1);this.state.modeGen++;xi(this);return}}}),indentLine:Ei(function(e,t,i){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract");rt(this.doc,e)&&Sr(this,e,t,i)}),indentSelection:Ei(function(e){for(var t=this.doc.sel.ranges,i=-1,r=0;r<t.length;r++){var n=t[r];if(n.empty()){if(n.head.line>i){Sr(this,n.head.line,e,!0);i=n.head.line;r==this.doc.sel.primIndex&&yr(this)}}else{var o=n.from(),s=n.to(),a=Math.max(i,o.line);i=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var l=a;i>l;++l)Sr(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[r].from().ch>0&<(this.doc,r,new Q(o,u[r].to()),Ta)}}}),getTokenAt:function(e,t){return xn(this,e,t)},getLineTokens:function(e,t){return xn(this,Is(e),t,!0)},getTokenTypeAt:function(e){e=tt(this.doc,e);var t,i=Ln(this,Bn(this.doc,e.line)),r=0,n=(i.length-1)/2,o=e.ch;if(0==o)t=i[2];else for(;;){var s=r+n>>1;if((s?i[2*s-1]:0)>=o)n=s;else{if(!(i[2*s+1]<o)){t=i[2*s+2];break}r=s+1}}var a=t?t.indexOf("cm-overlay "):-1;return 0>a?t:0==a?null:t.slice(0,a-1)},getModeAt:function(t){var i=this.doc.mode;return i.innerMode?e.innerMode(i,this.getTokenAt(t).state).mode:i},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var i=[];if(!zs.hasOwnProperty(t))return zs;var r=zs[t],n=this.getModeAt(e);if("string"==typeof n[t])r[n[t]]&&i.push(r[n[t]]);else if(n[t])for(var o=0;o<n[t].length;o++){var s=r[n[t][o]];s&&i.push(s)}else n.helperType&&r[n.helperType]?i.push(r[n.helperType]):r[n.name]&&i.push(r[n.name]);for(var o=0;o<r._global.length;o++){var a=r._global[o];a.pred(n,this)&&-1==To(i,a.val)&&i.push(a.val)}return i},getStateAfter:function(e,t){var i=this.doc;e=et(i,null==e?i.first+i.size-1:e);return Ct(this,e+1,t)},cursorCoords:function(e,t){var i,r=this.doc.sel.primary();i=null==e?r.head:"object"==typeof e?tt(this.doc,e):e?r.from():r.to();return Qt(this,i,t||"page")},charCoords:function(e,t){return $t(this,tt(this.doc,e),t||"page")},coordsChar:function(e,t){e=Kt(this,e,t||"page");return ei(this,e.left,e.top)},lineAtHeight:function(e,t){e=Kt(this,{top:e,left:0},t||"page").top;return jn(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var i=!1,r=this.doc.first+this.doc.size-1;if(e<this.doc.first)e=this.doc.first;else if(e>r){e=r;i=!0}var n=Bn(this.doc,e);return Yt(this,n,{top:0,left:0},t||"page").top+(i?this.doc.height-Wn(n):0)},defaultTextHeight:function(){return ii(this.display)},defaultCharWidth:function(){return ri(this.display)},setGutterMarker:Ei(function(e,t,i){return Cr(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});r[t]=i;!i&&Co(r)&&(e.gutterMarkers=null);return!0})}),clearGutter:Ei(function(e){var t=this,i=t.doc,r=i.first;i.iter(function(i){if(i.gutterMarkers&&i.gutterMarkers[e]){i.gutterMarkers[e]=null;Ni(t,r,"gutter");Co(i.gutterMarkers)&&(i.gutterMarkers=null)}++r})}),addLineWidget:Ei(function(e,t,i){return fn(this,e,t,i)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!rt(this.doc,e))return null;var t=e;e=Bn(this.doc,e);if(!e)return null}else{var t=Hn(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,i,r,n){var o=this.display;e=Qt(this,tt(this.doc,e));var s=e.bottom,a=e.left;t.style.position="absolute";t.setAttribute("cm-ignore-events","true");o.sizer.appendChild(t);if("over"==r)s=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?s=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(s=e.bottom);a+t.offsetWidth>u&&(a=u-t.offsetWidth)}t.style.top=s+"px";t.style.left=t.style.right="";if("right"==n){a=o.sizer.clientWidth-t.offsetWidth;t.style.right="0px"}else{"left"==n?a=0:"middle"==n&&(a=(o.sizer.clientWidth-t.offsetWidth)/2);t.style.left=a+"px"}i&&Tr(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:Ei(Ji),triggerOnKeyPress:Ei(ir),triggerOnKeyUp:tr,execCommand:function(e){return Ks.hasOwnProperty(e)?Ks[e](this):void 0},findPosH:function(e,t,i,r){var n=1;if(0>t){n=-1;t=-t}for(var o=0,s=tt(this.doc,e);t>o;++o){s=br(this.doc,s,n,i,r);if(s.hitSide)break}return s},moveH:Ei(function(e,t){var i=this;i.extendSelectionsBy(function(r){return i.display.shift||i.doc.extend||r.empty()?br(i.doc,r.head,e,t,i.options.rtlMoveVisually):0>e?r.from():r.to()},Ia)}),deleteH:Ei(function(e,t){var i=this.doc.sel,r=this.doc;i.somethingSelected()?r.replaceSelection("",null,"+delete"):Rr(this,function(i){var n=br(r,i.head,e,t,!1);return 0>e?{from:n,to:i.head}:{from:i.head,to:n}})}),findPosV:function(e,t,i,r){var n=1,o=r;if(0>t){n=-1;t=-t}for(var s=0,a=tt(this.doc,e);t>s;++s){var l=Qt(this,a,"div");null==o?o=l.left:l.left=o;a=Or(this,l,n,i);if(a.hitSide)break}return a},moveV:Ei(function(e,t){var i=this,r=this.doc,n=[],o=!i.display.shift&&!r.extend&&r.sel.somethingSelected();r.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=Qt(i,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn);n.push(a.left);var l=Or(i,a,e,t);
"page"==t&&s==r.sel.primary()&&Ir(i,null,$t(i,l,"div").top-a.top);return l},Ia);if(n.length)for(var s=0;s<r.sel.ranges.length;s++)r.sel.ranges[s].goalColumn=n[s]}),findWordAt:function(e){var t=this.doc,i=Bn(t,e.line).text,r=e.ch,n=e.ch;if(i){var o=this.getHelper(e,"wordChars");(e.xRel<0||n==i.length)&&r?--r:++n;for(var s=i.charAt(r),a=So(s,o)?function(e){return So(e,o)}:/\s/.test(s)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!So(e)};r>0&&a(i.charAt(r-1));)--r;for(;n<i.length&&a(i.charAt(n));)++n}return new Q(Is(e.line,r),Is(e.line,n))},toggleOverwrite:function(e){if(null==e||e!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?_a(this.display.cursorDiv,"CodeMirror-overwrite"):wa(this.display.cursorDiv,"CodeMirror-overwrite");ga(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return wo()==this.display.input},scrollTo:Ei(function(e,t){(null!=e||null!=t)&&Ar(this);null!=e&&(this.curOp.scrollLeft=e);null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-Pt(this)-this.display.barHeight,width:e.scrollWidth-Pt(this)-this.display.barWidth,clientHeight:wt(this),clientWidth:Dt(this)}},scrollIntoView:Ei(function(e,t){if(null==e){e={from:this.doc.sel.primary().head,to:null};null==t&&(t=this.options.cursorScrollMargin)}else"number"==typeof e?e={from:Is(e,0),to:null}:null==e.from&&(e={from:e,to:null});e.to||(e.to=e.from);e.margin=t||0;if(null!=e.from.line){Ar(this);this.curOp.scrollToPos=e}else{var i=Lr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(i.scrollLeft,i.scrollTop)}}),setSize:Ei(function(e,t){function i(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(r.display.wrapper.style.width=i(e));null!=t&&(r.display.wrapper.style.height=i(t));r.options.lineWrapping&&Wt(this);var n=r.display.viewFrom;r.doc.iter(n,r.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){Ni(r,n,"widget");break}++n});r.curOp.forceUpdate=!0;ga(r,"refresh",this)}),operation:function(e){return fi(this,e)},refresh:Ei(function(){var e=this.display.cachedTextHeight;xi(this);this.curOp.forceUpdate=!0;qt(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);p(this);(null==e||Math.abs(e-ii(this.display))>.5)&&s(this);ga(this,"refresh",this)}),swapDoc:Ei(function(e){var t=this.doc;t.cm=null;Gn(this,e);qt(this);bi(this);this.scrollTo(e.scrollLeft,e.scrollTop);this.curOp.forceScroll=!0;po(this,"swapDoc",this,t);return t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};mo(e);var Us=e.defaults={},Vs=e.optionHandlers={},Fs=e.Init={toString:function(){return"CodeMirror.Init"}};Pr("value","",function(e,t){e.setValue(t)},!0);Pr("mode",null,function(e,t){e.doc.modeOption=t;i(e)},!0);Pr("indentUnit",2,i,!0);Pr("indentWithTabs",!1);Pr("smartIndent",!0);Pr("tabSize",4,function(e){r(e);qt(e);xi(e)},!0);Pr("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g");e.refresh()},!0);Pr("specialCharPlaceholder",Sn,function(e){e.refresh()},!0);Pr("electricChars",!0);Pr("rtlMoveVisually",!gs);Pr("wholeLineUpdateBefore",!0);Pr("theme","default",function(e){a(e);l(e)},!0);Pr("keyMap","default",function(t,i,r){var n=wr(i),o=r!=e.Init&&wr(r);o&&o.detach&&o.detach(t,n);n.attach&&n.attach(t,o||null)});Pr("extraKeys",null);Pr("lineWrapping",!1,n,!0);Pr("gutters",[],function(e){f(e.options);l(e)},!0);Pr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?y(e.display)+"px":"0";e.refresh()},!0);Pr("coverGutterNextToScrollbar",!1,function(e){v(e)},!0);Pr("scrollbarStyle","native",function(e){g(e);v(e);e.display.scrollbars.setScrollTop(e.doc.scrollTop);e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0);Pr("lineNumbers",!1,function(e){f(e.options);l(e)},!0);Pr("firstLineNumber",1,l,!0);Pr("lineNumberFormatter",function(e){return e},l,!0);Pr("showCursorWhenSelecting",!1,Nt,!0);Pr("resetSelectionOnContextMenu",!0);Pr("readOnly",!1,function(e,t){if("nocursor"==t){nr(e);e.display.input.blur();e.display.disabled=!0}else{e.display.disabled=!1;t||bi(e)}});Pr("disableInput",!1,function(e,t){t||bi(e)},!0);Pr("dragDrop",!0);Pr("cursorBlinkRate",530);Pr("cursorScrollMargin",0);Pr("cursorHeight",1,Nt,!0);Pr("singleCursorHeightPerLine",!0,Nt,!0);Pr("workTime",100);Pr("workDelay",100);Pr("flattenSpans",!0,r,!0);Pr("addModeClass",!1,r,!0);Pr("pollInterval",100);Pr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t});Pr("historyEventDelay",1250);Pr("viewportMargin",10,function(e){e.refresh()},!0);Pr("maxHighlightLength",1e4,r,!0);Pr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)});Pr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""});Pr("autofocus",null);var Hs=e.modes={},js=e.mimeModes={};e.defineMode=function(t,i){e.defaults.mode||"null"==t||(e.defaults.mode=t);arguments.length>2&&(i.dependencies=Array.prototype.slice.call(arguments,2));Hs[t]=i};e.defineMIME=function(e,t){js[e]=t};e.resolveMode=function(t){if("string"==typeof t&&js.hasOwnProperty(t))t=js[t];else if(t&&"string"==typeof t.name&&js.hasOwnProperty(t.name)){var i=js[t.name];"string"==typeof i&&(i={name:i});t=Io(i,t);t.name=i.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}};e.getMode=function(t,i){var i=e.resolveMode(i),r=Hs[i.name];if(!r)return e.getMode(t,"text/plain");var n=r(t,i);if(Ws.hasOwnProperty(i.name)){var o=Ws[i.name];for(var s in o)if(o.hasOwnProperty(s)){n.hasOwnProperty(s)&&(n["_"+s]=n[s]);n[s]=o[s]}}n.name=i.name;i.helperType&&(n.helperType=i.helperType);if(i.modeProps)for(var s in i.modeProps)n[s]=i.modeProps[s];return n};e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}});e.defineMIME("text/plain","null");var Ws=e.modeExtensions={};e.extendMode=function(e,t){var i=Ws.hasOwnProperty(e)?Ws[e]:Ws[e]={};yo(t,i)};e.defineExtension=function(t,i){e.prototype[t]=i};e.defineDocExtension=function(e,t){ua.prototype[e]=t};e.defineOption=Pr;var qs=[];e.defineInitHook=function(e){qs.push(e)};var zs=e.helpers={};e.registerHelper=function(t,i,r){zs.hasOwnProperty(t)||(zs[t]=e[t]={_global:[]});zs[t][i]=r};e.registerGlobalHelper=function(t,i,r,n){e.registerHelper(t,i,n);zs[t]._global.push({pred:r,val:n})};var Xs=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var i={};for(var r in t){var n=t[r];n instanceof Array&&(n=n.concat([]));i[r]=n}return i},Ys=e.startState=function(e,t,i){return e.startState?e.startState(t,i):!0};e.innerMode=function(e,t){for(;e.innerMode;){var i=e.innerMode(t);if(!i||i.mode==e)break;t=i.state;e=i.mode}return i||{mode:e,state:t}};var Ks=e.commands={selectAll:function(e){e.setSelection(Is(e.firstLine(),0),Is(e.lastLine()),Ta)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),Ta)},killLine:function(e){Rr(e,function(t){if(t.empty()){var i=Bn(e.doc,t.head.line).text.length;return t.head.ch==i&&t.head.line<e.lastLine()?{from:t.head,to:Is(t.head.line+1,0)}:{from:t.head,to:Is(t.head.line,i)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){Rr(e,function(t){return{from:Is(t.from().line,0),to:tt(e.doc,Is(t.to().line+1,0))}})},delLineLeft:function(e){Rr(e,function(e){return{from:Is(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return{from:r,to:t.from()}})},delWrappedLineRight:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div");return{from:t.from(),to:r}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(Is(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(Is(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Xo(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Ko(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return Yo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div")},Ia)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:i},"div")},Ia)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return r.ch<e.getLine(r.line).search(/\S/)?Ko(e,t.head):r},Ia)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],i=e.listSelections(),r=e.options.tabSize,n=0;n<i.length;n++){var o=i[n].from(),s=ya(e.getLine(o.line),o.ch,r);t.push(new Array(r-s%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){fi(e,function(){for(var t=e.listSelections(),i=[],r=0;r<t.length;r++){var n=t[r].head,o=Bn(e.doc,n.line).text;if(o){n.ch==o.length&&(n=new Is(n.line,n.ch-1));if(n.ch>0){n=new Is(n.line,n.ch+1);e.replaceRange(o.charAt(n.ch-1)+o.charAt(n.ch-2),Is(n.line,n.ch-2),n,"+transpose")}else if(n.line>e.doc.first){var s=Bn(e.doc,n.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),Is(n.line-1,s.length-1),Is(n.line,1),"+transpose")}}i.push(new Q(n,n))}e.setSelections(i)})},newlineAndIndent:function(e){fi(e,function(){for(var t=e.listSelections().length,i=0;t>i;i++){var r=e.listSelections()[i];e.replaceRange("\n",r.anchor,r.head,"+input");e.indentLine(r.from().line+1,null,!0);yr(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},$s=e.keyMap={};$s.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"};$s.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"};$s.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"};$s.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]};$s["default"]=ms?$s.macDefault:$s.pcDefault;e.normalizeKeyMap=function(e){var t={};for(var i in e)if(e.hasOwnProperty(i)){var r=e[i];if(/^(name|fallthrough|(de|at)tach)$/.test(i))continue;if("..."==r){delete e[i];continue}for(var n=Lo(i.split(" "),Dr),o=0;o<n.length;o++){var s,a;if(o==n.length-1){a=i;s=r}else{a=n.slice(0,o+1).join(" ");s="..."}var l=t[a];if(l){if(l!=s)throw new Error("Inconsistent bindings for "+a)}else t[a]=s}delete e[i]}for(var u in t)e[u]=t[u];return e};var Qs=e.lookupKey=function(e,t,i,r){t=wr(t);var n=t.call?t.call(e,r):t[e];if(n===!1)return"nothing";if("..."===n)return"multi";if(null!=n&&i(n))return"handled";if(t.fallthrough){if("[object Array]"!=Object.prototype.toString.call(t.fallthrough))return Qs(e,t.fallthrough,i,r);for(var o=0;o<t.fallthrough.length;o++){var s=Qs(e,t.fallthrough[o],i,r);if(s)return s}}},Zs=e.isModifierKey=function(e){var t="string"==typeof e?e:Fa[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Js=e.keyName=function(e,t){if(us&&34==e.keyCode&&e["char"])return!1;var i=Fa[e.keyCode],r=i;if(null==r||e.altGraphKey)return!1;e.altKey&&"Alt"!=i&&(r="Alt-"+r);(xs?e.metaKey:e.ctrlKey)&&"Ctrl"!=i&&(r="Ctrl-"+r);(xs?e.ctrlKey:e.metaKey)&&"Cmd"!=i&&(r="Cmd-"+r);!t&&e.shiftKey&&"Shift"!=i&&(r="Shift-"+r);return r};e.fromTextArea=function(t,i){function r(){t.value=u.getValue()}i||(i={});i.value=t.value;!i.tabindex&&t.tabindex&&(i.tabindex=t.tabindex);!i.placeholder&&t.placeholder&&(i.placeholder=t.placeholder);if(null==i.autofocus){var n=wo();i.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}if(t.form){Ea(t.form,"submit",r);if(!i.leaveSubmitMethodAlone){var o=t.form,s=o.submit;try{var a=o.submit=function(){r();o.submit=s;o.submit();o.submit=a}}catch(l){}}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},i);u.save=r;u.getTextArea=function(){return t};u.toTextArea=function(){u.toTextArea=isNaN;r();t.parentNode.removeChild(u.getWrapperElement());t.style.display="";if(t.form){ma(t.form,"submit",r);"function"==typeof t.form.submit&&(t.form.submit=s)}};return u};var ea=e.StringStream=function(e,t){this.pos=this.start=0;this.string=e;this.tabSize=t||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};ea.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var i=t==e;else var i=t&&(e.test?e.test(t):e(t));if(i){++this.pos;return t}},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1){this.pos=t;return!0}},backUp:function(e){this.pos-=e},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=ya(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ya(this.string,null,this.tabSize)-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,i){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);if(r&&r.index>0)return null;r&&t!==!1&&(this.pos+=r[0].length);return r}var n=function(e){return i?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);if(n(o)==n(e)){t!==!1&&(this.pos+=e.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var ta=e.TextMarker=function(e,t){this.lines=[];this.type=t;this.doc=e};mo(ta);ta.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;t&&ni(e);if(Eo(this,"clear")){var i=this.find();i&&po(this,"clear",i.from,i.to)}for(var r=null,n=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=Vr(s.markedSpans,this);if(e&&!this.collapsed)Ni(e,Hn(s),"text");else if(e){null!=a.to&&(n=Hn(s));null!=a.from&&(r=Hn(s))}s.markedSpans=Fr(s.markedSpans,a);null==a.from&&this.collapsed&&!un(this.doc,s)&&e&&Fn(s,ii(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=on(this.lines[o]),u=c(l);if(u>e.display.maxLineLength){e.display.maxLine=l;e.display.maxLineLength=u;e.display.maxLineChanged=!0}}null!=r&&e&&this.collapsed&&xi(e,r,n+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;e&&Et(e.doc)}e&&po(e,"markerCleared",e,this);t&&si(e);this.parent&&this.parent.clear()}};ta.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var i,r,n=0;n<this.lines.length;++n){var o=this.lines[n],s=Vr(o.markedSpans,this);if(null!=s.from){i=Is(t?o:Hn(o),s.from);if(-1==e)return i}if(null!=s.to){r=Is(t?o:Hn(o),s.to);if(1==e)return r}}return i&&{from:i,to:r}};ta.prototype.changed=function(){var e=this.find(-1,!0),t=this,i=this.doc.cm;e&&i&&fi(i,function(){var r=e.line,n=Hn(e.line),o=Bt(i,n);if(o){jt(o);i.curOp.selectionChanged=i.curOp.forceUpdate=!0}i.curOp.updateMaxLine=!0;if(!un(t.doc,r)&&null!=t.height){var s=t.height;t.height=null;var a=dn(t)-s;a&&Fn(r,r.height+a)}})};ta.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=To(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)};ta.prototype.detachLine=function(e){this.lines.splice(To(this.lines,e),1);if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var ia=0,ra=e.SharedTextMarker=function(e,t){this.markers=e;this.primary=t;for(var i=0;i<e.length;++i)e[i].parent=this};mo(ra);ra.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();po(this,"clear")}};ra.prototype.find=function(e,t){return this.primary.find(e,t)};var na=e.LineWidget=function(e,t,i){if(i)for(var r in i)i.hasOwnProperty(r)&&(this[r]=i[r]);this.cm=e;this.node=t};mo(na);na.prototype.clear=function(){var e=this.cm,t=this.line.widgets,i=this.line,r=Hn(i);if(null!=r&&t){for(var n=0;n<t.length;++n)t[n]==this&&t.splice(n--,1);t.length||(i.widgets=null);var o=dn(this);fi(e,function(){cn(e,i,-o);Ni(e,r,"widget");Fn(i,Math.max(0,i.height-o))})}};na.prototype.changed=function(){var e=this.height,t=this.cm,i=this.line;this.height=null;var r=dn(this)-e;r&&fi(t,function(){t.curOp.forceUpdate=!0;cn(t,i,r);Fn(i,i.height+r)})};var oa=e.Line=function(e,t,i){this.text=e;$r(this,t);this.height=i?i(this):1};mo(oa);oa.prototype.lineNo=function(){return Hn(this)};var sa={},aa={};_n.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var i=e,r=e+t;r>i;++i){var n=this.lines[i];this.height-=n.height;En(n);po(n,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,i){this.height+=i;this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,i){for(var r=e+t;r>e;++e)if(i(this.lines[e]))return!0}};Mn.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var i=0;i<this.children.length;++i){var r=this.children[i],n=r.chunkSize();if(n>e){var o=Math.min(t,n-e),s=r.height;r.removeInner(e,o);this.height-=s-r.height;if(n==o){this.children.splice(i--,1);r.parent=null}if(0==(t-=o))break;e=0}else e-=n}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof _n))){var a=[];this.collapse(a);this.children=[new _n(a)];this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,i){this.size+=t.length;this.height+=i;for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>=e){n.insertInner(e,t,i);if(n.lines&&n.lines.length>50){for(;n.lines.length>50;){var s=n.lines.splice(n.lines.length-25,25),a=new _n(s);n.height-=a.height;this.children.splice(r+1,0,a);a.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),i=new Mn(t);if(e.parent){e.size-=i.size;e.height-=i.height;var r=To(e.parent.children,e);e.parent.children.splice(r+1,0,i)}else{var n=new Mn(e.children);n.parent=e;e.children=[n,i];e=n}i.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,i){for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>e){var s=Math.min(t,o-e);if(n.iterN(e,s,i))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var la=0,ua=e.Doc=function(e,t,i){if(!(this instanceof ua))return new ua(e,t,i);null==i&&(i=0);Mn.call(this,[new _n([new oa("",null)])]);this.first=i;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=i;var r=Is(i,0);this.sel=J(r);this.history=new zn(null);this.id=++la;this.modeOption=t;"string"==typeof e&&(e=Ga(e));wn(this,{from:r,to:r,text:e});dt(this,J(r),Ta)};ua.prototype=Io(Mn.prototype,{constructor:ua,iter:function(e,t,i){i?this.iterN(e-this.first,t-e,i):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var i=0,r=0;r<t.length;++r)i+=t[r].height;this.insertInner(e-this.first,t,i)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Vn(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:mi(function(e){var t=Is(this.first,0),i=this.first+this.size-1;dr(this,{from:t,to:Is(i,Bn(this,i).text.length),text:Ga(e),origin:"setValue",full:!0},!0);dt(this,J(t))}),replaceRange:function(e,t,i,r){t=tt(this,t);i=i?tt(this,i):t;vr(this,e,t,i,r)},getRange:function(e,t,i){var r=Un(this,tt(this,e),tt(this,t));return i===!1?r:r.join(i||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return rt(this,e)?Bn(this,e):void 0},getLineNumber:function(e){return Hn(e)},getLineHandleVisualStart:function(e){"number"==typeof e&&(e=Bn(this,e));return on(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return tt(this,e)},getCursor:function(e){var t,i=this.sel.primary();t=null==e||"head"==e?i.head:"anchor"==e?i.anchor:"end"==e||"to"==e||e===!1?i.to():i.from();return t},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:mi(function(e,t,i){ut(this,tt(this,"number"==typeof e?Is(e,t||0):e),null,i)}),setSelection:mi(function(e,t,i){ut(this,tt(this,e),tt(this,t||e),i)}),extendSelection:mi(function(e,t,i){st(this,tt(this,e),t&&tt(this,t),i)}),extendSelections:mi(function(e,t){at(this,nt(this,e,t))}),extendSelectionsBy:mi(function(e,t){at(this,Lo(this.sel.ranges,e),t)}),setSelections:mi(function(e,t,i){if(e.length){for(var r=0,n=[];r<e.length;r++)n[r]=new Q(tt(this,e[r].anchor),tt(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex));dt(this,Z(n,t),i)}}),addSelection:mi(function(e,t,i){var r=this.sel.ranges.slice(0);r.push(new Q(tt(this,e),tt(this,t||e)));dt(this,Z(r,r.length-1),i)}),getSelection:function(e){for(var t,i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());t=t?t.concat(n):n}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());e!==!1&&(n=n.join(e||"\n"));t[r]=n}return t},replaceSelection:function(e,t,i){for(var r=[],n=0;n<this.sel.ranges.length;n++)r[n]=e;this.replaceSelections(r,t,i||"+input")},replaceSelections:mi(function(e,t,i){for(var r=[],n=this.sel,o=0;o<n.ranges.length;o++){var s=n.ranges[o];r[o]={from:s.from(),to:s.to(),text:Ga(e[o]),origin:i}}for(var a=t&&"end"!=t&&pr(this,r,t),o=r.length-1;o>=0;o--)dr(this,r[o]);a?ct(this,a):this.cm&&yr(this.cm)}),undo:mi(function(){hr(this,"undo")}),redo:mi(function(){hr(this,"redo")}),undoSelection:mi(function(){hr(this,"undo",!0)}),redoSelection:mi(function(){hr(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,i=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++i;return{undo:t,redo:i}},clearHistory:function(){this.history=new zn(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:ro(this.history.done),undone:ro(this.history.undone)}},setHistory:function(e){var t=this.history=new zn(this.history.maxGeneration);t.done=ro(e.done.slice(0),null,!0);t.undone=ro(e.undone.slice(0),null,!0)},addLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass";if(e[r]){if(_o(i).test(e[r]))return!1;e[r]+=" "+i}else e[r]=i;return!0})}),removeLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass",n=e[r];if(!n)return!1;if(null==i)e[r]=null;else{var o=n.match(_o(i));if(!o)return!1;var s=o.index+o[0].length;e[r]=n.slice(0,o.index)+(o.index&&s!=n.length?" ":"")+n.slice(s)||null}return!0})}),markText:function(e,t,i){return _r(this,tt(this,e),tt(this,t),i,"range")},setBookmark:function(e,t){var i={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};e=tt(this,e);return _r(this,e,e,i,"bookmark")},findMarksAt:function(e){e=tt(this,e);var t=[],i=Bn(this,e.line).markedSpans;if(i)for(var r=0;r<i.length;++r){var n=i[r];(null==n.from||n.from<=e.ch)&&(null==n.to||n.to>=e.ch)&&t.push(n.marker.parent||n.marker)}return t},findMarks:function(e,t,i){e=tt(this,e);t=tt(this,t);var r=[],n=e.line;this.iter(e.line,t.line+1,function(o){var s=o.markedSpans;if(s)for(var a=0;a<s.length;a++){var l=s[a];n==e.line&&e.ch>l.to||null==l.from&&n!=e.line||n==t.line&&l.from>t.ch||i&&!i(l.marker)||r.push(l.marker.parent||l.marker)}++n});return r},getAllMarks:function(){var e=[];this.iter(function(t){var i=t.markedSpans;if(i)for(var r=0;r<i.length;++r)null!=i[r].from&&e.push(i[r].marker)});return e},posFromIndex:function(e){var t,i=this.first;this.iter(function(r){var n=r.text.length+1;if(n>e){t=e;return!0}e-=n;++i});return tt(this,Is(i,t))},indexFromPos:function(e){e=tt(this,e);var t=e.ch;if(e.line<this.first||e.ch<0)return 0;this.iter(this.first,e.line,function(e){t+=e.text.length+1});return t},copy:function(e){var t=new ua(Vn(this,this.first,this.first+this.size),this.modeOption,this.first);t.scrollTop=this.scrollTop;t.scrollLeft=this.scrollLeft;t.sel=this.sel;t.extend=!1;if(e){t.history.undoDepth=this.history.undoDepth;t.setHistory(this.getHistory())}return t},linkedDoc:function(e){e||(e={});var t=this.first,i=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from);null!=e.to&&e.to<i&&(i=e.to);var r=new ua(Vn(this,t,i),e.mode||this.modeOption,t);e.sharedHist&&(r.history=this.history);(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist});r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}];Gr(r,kr(this));return r},unlinkDoc:function(t){t instanceof e&&(t=t.doc);if(this.linked)for(var i=0;i<this.linked.length;++i){var r=this.linked[i];if(r.doc==t){this.linked.splice(i,1);t.unlinkDoc(this);Br(kr(this));break}}if(t.history==this.history){var n=[t.id];kn(t,function(e){n.push(e.id)},!0);t.history=new zn(null);t.history.done=ro(this.history.done,n);t.history.undone=ro(this.history.undone,n)}},iterLinkedDocs:function(e){kn(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}});ua.prototype.eachLine=ua.prototype.iter;var pa="iter insert remove copy getEditor".split(" ");for(var ca in ua.prototype)ua.prototype.hasOwnProperty(ca)&&To(pa,ca)<0&&(e.prototype[ca]=function(e){return function(){return e.apply(this.doc,arguments)}}(ua.prototype[ca]));mo(ua);var da=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},fa=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ha=e.e_stop=function(e){da(e);fa(e)},Ea=e.on=function(e,t,i){if(e.addEventListener)e.addEventListener(t,i,!1);else if(e.attachEvent)e.attachEvent("on"+t,i);else{var r=e._handlers||(e._handlers={}),n=r[t]||(r[t]=[]);n.push(i)}},ma=e.off=function(e,t,i){if(e.removeEventListener)e.removeEventListener(t,i,!1);else if(e.detachEvent)e.detachEvent("on"+t,i);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var n=0;n<r.length;++n)if(r[n]==i){r.splice(n,1);break}}},ga=e.signal=function(e,t){var i=e._handlers&&e._handlers[t];if(i)for(var r=Array.prototype.slice.call(arguments,2),n=0;n<i.length;++n)i[n].apply(null,r)},va=null,xa=30,Na=e.Pass={toString:function(){return"CodeMirror.Pass"}},Ta={scroll:!1},La={origin:"*mouse"},Ia={origin:"+move"};go.prototype.set=function(e,t){clearTimeout(this.id);this.id=setTimeout(t,e)};var ya=e.countColumn=function(e,t,i,r,n){if(null==t){t=e.search(/[^\s\u00a0]/);-1==t&&(t=e.length)}for(var o=r||0,s=n||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o;s+=i-s%i;o=a+1}},Aa=[""],Sa=function(e){e.select()};hs?Sa=function(e){e.selectionStart=0;e.selectionEnd=e.value.length}:ns&&(Sa=function(e){try{e.select()}catch(t){}});var Ca,Ra=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ba=e.isWordChar=function(e){return/\w/.test(e)||e>""&&(e.toUpperCase()!=e.toLowerCase()||Ra.test(e))},Oa=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
Ca=document.createRange?function(e,t,i){var r=document.createRange();r.setEnd(e,i);r.setStart(e,t);return r}:function(e,t,i){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(n){return r}r.collapse(!0);r.moveEnd("character",i);r.moveStart("character",t);return r};ns&&11>os&&(wo=function(){try{return document.activeElement}catch(e){return document.body}});var Pa,Da,wa=e.rmClass=function(e,t){var i=e.className,r=_o(t).exec(i);if(r){var n=i.slice(r.index+r[0].length);e.className=i.slice(0,r.index)+(n?r[1]+n:"")}},_a=e.addClass=function(e,t){var i=e.className;_o(t).test(i)||(e.className+=(i?" ":"")+t)},Ma=!1,ka=function(){if(ns&&9>os)return!1;var e=bo("div");return"draggable"in e||"dragDrop"in e}(),Ga=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,i=[],r=e.length;r>=t;){var n=e.indexOf("\n",t);-1==n&&(n=e.length);var o=e.slice(t,"\r"==e.charAt(n-1)?n-1:n),s=o.indexOf("\r");if(-1!=s){i.push(o.slice(0,s));t+=s+1}else{i.push(o);t=n+1}}return i}:function(e){return e.split(/\r\n?|\n/)},Ba=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(i){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Ua=function(){var e=bo("div");if("oncopy"in e)return!0;e.setAttribute("oncopy","return;");return"function"==typeof e.oncopy}(),Va=null,Fa={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};e.keyNames=Fa;(function(){for(var e=0;10>e;e++)Fa[e+48]=Fa[e+96]=String(e);for(var e=65;90>=e;e++)Fa[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Fa[e+111]=Fa[e+63235]="F"+e})();var Ha,ja=function(){function e(e){return 247>=e?i.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,i){this.level=e;this.from=t;this.to=i}var i="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(i){if(!n.test(i))return!1;for(var r,p=i.length,c=[],d=0;p>d;++d)c.push(r=e(i.charCodeAt(d)));for(var d=0,f=u;p>d;++d){var r=c[d];"m"==r?c[d]=f:f=r}for(var d=0,h=u;p>d;++d){var r=c[d];if("1"==r&&"r"==h)c[d]="n";else if(s.test(r)){h=r;"r"==r&&(c[d]="R")}}for(var d=1,f=c[0];p-1>d;++d){var r=c[d];"+"==r&&"1"==f&&"1"==c[d+1]?c[d]="1":","!=r||f!=c[d+1]||"1"!=f&&"n"!=f||(c[d]=f);f=r}for(var d=0;p>d;++d){var r=c[d];if(","==r)c[d]="N";else if("%"==r){for(var E=d+1;p>E&&"%"==c[E];++E);for(var m=d&&"!"==c[d-1]||p>E&&"1"==c[E]?"1":"N",g=d;E>g;++g)c[g]=m;d=E-1}}for(var d=0,h=u;p>d;++d){var r=c[d];"L"==h&&"1"==r?c[d]="L":s.test(r)&&(h=r)}for(var d=0;p>d;++d)if(o.test(c[d])){for(var E=d+1;p>E&&o.test(c[E]);++E);for(var v="L"==(d?c[d-1]:u),x="L"==(p>E?c[E]:u),m=v||x?"L":"R",g=d;E>g;++g)c[g]=m;d=E-1}for(var N,T=[],d=0;p>d;)if(a.test(c[d])){var L=d;for(++d;p>d&&a.test(c[d]);++d);T.push(new t(0,L,d))}else{var I=d,y=T.length;for(++d;p>d&&"L"!=c[d];++d);for(var g=I;d>g;)if(l.test(c[g])){g>I&&T.splice(y,0,new t(1,I,g));var A=g;for(++g;d>g&&l.test(c[g]);++g);T.splice(y,0,new t(2,A,g));I=g}else++g;d>I&&T.splice(y,0,new t(1,I,d))}if(1==T[0].level&&(N=i.match(/^\s+/))){T[0].from=N[0].length;T.unshift(new t(0,0,N[0].length))}if(1==No(T).level&&(N=i.match(/\s+$/))){No(T).to-=N[0].length;T.push(new t(0,p-N[0].length,p))}T[0].level!=No(T).level&&T.push(new t(T[0].level,p,p));return T}}();e.version="4.12.0";return e})},{}],15:[function(t,i){(function(e,t){"object"==typeof i&&"object"==typeof i.exports?i.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)})("undefined"!=typeof window?window:this,function(t,i){function r(e){var t=e.length,i=ot.type(e);return"function"===i||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===i||0===t||"number"==typeof t&&t>0&&t-1 in e}function n(e,t,i){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==i});if(t.nodeType)return ot.grep(e,function(e){return e===t!==i});if("string"==typeof t){if(ft.test(t))return ot.filter(t,e,i);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==i})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=Tt[e]={};ot.each(e.match(Nt)||[],function(e,i){t[i]=!0});return t}function a(){if(Et.addEventListener){Et.removeEventListener("DOMContentLoaded",l,!1);t.removeEventListener("load",l,!1)}else{Et.detachEvent("onreadystatechange",l);t.detachEvent("onload",l)}}function l(){if(Et.addEventListener||"load"===event.type||"complete"===Et.readyState){a();ot.ready()}}function u(e,t,i){if(void 0===i&&1===e.nodeType){var r="data-"+t.replace(St,"-$1").toLowerCase();i=e.getAttribute(r);if("string"==typeof i){try{i="true"===i?!0:"false"===i?!1:"null"===i?null:+i+""===i?+i:At.test(i)?ot.parseJSON(i):i}catch(n){}ot.data(e,t,i)}else i=void 0}return i}function p(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,i,r){if(ot.acceptData(e)){var n,o,s=ot.expando,a=e.nodeType,l=a?ot.cache:e,u=a?e[s]:e[s]&&s;if(u&&l[u]&&(r||l[u].data)||void 0!==i||"string"!=typeof t){u||(u=a?e[s]=K.pop()||ot.guid++:s);l[u]||(l[u]=a?{}:{toJSON:ot.noop});("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t));o=l[u];if(!r){o.data||(o.data={});o=o.data}void 0!==i&&(o[ot.camelCase(t)]=i);if("string"==typeof t){n=o[t];null==n&&(n=o[ot.camelCase(t)])}else n=o;return n}}}function d(e,t,i){if(ot.acceptData(e)){var r,n,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t){r=i?s[a]:s[a].data;if(r){if(ot.isArray(t))t=t.concat(ot.map(t,ot.camelCase));else if(t in r)t=[t];else{t=ot.camelCase(t);t=t in r?[t]:t.split(" ")}n=t.length;for(;n--;)delete r[t[n]];if(i?!p(r):!ot.isEmptyObject(r))return}}if(!i){delete s[a].data;if(!p(s[a]))return}o?ot.cleanData([e],!0):rt.deleteExpando||s!=s.window?delete s[a]:s[a]=null}}}function f(){return!0}function h(){return!1}function E(){try{return Et.activeElement}catch(e){}}function m(e){var t=Gt.split("|"),i=e.createDocumentFragment();if(i.createElement)for(;t.length;)i.createElement(t.pop());return i}function g(e,t){var i,r,n=0,o=typeof e.getElementsByTagName!==yt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==yt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],i=e.childNodes||e;null!=(r=i[n]);n++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,g(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function v(e){Pt.test(e.type)&&(e.defaultChecked=e.checked)}function x(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function N(e){e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type;return e}function T(e){var t=Yt.exec(e.type);t?e.type=t[1]:e.removeAttribute("type");return e}function L(e,t){for(var i,r=0;null!=(i=e[r]);r++)ot._data(i,"globalEval",!t||ot._data(t[r],"globalEval"))}function I(e,t){if(1===t.nodeType&&ot.hasData(e)){var i,r,n,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle;s.events={};for(i in a)for(r=0,n=a[i].length;n>r;r++)ot.event.add(t,i,a[i][r])}s.data&&(s.data=ot.extend({},s.data))}}function y(e,t){var i,r,n;if(1===t.nodeType){i=t.nodeName.toLowerCase();if(!rt.noCloneEvent&&t[ot.expando]){n=ot._data(t);for(r in n.events)ot.removeEvent(t,r,n.handle);t.removeAttribute(ot.expando)}if("script"===i&&t.text!==e.text){N(t).text=e.text;T(t)}else if("object"===i){t.parentNode&&(t.outerHTML=e.outerHTML);rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)}else if("input"===i&&Pt.test(e.type)){t.defaultChecked=t.checked=e.checked;t.value!==e.value&&(t.value=e.value)}else"option"===i?t.defaultSelected=t.selected=e.defaultSelected:("input"===i||"textarea"===i)&&(t.defaultValue=e.defaultValue)}}function A(e,i){var r,n=ot(i.createElement(e)).appendTo(i.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(n[0]))?r.display:ot.css(n[0],"display");n.detach();return o}function S(e){var t=Et,i=ei[e];if(!i){i=A(e,t);if("none"===i||!i){Jt=(Jt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement);t=(Jt[0].contentWindow||Jt[0].contentDocument).document;t.write();t.close();i=A(e,t);Jt.detach()}ei[e]=i}return i}function C(e,t){return{get:function(){var i=e();if(null!=i){if(!i)return(this.get=t).apply(this,arguments);delete this.get}}}}function R(e,t){if(t in e)return t;for(var i=t.charAt(0).toUpperCase()+t.slice(1),r=t,n=fi.length;n--;){t=fi[n]+i;if(t in e)return t}return r}function b(e,t){for(var i,r,n,o=[],s=0,a=e.length;a>s;s++){r=e[s];if(r.style){o[s]=ot._data(r,"olddisplay");i=r.style.display;if(t){o[s]||"none"!==i||(r.style.display="");""===r.style.display&&bt(r)&&(o[s]=ot._data(r,"olddisplay",S(r.nodeName)))}else{n=bt(r);(i&&"none"!==i||!n)&&ot._data(r,"olddisplay",n?i:ot.css(r,"display"))}}}for(s=0;a>s;s++){r=e[s];r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"))}return e}function O(e,t,i){var r=ui.exec(t);return r?Math.max(0,r[1]-(i||0))+(r[2]||"px"):t}function P(e,t,i,r,n){for(var o=i===(r?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2){"margin"===i&&(s+=ot.css(e,i+Rt[o],!0,n));if(r){"content"===i&&(s-=ot.css(e,"padding"+Rt[o],!0,n));"margin"!==i&&(s-=ot.css(e,"border"+Rt[o]+"Width",!0,n))}else{s+=ot.css(e,"padding"+Rt[o],!0,n);"padding"!==i&&(s+=ot.css(e,"border"+Rt[o]+"Width",!0,n))}}return s}function D(e,t,i){var r=!0,n="width"===t?e.offsetWidth:e.offsetHeight,o=ti(e),s=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=n||null==n){n=ii(e,t,o);(0>n||null==n)&&(n=e.style[t]);if(ni.test(n))return n;r=s&&(rt.boxSizingReliable()||n===e.style[t]);n=parseFloat(n)||0}return n+P(e,t,i||(s?"border":"content"),r,o)+"px"}function w(e,t,i,r,n){return new w.prototype.init(e,t,i,r,n)}function _(){setTimeout(function(){hi=void 0});return hi=ot.now()}function M(e,t){var i,r={height:e},n=0;t=t?1:0;for(;4>n;n+=2-t){i=Rt[n];r["margin"+i]=r["padding"+i]=e}t&&(r.opacity=r.width=e);return r}function k(e,t,i){for(var r,n=(Ni[t]||[]).concat(Ni["*"]),o=0,s=n.length;s>o;o++)if(r=n[o].call(i,t,e))return r}function G(e,t,i){var r,n,o,s,a,l,u,p,c=this,d={},f=e.style,h=e.nodeType&&bt(e),E=ot._data(e,"fxshow");if(!i.queue){a=ot._queueHooks(e,"fx");if(null==a.unqueued){a.unqueued=0;l=a.empty.fire;a.empty.fire=function(){a.unqueued||l()}}a.unqueued++;c.always(function(){c.always(function(){a.unqueued--;ot.queue(e,"fx").length||a.empty.fire()})})}if(1===e.nodeType&&("height"in t||"width"in t)){i.overflow=[f.overflow,f.overflowX,f.overflowY];u=ot.css(e,"display");p="none"===u?ot._data(e,"olddisplay")||S(e.nodeName):u;"inline"===p&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?f.zoom=1:f.display="inline-block")}if(i.overflow){f.overflow="hidden";rt.shrinkWrapBlocks()||c.always(function(){f.overflow=i.overflow[0];f.overflowX=i.overflow[1];f.overflowY=i.overflow[2]})}for(r in t){n=t[r];if(mi.exec(n)){delete t[r];o=o||"toggle"===n;if(n===(h?"hide":"show")){if("show"!==n||!E||void 0===E[r])continue;h=!0}d[r]=E&&E[r]||ot.style(e,r)}else u=void 0}if(ot.isEmptyObject(d))"inline"===("none"===u?S(e.nodeName):u)&&(f.display=u);else{E?"hidden"in E&&(h=E.hidden):E=ot._data(e,"fxshow",{});o&&(E.hidden=!h);h?ot(e).show():c.done(function(){ot(e).hide()});c.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d){s=k(h?E[r]:0,r,c);if(!(r in E)){E[r]=s.start;if(h){s.end=s.start;s.start="width"===r||"height"===r?1:0}}}}}function B(e,t){var i,r,n,o,s;for(i in e){r=ot.camelCase(i);n=t[r];o=e[i];if(ot.isArray(o)){n=o[1];o=e[i]=o[0]}if(i!==r){e[r]=o;delete e[i]}s=ot.cssHooks[r];if(s&&"expand"in s){o=s.expand(o);delete e[r];for(i in o)if(!(i in e)){e[i]=o[i];t[i]=n}}else t[r]=n}}function U(e,t,i){var r,n,o=0,s=xi.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(n)return!1;for(var t=hi||_(),i=Math.max(0,u.startTime+u.duration-t),r=i/u.duration||0,o=1-r,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);a.notifyWith(e,[u,o,i]);if(1>o&&l)return i;a.resolveWith(e,[u]);return!1},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},i),originalProperties:t,originalOptions:i,startTime:hi||_(),duration:i.duration,tweens:[],createTween:function(t,i){var r=ot.Tween(e,u.opts,t,i,u.opts.specialEasing[t]||u.opts.easing);u.tweens.push(r);return r},stop:function(t){var i=0,r=t?u.tweens.length:0;if(n)return this;n=!0;for(;r>i;i++)u.tweens[i].run(1);t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]);return this}}),p=u.props;B(p,u.opts.specialEasing);for(;s>o;o++){r=xi[o].call(u,e,p,u.opts);if(r)return r}ot.map(p,k,u);ot.isFunction(u.opts.start)&&u.opts.start.call(e,u);ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue}));return u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function V(e){return function(t,i){if("string"!=typeof t){i=t;t="*"}var r,n=0,o=t.toLowerCase().match(Nt)||[];if(ot.isFunction(i))for(;r=o[n++];)if("+"===r.charAt(0)){r=r.slice(1)||"*";(e[r]=e[r]||[]).unshift(i)}else(e[r]=e[r]||[]).push(i)}}function F(e,t,i,r){function n(a){var l;o[a]=!0;ot.each(e[a]||[],function(e,a){var u=a(t,i,r);if("string"==typeof u&&!s&&!o[u]){t.dataTypes.unshift(u);n(u);return!1}return s?!(l=u):void 0});return l}var o={},s=e===Wi;return n(t.dataTypes[0])||!o["*"]&&n("*")}function H(e,t){var i,r,n=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((n[r]?e:i||(i={}))[r]=t[r]);i&&ot.extend(!0,e,i);return e}function j(e,t,i){for(var r,n,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];){l.shift();void 0===n&&(n=e.mimeType||t.getResponseHeader("Content-Type"))}if(n)for(s in a)if(a[s]&&a[s].test(n)){l.unshift(s);break}if(l[0]in i)o=l[0];else{for(s in i){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}r||(r=s)}o=o||r}if(o){o!==l[0]&&l.unshift(o);return i[o]}}function W(e,t,i,r){var n,o,s,a,l,u={},p=e.dataTypes.slice();if(p[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];o=p.shift();for(;o;){e.responseFields[o]&&(i[e.responseFields[o]]=t);!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType));l=o;o=p.shift();if(o)if("*"===o)o=l;else if("*"!==l&&l!==o){s=u[l+" "+o]||u["* "+o];if(!s)for(n in u){a=n.split(" ");if(a[1]===o){s=u[l+" "+a[0]]||u["* "+a[0]];if(s){if(s===!0)s=u[n];else if(u[n]!==!0){o=a[0];p.unshift(a[1])}break}}}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(c){return{state:"parsererror",error:s?c:"No conversion from "+l+" to "+o}}}}return{state:"success",data:t}}function q(e,t,i,r){var n;if(ot.isArray(t))ot.each(t,function(t,n){i||Yi.test(e)?r(e,n):q(e+"["+("object"==typeof n?t:"")+"]",n,i,r)});else if(i||"object"!==ot.type(t))r(e,t);else for(n in t)q(e+"["+n+"]",t[n],i,r)}function z(){try{return new t.XMLHttpRequest}catch(e){}}function X(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function Y(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var K=[],$=K.slice,Q=K.concat,Z=K.push,J=K.indexOf,et={},tt=et.toString,it=et.hasOwnProperty,rt={},nt="1.11.2",ot=function(e,t){return new ot.fn.init(e,t)},st=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:nt,constructor:ot,selector:"",length:0,toArray:function(){return $.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:$.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);t.prevObject=this;t.context=this.context;return t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,i){return e.call(t,i,t)}))},slice:function(){return this.pushStack($.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,i=+e+(0>e?t:0);return this.pushStack(i>=0&&t>i?[this[i]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:K.sort,splice:K.splice};ot.extend=ot.fn.extend=function(){var e,t,i,r,n,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;if("boolean"==typeof s){u=s;s=arguments[a]||{};a++}"object"==typeof s||ot.isFunction(s)||(s={});if(a===l){s=this;a--}for(;l>a;a++)if(null!=(n=arguments[a]))for(r in n){e=s[r];i=n[r];if(s!==i)if(u&&i&&(ot.isPlainObject(i)||(t=ot.isArray(i)))){if(t){t=!1;o=e&&ot.isArray(e)?e:[]}else o=e&&ot.isPlainObject(e)?e:{};s[r]=ot.extend(u,o,i)}else void 0!==i&&(s[r]=i)}return s};ot.extend({expando:"jQuery"+(nt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!it.call(e,"constructor")&&!it.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(i){return!1}if(rt.ownLast)for(t in e)return it.call(e,t);for(t in e);return void 0===t||it.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(at,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,i){var n,o=0,s=e.length,a=r(e);if(i)if(a)for(;s>o;o++){n=t.apply(e[o],i);if(n===!1)break}else for(o in e){n=t.apply(e[o],i);if(n===!1)break}else if(a)for(;s>o;o++){n=t.call(e[o],o,e[o]);if(n===!1)break}else for(o in e){n=t.call(e[o],o,e[o]);if(n===!1)break}return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var i=t||[];null!=e&&(r(Object(e))?ot.merge(i,"string"==typeof e?[e]:e):Z.call(i,e));return i},inArray:function(e,t,i){var r;if(t){if(J)return J.call(t,e,i);r=t.length;i=i?0>i?Math.max(0,r+i):i:0;for(;r>i;i++)if(i in t&&t[i]===e)return i}return-1},merge:function(e,t){for(var i=+t.length,r=0,n=e.length;i>r;)e[n++]=t[r++];if(i!==i)for(;void 0!==t[r];)e[n++]=t[r++];e.length=n;return e},grep:function(e,t,i){for(var r,n=[],o=0,s=e.length,a=!i;s>o;o++){r=!t(e[o],o);r!==a&&n.push(e[o])}return n},map:function(e,t,i){var n,o=0,s=e.length,a=r(e),l=[];if(a)for(;s>o;o++){n=t(e[o],o,i);null!=n&&l.push(n)}else for(o in e){n=t(e[o],o,i);null!=n&&l.push(n)}return Q.apply([],l)},guid:1,proxy:function(e,t){var i,r,n;if("string"==typeof t){n=e[t];t=e;e=n}if(!ot.isFunction(e))return void 0;i=$.call(arguments,2);r=function(){return e.apply(t||this,i.concat($.call(arguments)))};r.guid=e.guid=e.guid||ot.guid++;return r},now:function(){return+new Date},support:rt});ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var pt=function(e){function t(e,t,i,r){var n,o,s,a,l,u,c,f,h,E;(t?t.ownerDocument||t:V)!==D&&P(t);t=t||D;i=i||[];a=t.nodeType;if("string"!=typeof e||!e||1!==a&&9!==a&&11!==a)return i;if(!r&&_){if(11!==a&&(n=vt.exec(e)))if(s=n[1]){if(9===a){o=t.getElementById(s);if(!o||!o.parentNode)return i;if(o.id===s){i.push(o);return i}}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&B(t,o)&&o.id===s){i.push(o);return i}}else{if(n[2]){Z.apply(i,t.getElementsByTagName(e));return i}if((s=n[3])&&T.getElementsByClassName){Z.apply(i,t.getElementsByClassName(s));return i}}if(T.qsa&&(!M||!M.test(e))){f=c=U;h=t;E=1!==a&&e;if(1===a&&"object"!==t.nodeName.toLowerCase()){u=A(e);(c=t.getAttribute("id"))?f=c.replace(Nt,"\\$&"):t.setAttribute("id",f);f="[id='"+f+"'] ";l=u.length;for(;l--;)u[l]=f+d(u[l]);h=xt.test(e)&&p(t.parentNode)||t;E=u.join(",")}if(E)try{Z.apply(i,h.querySelectorAll(E));return i}catch(m){}finally{c||t.removeAttribute("id")}}}return C(e.replace(lt,"$1"),t,i,r)}function i(){function e(i,r){t.push(i+" ")>L.cacheLength&&delete e[t.shift()];return e[i+" "]=r}var t=[];return e}function r(e){e[U]=!0;return e}function n(e){var t=D.createElement("div");try{return!!e(t)}catch(i){return!1}finally{t.parentNode&&t.parentNode.removeChild(t);t=null}}function o(e,t){for(var i=e.split("|"),r=e.length;r--;)L.attrHandle[i[r]]=t}function s(e,t){var i=t&&e,r=i&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||X)-(~e.sourceIndex||X);if(r)return r;if(i)for(;i=i.nextSibling;)if(i===t)return-1;return e?1:-1}function a(e){return function(t){var i=t.nodeName.toLowerCase();return"input"===i&&t.type===e}}function l(e){return function(t){var i=t.nodeName.toLowerCase();return("input"===i||"button"===i)&&t.type===e}}function u(e){return r(function(t){t=+t;return r(function(i,r){for(var n,o=e([],i.length,t),s=o.length;s--;)i[n=o[s]]&&(i[n]=!(r[n]=i[n]))})})}function p(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function c(){}function d(e){for(var t=0,i=e.length,r="";i>t;t++)r+=e[t].value;return r}function f(e,t,i){var r=t.dir,n=i&&"parentNode"===r,o=H++;return t.first?function(t,i,o){for(;t=t[r];)if(1===t.nodeType||n)return e(t,i,o)}:function(t,i,s){var a,l,u=[F,o];if(s){for(;t=t[r];)if((1===t.nodeType||n)&&e(t,i,s))return!0}else for(;t=t[r];)if(1===t.nodeType||n){l=t[U]||(t[U]={});if((a=l[r])&&a[0]===F&&a[1]===o)return u[2]=a[2];l[r]=u;if(u[2]=e(t,i,s))return!0}}}function h(e){return e.length>1?function(t,i,r){for(var n=e.length;n--;)if(!e[n](t,i,r))return!1;return!0}:e[0]}function E(e,i,r){for(var n=0,o=i.length;o>n;n++)t(e,i[n],r);return r}function m(e,t,i,r,n){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)if((o=e[a])&&(!i||i(o,r,n))){s.push(o);u&&t.push(a)}return s}function g(e,t,i,n,o,s){n&&!n[U]&&(n=g(n));o&&!o[U]&&(o=g(o,s));return r(function(r,s,a,l){var u,p,c,d=[],f=[],h=s.length,g=r||E(t||"*",a.nodeType?[a]:a,[]),v=!e||!r&&t?g:m(g,d,e,a,l),x=i?o||(r?e:h||n)?[]:s:v;i&&i(v,x,a,l);if(n){u=m(x,f);n(u,[],a,l);p=u.length;for(;p--;)(c=u[p])&&(x[f[p]]=!(v[f[p]]=c))}if(r){if(o||e){if(o){u=[];p=x.length;for(;p--;)(c=x[p])&&u.push(v[p]=c);o(null,x=[],u,l)}p=x.length;for(;p--;)(c=x[p])&&(u=o?et(r,c):d[p])>-1&&(r[u]=!(s[u]=c))}}else{x=m(x===s?x.splice(h,x.length):x);o?o(null,s,x,l):Z.apply(s,x)}})}function v(e){for(var t,i,r,n=e.length,o=L.relative[e[0].type],s=o||L.relative[" "],a=o?1:0,l=f(function(e){return e===t},s,!0),u=f(function(e){return et(t,e)>-1},s,!0),p=[function(e,i,r){var n=!o&&(r||i!==R)||((t=i).nodeType?l(e,i,r):u(e,i,r));t=null;return n}];n>a;a++)if(i=L.relative[e[a].type])p=[f(h(p),i)];else{i=L.filter[e[a].type].apply(null,e[a].matches);if(i[U]){r=++a;for(;n>r&&!L.relative[e[r].type];r++);return g(a>1&&h(p),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),i,r>a&&v(e.slice(a,r)),n>r&&v(e=e.slice(r)),n>r&&d(e))}p.push(i)}return h(p)}function x(e,i){var n=i.length>0,o=e.length>0,s=function(r,s,a,l,u){var p,c,d,f=0,h="0",E=r&&[],g=[],v=R,x=r||o&&L.find.TAG("*",u),N=F+=null==v?1:Math.random()||.1,T=x.length;u&&(R=s!==D&&s);for(;h!==T&&null!=(p=x[h]);h++){if(o&&p){c=0;for(;d=e[c++];)if(d(p,s,a)){l.push(p);break}u&&(F=N)}if(n){(p=!d&&p)&&f--;r&&E.push(p)}}f+=h;if(n&&h!==f){c=0;for(;d=i[c++];)d(E,g,s,a);if(r){if(f>0)for(;h--;)E[h]||g[h]||(g[h]=$.call(l));g=m(g)}Z.apply(l,g);u&&!r&&g.length>0&&f+i.length>1&&t.uniqueSort(l)}if(u){F=N;R=v}return E};return n?r(s):s}var N,T,L,I,y,A,S,C,R,b,O,P,D,w,_,M,k,G,B,U="sizzle"+1*new Date,V=e.document,F=0,H=0,j=i(),W=i(),q=i(),z=function(e,t){e===t&&(O=!0);return 0},X=1<<31,Y={}.hasOwnProperty,K=[],$=K.pop,Q=K.push,Z=K.push,J=K.slice,et=function(e,t){for(var i=0,r=e.length;r>i;i++)if(e[i]===t)return i;return-1},tt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",it="[\\x20\\t\\r\\n\\f]",rt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",nt=rt.replace("w","w#"),ot="\\["+it+"*("+rt+")(?:"+it+"*([*^$|!~]?=)"+it+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+nt+"))|)"+it+"*\\]",st=":("+rt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ot+")*)|.*)\\)|)",at=new RegExp(it+"+","g"),lt=new RegExp("^"+it+"+|((?:^|[^\\\\])(?:\\\\.)*)"+it+"+$","g"),ut=new RegExp("^"+it+"*,"+it+"*"),pt=new RegExp("^"+it+"*([>+~]|"+it+")"+it+"*"),ct=new RegExp("="+it+"*([^\\]'\"]*?)"+it+"*\\]","g"),dt=new RegExp(st),ft=new RegExp("^"+nt+"$"),ht={ID:new RegExp("^#("+rt+")"),CLASS:new RegExp("^\\.("+rt+")"),TAG:new RegExp("^("+rt.replace("w","w*")+")"),ATTR:new RegExp("^"+ot),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+it+"*(even|odd|(([+-]|)(\\d*)n|)"+it+"*(?:([+-]|)"+it+"*(\\d+)|))"+it+"*\\)|)","i"),bool:new RegExp("^(?:"+tt+")$","i"),needsContext:new RegExp("^"+it+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+it+"*((?:-\\d)?\\d*)"+it+"*\\)|)(?=[^-]|$)","i")},Et=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,xt=/[+~]/,Nt=/'|\\/g,Tt=new RegExp("\\\\([\\da-f]{1,6}"+it+"?|("+it+")|.)","ig"),Lt=function(e,t,i){var r="0x"+t-65536;return r!==r||i?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},It=function(){P()};try{Z.apply(K=J.call(V.childNodes),V.childNodes);K[V.childNodes.length].nodeType}catch(yt){Z={apply:K.length?function(e,t){Q.apply(e,J.call(t))}:function(e,t){for(var i=e.length,r=0;e[i++]=t[r++];);e.length=i-1}}}T=t.support={};y=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1};P=t.setDocument=function(e){var t,i,r=e?e.ownerDocument||e:V;if(r===D||9!==r.nodeType||!r.documentElement)return D;D=r;w=r.documentElement;i=r.defaultView;i&&i!==i.top&&(i.addEventListener?i.addEventListener("unload",It,!1):i.attachEvent&&i.attachEvent("onunload",It));_=!y(r);T.attributes=n(function(e){e.className="i";return!e.getAttribute("className")});T.getElementsByTagName=n(function(e){e.appendChild(r.createComment(""));return!e.getElementsByTagName("*").length});T.getElementsByClassName=gt.test(r.getElementsByClassName);T.getById=n(function(e){w.appendChild(e).id=U;return!r.getElementsByName||!r.getElementsByName(U).length});if(T.getById){L.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&_){var i=t.getElementById(e);return i&&i.parentNode?[i]:[]}};L.filter.ID=function(e){var t=e.replace(Tt,Lt);return function(e){return e.getAttribute("id")===t}}}else{delete L.find.ID;L.filter.ID=function(e){var t=e.replace(Tt,Lt);return function(e){var i="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return i&&i.value===t}}}L.find.TAG=T.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):T.qsa?t.querySelectorAll(e):void 0}:function(e,t){var i,r=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;i=o[n++];)1===i.nodeType&&r.push(i);return r}return o};L.find.CLASS=T.getElementsByClassName&&function(e,t){return _?t.getElementsByClassName(e):void 0};k=[];M=[];if(T.qsa=gt.test(r.querySelectorAll)){n(function(e){w.appendChild(e).innerHTML="<a id='"+U+"'></a><select id='"+U+"-\f]' msallowcapture=''><option selected=''></option></select>";e.querySelectorAll("[msallowcapture^='']").length&&M.push("[*^$]="+it+"*(?:''|\"\")");e.querySelectorAll("[selected]").length||M.push("\\["+it+"*(?:value|"+tt+")");e.querySelectorAll("[id~="+U+"-]").length||M.push("~=");e.querySelectorAll(":checked").length||M.push(":checked");e.querySelectorAll("a#"+U+"+*").length||M.push(".#.+[+~]")});n(function(e){var t=r.createElement("input");t.setAttribute("type","hidden");e.appendChild(t).setAttribute("name","D");e.querySelectorAll("[name=d]").length&&M.push("name"+it+"*[*^$|!~]?=");e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled");e.querySelectorAll("*,:x");M.push(",.*:")})}(T.matchesSelector=gt.test(G=w.matches||w.webkitMatchesSelector||w.mozMatchesSelector||w.oMatchesSelector||w.msMatchesSelector))&&n(function(e){T.disconnectedMatch=G.call(e,"div");G.call(e,"[s!='']:x");k.push("!=",st)});M=M.length&&new RegExp(M.join("|"));k=k.length&&new RegExp(k.join("|"));t=gt.test(w.compareDocumentPosition);B=t||gt.test(w.contains)?function(e,t){var i=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(i.contains?i.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1};z=t?function(e,t){if(e===t){O=!0;return 0}var i=!e.compareDocumentPosition-!t.compareDocumentPosition;if(i)return i;i=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1;return 1&i||!T.sortDetached&&t.compareDocumentPosition(e)===i?e===r||e.ownerDocument===V&&B(V,e)?-1:t===r||t.ownerDocument===V&&B(V,t)?1:b?et(b,e)-et(b,t):0:4&i?-1:1}:function(e,t){if(e===t){O=!0;return 0}var i,n=0,o=e.parentNode,a=t.parentNode,l=[e],u=[t];if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:b?et(b,e)-et(b,t):0;if(o===a)return s(e,t);i=e;for(;i=i.parentNode;)l.unshift(i);i=t;for(;i=i.parentNode;)u.unshift(i);for(;l[n]===u[n];)n++;return n?s(l[n],u[n]):l[n]===V?-1:u[n]===V?1:0};return r};t.matches=function(e,i){return t(e,null,null,i)};t.matchesSelector=function(e,i){(e.ownerDocument||e)!==D&&P(e);i=i.replace(ct,"='$1']");if(!(!T.matchesSelector||!_||k&&k.test(i)||M&&M.test(i)))try{var r=G.call(e,i);if(r||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(n){}return t(i,D,null,[e]).length>0};t.contains=function(e,t){(e.ownerDocument||e)!==D&&P(e);return B(e,t)};t.attr=function(e,t){(e.ownerDocument||e)!==D&&P(e);var i=L.attrHandle[t.toLowerCase()],r=i&&Y.call(L.attrHandle,t.toLowerCase())?i(e,t,!_):void 0;return void 0!==r?r:T.attributes||!_?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null};t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};t.uniqueSort=function(e){var t,i=[],r=0,n=0;O=!T.detectDuplicates;b=!T.sortStable&&e.slice(0);e.sort(z);if(O){for(;t=e[n++];)t===e[n]&&(r=i.push(n));for(;r--;)e.splice(i[r],1)}b=null;return e};I=t.getText=function(e){var t,i="",r=0,n=e.nodeType;if(n){if(1===n||9===n||11===n){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)i+=I(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[r++];)i+=I(t);return i};L=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(Tt,Lt);e[3]=(e[3]||e[4]||e[5]||"").replace(Tt,Lt);"~="===e[2]&&(e[3]=" "+e[3]+" ");return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if("nth"===e[1].slice(0,3)){e[3]||t.error(e[0]);e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3]));e[5]=+(e[7]+e[8]||"odd"===e[3])}else e[3]&&t.error(e[0]);return e},PSEUDO:function(e){var t,i=!e[6]&&e[2];
if(ht.CHILD.test(e[0]))return null;if(e[3])e[2]=e[4]||e[5]||"";else if(i&&dt.test(i)&&(t=A(i,!0))&&(t=i.indexOf(")",i.length-t)-i.length)){e[0]=e[0].slice(0,t);e[2]=i.slice(0,t)}return e.slice(0,3)}},filter:{TAG:function(e){var t=e.replace(Tt,Lt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=j[e+" "];return t||(t=new RegExp("(^|"+it+")"+e+"("+it+"|$)"))&&j(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,i,r){return function(n){var o=t.attr(n,e);if(null==o)return"!="===i;if(!i)return!0;o+="";return"="===i?o===r:"!="===i?o!==r:"^="===i?r&&0===o.indexOf(r):"*="===i?r&&o.indexOf(r)>-1:"$="===i?r&&o.slice(-r.length)===r:"~="===i?(" "+o.replace(at," ")+" ").indexOf(r)>-1:"|="===i?o===r||o.slice(0,r.length+1)===r+"-":!1}},CHILD:function(e,t,i,r,n){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===n?function(e){return!!e.parentNode}:function(t,i,l){var u,p,c,d,f,h,E=o!==s?"nextSibling":"previousSibling",m=t.parentNode,g=a&&t.nodeName.toLowerCase(),v=!l&&!a;if(m){if(o){for(;E;){c=t;for(;c=c[E];)if(a?c.nodeName.toLowerCase()===g:1===c.nodeType)return!1;h=E="only"===e&&!h&&"nextSibling"}return!0}h=[s?m.firstChild:m.lastChild];if(s&&v){p=m[U]||(m[U]={});u=p[e]||[];f=u[0]===F&&u[1];d=u[0]===F&&u[2];c=f&&m.childNodes[f];for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if(1===c.nodeType&&++d&&c===t){p[e]=[F,f,d];break}}else if(v&&(u=(t[U]||(t[U]={}))[e])&&u[0]===F)d=u[1];else for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if((a?c.nodeName.toLowerCase()===g:1===c.nodeType)&&++d){v&&((c[U]||(c[U]={}))[e]=[F,d]);if(c===t)break}d-=n;return d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,i){var n,o=L.pseudos[e]||L.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);if(o[U])return o(i);if(o.length>1){n=[e,e,"",i];return L.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,n=o(e,i),s=n.length;s--;){r=et(e,n[s]);e[r]=!(t[r]=n[s])}}):function(e){return o(e,0,n)}}return o}},pseudos:{not:r(function(e){var t=[],i=[],n=S(e.replace(lt,"$1"));return n[U]?r(function(e,t,i,r){for(var o,s=n(e,null,r,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,r,o){t[0]=e;n(t,null,o,i);t[0]=null;return!i.pop()}}),has:r(function(e){return function(i){return t(e,i).length>0}}),contains:r(function(e){e=e.replace(Tt,Lt);return function(t){return(t.textContent||t.innerText||I(t)).indexOf(e)>-1}}),lang:r(function(e){ft.test(e||"")||t.error("unsupported lang: "+e);e=e.replace(Tt,Lt).toLowerCase();return function(t){var i;do if(i=_?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang")){i=i.toLowerCase();return i===e||0===i.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var i=e.location&&e.location.hash;return i&&i.slice(1)===t.id},root:function(e){return e===w},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){e.parentNode&&e.parentNode.selectedIndex;return e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!L.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return Et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,i){return[0>i?i+t:i]}),even:u(function(e,t){for(var i=0;t>i;i+=2)e.push(i);return e}),odd:u(function(e,t){for(var i=1;t>i;i+=2)e.push(i);return e}),lt:u(function(e,t,i){for(var r=0>i?i+t:i;--r>=0;)e.push(r);return e}),gt:u(function(e,t,i){for(var r=0>i?i+t:i;++r<t;)e.push(r);return e})}};L.pseudos.nth=L.pseudos.eq;for(N in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})L.pseudos[N]=a(N);for(N in{submit:!0,reset:!0})L.pseudos[N]=l(N);c.prototype=L.filters=L.pseudos;L.setFilters=new c;A=t.tokenize=function(e,i){var r,n,o,s,a,l,u,p=W[e+" "];if(p)return i?0:p.slice(0);a=e;l=[];u=L.preFilter;for(;a;){if(!r||(n=ut.exec(a))){n&&(a=a.slice(n[0].length)||a);l.push(o=[])}r=!1;if(n=pt.exec(a)){r=n.shift();o.push({value:r,type:n[0].replace(lt," ")});a=a.slice(r.length)}for(s in L.filter)if((n=ht[s].exec(a))&&(!u[s]||(n=u[s](n)))){r=n.shift();o.push({value:r,type:s,matches:n});a=a.slice(r.length)}if(!r)break}return i?a.length:a?t.error(e):W(e,l).slice(0)};S=t.compile=function(e,t){var i,r=[],n=[],o=q[e+" "];if(!o){t||(t=A(e));i=t.length;for(;i--;){o=v(t[i]);o[U]?r.push(o):n.push(o)}o=q(e,x(n,r));o.selector=e}return o};C=t.select=function(e,t,i,r){var n,o,s,a,l,u="function"==typeof e&&e,c=!r&&A(e=u.selector||e);i=i||[];if(1===c.length){o=c[0]=c[0].slice(0);if(o.length>2&&"ID"===(s=o[0]).type&&T.getById&&9===t.nodeType&&_&&L.relative[o[1].type]){t=(L.find.ID(s.matches[0].replace(Tt,Lt),t)||[])[0];if(!t)return i;u&&(t=t.parentNode);e=e.slice(o.shift().value.length)}n=ht.needsContext.test(e)?0:o.length;for(;n--;){s=o[n];if(L.relative[a=s.type])break;if((l=L.find[a])&&(r=l(s.matches[0].replace(Tt,Lt),xt.test(o[0].type)&&p(t.parentNode)||t))){o.splice(n,1);e=r.length&&d(o);if(!e){Z.apply(i,r);return i}break}}}(u||S(e,c))(r,t,!_,i,xt.test(e)&&p(t.parentNode)||t);return i};T.sortStable=U.split("").sort(z).join("")===U;T.detectDuplicates=!!O;P();T.sortDetached=n(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))});n(function(e){e.innerHTML="<a href='#'></a>";return"#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,i){return i?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)});T.attributes&&n(function(e){e.innerHTML="<input/>";e.firstChild.setAttribute("value","");return""===e.firstChild.getAttribute("value")})||o("value",function(e,t,i){return i||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue});n(function(e){return null==e.getAttribute("disabled")})||o(tt,function(e,t,i){var r;return i?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});return t}(t);ot.find=pt;ot.expr=pt.selectors;ot.expr[":"]=ot.expr.pseudos;ot.unique=pt.uniqueSort;ot.text=pt.getText;ot.isXMLDoc=pt.isXML;ot.contains=pt.contains;var ct=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,i){var r=t[0];i&&(e=":not("+e+")");return 1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))};ot.fn.extend({find:function(e){var t,i=[],r=this,n=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;n>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;n>t;t++)ot.find(e,r[t],i);i=this.pushStack(n>1?ot.unique(i):i);i.selector=this.selector?this.selector+" "+e:e;return i},filter:function(e){return this.pushStack(n(this,e||[],!1))},not:function(e){return this.pushStack(n(this,e||[],!0))},is:function(e){return!!n(this,"string"==typeof e&&ct.test(e)?ot(e):e||[],!1).length}});var ht,Et=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=ot.fn.init=function(e,t){var i,r;if(!e)return this;if("string"==typeof e){i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e);if(!i||!i[1]&&t)return!t||t.jquery?(t||ht).find(e):this.constructor(t).find(e);if(i[1]){t=t instanceof ot?t[0]:t;ot.merge(this,ot.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:Et,!0));if(dt.test(i[1])&&ot.isPlainObject(t))for(i in t)ot.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}r=Et.getElementById(i[2]);if(r&&r.parentNode){if(r.id!==i[2])return ht.find(e);this.length=1;this[0]=r}this.context=Et;this.selector=e;return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(ot.isFunction(e))return"undefined"!=typeof ht.ready?ht.ready(e):e(ot);if(void 0!==e.selector){this.selector=e.selector;this.context=e.context}return ot.makeArray(e,this)};gt.prototype=ot.fn;ht=ot(Et);var vt=/^(?:parents|prev(?:Until|All))/,xt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,i){for(var r=[],n=e[t];n&&9!==n.nodeType&&(void 0===i||1!==n.nodeType||!ot(n).is(i));){1===n.nodeType&&r.push(n);n=n[t]}return r},sibling:function(e,t){for(var i=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&i.push(e);return i}});ot.fn.extend({has:function(e){var t,i=ot(e,this),r=i.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,i[t]))return!0})},closest:function(e,t){for(var i,r=0,n=this.length,o=[],s=ct.test(e)||"string"!=typeof e?ot(e,t||this.context):0;n>r;r++)for(i=this[r];i&&i!==t;i=i.parentNode)if(i.nodeType<11&&(s?s.index(i)>-1:1===i.nodeType&&ot.find.matchesSelector(i,e))){o.push(i);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,i){return ot.dir(e,"parentNode",i)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,i){return ot.dir(e,"nextSibling",i)},prevUntil:function(e,t,i){return ot.dir(e,"previousSibling",i)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(i,r){var n=ot.map(this,t,i);"Until"!==e.slice(-5)&&(r=i);r&&"string"==typeof r&&(n=ot.filter(r,n));if(this.length>1){xt[e]||(n=ot.unique(n));vt.test(e)&&(n=n.reverse())}return this.pushStack(n)}});var Nt=/\S+/g,Tt={};ot.Callbacks=function(e){e="string"==typeof e?Tt[e]||s(e):ot.extend({},e);var t,i,r,n,o,a,l=[],u=!e.once&&[],p=function(s){i=e.memory&&s;r=!0;o=a||0;a=0;n=l.length;t=!0;for(;l&&n>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){i=!1;break}t=!1;l&&(u?u.length&&p(u.shift()):i?l=[]:c.disable())},c={add:function(){if(l){var r=l.length;(function o(t){ot.each(t,function(t,i){var r=ot.type(i);"function"===r?e.unique&&c.has(i)||l.push(i):i&&i.length&&"string"!==r&&o(i)})})(arguments);if(t)n=l.length;else if(i){a=r;p(i)}}return this},remove:function(){l&&ot.each(arguments,function(e,i){for(var r;(r=ot.inArray(i,l,r))>-1;){l.splice(r,1);if(t){n>=r&&n--;o>=r&&o--}}});return this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){l=[];n=0;return this},disable:function(){l=u=i=void 0;return this},disabled:function(){return!l},lock:function(){u=void 0;i||c.disable();return this},locked:function(){return!u},fireWith:function(e,i){if(l&&(!r||u)){i=i||[];i=[e,i.slice?i.slice():i];t?u.push(i):p(i)}return this},fire:function(){c.fireWith(this,arguments);return this},fired:function(){return!!r}};return c};ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],i="pending",r={state:function(){return i},always:function(){n.done(arguments).fail(arguments);return this},then:function(){var e=arguments;return ot.Deferred(function(i){ot.each(t,function(t,o){var s=ot.isFunction(e[t])&&e[t];n[o[1]](function(){var e=s&&s.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[o[0]+"With"](this===r?i.promise():this,s?[e]:arguments)})});e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},n={};r.pipe=r.then;ot.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add;a&&s.add(function(){i=a},t[1^e][2].disable,t[2][2].lock);n[o[0]]=function(){n[o[0]+"With"](this===n?r:this,arguments);return this};n[o[0]+"With"]=s.fireWith});r.promise(n);e&&e.call(n,n);return n},when:function(e){var t,i,r,n=0,o=$.call(arguments),s=o.length,a=1!==s||e&&ot.isFunction(e.promise)?s:0,l=1===a?e:ot.Deferred(),u=function(e,i,r){return function(n){i[e]=this;r[e]=arguments.length>1?$.call(arguments):n;r===t?l.notifyWith(i,r):--a||l.resolveWith(i,r)}};if(s>1){t=new Array(s);i=new Array(s);r=new Array(s);for(;s>n;n++)o[n]&&ot.isFunction(o[n].promise)?o[n].promise().done(u(n,r,o)).fail(l.reject).progress(u(n,i,t)):--a}a||l.resolveWith(r,o);return l.promise()}});var Lt;ot.fn.ready=function(e){ot.ready.promise().done(e);return this};ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!Et.body)return setTimeout(ot.ready);ot.isReady=!0;if(!(e!==!0&&--ot.readyWait>0)){Lt.resolveWith(Et,[ot]);if(ot.fn.triggerHandler){ot(Et).triggerHandler("ready");ot(Et).off("ready")}}}}});ot.ready.promise=function(e){if(!Lt){Lt=ot.Deferred();if("complete"===Et.readyState)setTimeout(ot.ready);else if(Et.addEventListener){Et.addEventListener("DOMContentLoaded",l,!1);t.addEventListener("load",l,!1)}else{Et.attachEvent("onreadystatechange",l);t.attachEvent("onload",l);var i=!1;try{i=null==t.frameElement&&Et.documentElement}catch(r){}i&&i.doScroll&&function n(){if(!ot.isReady){try{i.doScroll("left")}catch(e){return setTimeout(n,50)}a();ot.ready()}}()}}return Lt.promise(e)};var It,yt="undefined";for(It in ot(rt))break;rt.ownLast="0"!==It;rt.inlineBlockNeedsLayout=!1;ot(function(){var e,t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";rt.inlineBlockNeedsLayout=e=3===t.offsetWidth;e&&(i.style.zoom=1)}i.removeChild(r)}});(function(){var e=Et.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null})();ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],i=+e.nodeType||1;return 1!==i&&9!==i?!1:!t||t!==!0&&e.getAttribute("classid")===t};var At=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,St=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando];return!!e&&!p(e)},data:function(e,t,i){return c(e,t,i)},removeData:function(e,t){return d(e,t)},_data:function(e,t,i){return c(e,t,i,!0)},_removeData:function(e,t){return d(e,t,!0)}});ot.fn.extend({data:function(e,t){var i,r,n,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length){n=ot.data(o);if(1===o.nodeType&&!ot._data(o,"parsedAttrs")){i=s.length;for(;i--;)if(s[i]){r=s[i].name;if(0===r.indexOf("data-")){r=ot.camelCase(r.slice(5));u(o,r,n[r])}}ot._data(o,"parsedAttrs",!0)}}return n}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}});ot.extend({queue:function(e,t,i){var r;if(e){t=(t||"fx")+"queue";r=ot._data(e,t);i&&(!r||ot.isArray(i)?r=ot._data(e,t,ot.makeArray(i)):r.push(i));return r||[]}},dequeue:function(e,t){t=t||"fx";var i=ot.queue(e,t),r=i.length,n=i.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};if("inprogress"===n){n=i.shift();r--}if(n){"fx"===t&&i.unshift("inprogress");delete o.stop;n.call(e,s,o)}!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var i=t+"queueHooks";return ot._data(e,i)||ot._data(e,i,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue");ot._removeData(e,i)})})}});ot.fn.extend({queue:function(e,t){var i=2;if("string"!=typeof e){t=e;e="fx";i--}return arguments.length<i?ot.queue(this[0],e):void 0===t?this:this.each(function(){var i=ot.queue(this,e,t);ot._queueHooks(this,e);"fx"===e&&"inprogress"!==i[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var i,r=1,n=ot.Deferred(),o=this,s=this.length,a=function(){--r||n.resolveWith(o,[o])};if("string"!=typeof e){t=e;e=void 0}e=e||"fx";for(;s--;){i=ot._data(o[s],e+"queueHooks");if(i&&i.empty){r++;i.empty.add(a)}}a();return n.promise(t)}});var Ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Rt=["Top","Right","Bottom","Left"],bt=function(e,t){e=t||e;return"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Ot=ot.access=function(e,t,i,r,n,o,s){var a=0,l=e.length,u=null==i;if("object"===ot.type(i)){n=!0;for(a in i)ot.access(e,t,a,i[a],!0,o,s)}else if(void 0!==r){n=!0;ot.isFunction(r)||(s=!0);if(u)if(s){t.call(e,r);t=null}else{u=t;t=function(e,t,i){return u.call(ot(e),i)}}if(t)for(;l>a;a++)t(e[a],i,s?r:r.call(e[a],a,t(e[a],i)))}return n?e:u?t.call(e):l?t(e[0],i):o},Pt=/^(?:checkbox|radio)$/i;(function(){var e=Et.createElement("input"),t=Et.createElement("div"),i=Et.createDocumentFragment();t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";rt.leadingWhitespace=3===t.firstChild.nodeType;rt.tbody=!t.getElementsByTagName("tbody").length;rt.htmlSerialize=!!t.getElementsByTagName("link").length;rt.html5Clone="<:nav></:nav>"!==Et.createElement("nav").cloneNode(!0).outerHTML;e.type="checkbox";e.checked=!0;i.appendChild(e);rt.appendChecked=e.checked;t.innerHTML="<textarea>x</textarea>";rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue;i.appendChild(t);t.innerHTML="<input type='radio' checked='checked' name='t'/>";rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked;rt.noCloneEvent=!0;if(t.attachEvent){t.attachEvent("onclick",function(){rt.noCloneEvent=!1});t.cloneNode(!0).click()}if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}})();(function(){var e,i,r=Et.createElement("div");for(e in{submit:!0,change:!0,focusin:!0}){i="on"+e;if(!(rt[e+"Bubbles"]=i in t)){r.setAttribute(i,"t");rt[e+"Bubbles"]=r.attributes[i].expando===!1}}r=null})();var Dt=/^(?:input|select|textarea)$/i,wt=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,Mt=/^(?:focusinfocus|focusoutblur)$/,kt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot._data(e);if(m){if(i.handler){l=i;i=l.handler;n=l.selector}i.guid||(i.guid=ot.guid++);(s=m.events)||(s=m.events={});if(!(p=m.handle)){p=m.handle=function(e){return typeof ot===yt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(p.elem,arguments)};p.elem=e}t=(t||"").match(Nt)||[""];a=t.length;for(;a--;){o=kt.exec(t[a])||[];f=E=o[1];h=(o[2]||"").split(".").sort();if(f){u=ot.event.special[f]||{};f=(n?u.delegateType:u.bindType)||f;u=ot.event.special[f]||{};c=ot.extend({type:f,origType:E,data:r,handler:i,guid:i.guid,selector:n,needsContext:n&&ot.expr.match.needsContext.test(n),namespace:h.join(".")},l);if(!(d=s[f])){d=s[f]=[];d.delegateCount=0;u.setup&&u.setup.call(e,r,h,p)!==!1||(e.addEventListener?e.addEventListener(f,p,!1):e.attachEvent&&e.attachEvent("on"+f,p))}if(u.add){u.add.call(e,c);c.handler.guid||(c.handler.guid=i.guid)}n?d.splice(d.delegateCount++,0,c):d.push(c);ot.event.global[f]=!0}}e=null}},remove:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot.hasData(e)&&ot._data(e);if(m&&(p=m.events)){t=(t||"").match(Nt)||[""];u=t.length;for(;u--;){a=kt.exec(t[u])||[];f=E=a[1];h=(a[2]||"").split(".").sort();if(f){c=ot.event.special[f]||{};f=(r?c.delegateType:c.bindType)||f;d=p[f]||[];a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)");l=o=d.length;for(;o--;){s=d[o];if(!(!n&&E!==s.origType||i&&i.guid!==s.guid||a&&!a.test(s.namespace)||r&&r!==s.selector&&("**"!==r||!s.selector))){d.splice(o,1);s.selector&&d.delegateCount--;c.remove&&c.remove.call(e,s)}}if(l&&!d.length){c.teardown&&c.teardown.call(e,h,m.handle)!==!1||ot.removeEvent(e,f,m.handle);delete p[f]}}else for(f in p)ot.event.remove(e,f+t[u],i,r,!0)}if(ot.isEmptyObject(p)){delete m.handle;ot._removeData(e,"events")}}},trigger:function(e,i,r,n){var o,s,a,l,u,p,c,d=[r||Et],f=it.call(e,"type")?e.type:e,h=it.call(e,"namespace")?e.namespace.split("."):[];a=p=r=r||Et;if(3!==r.nodeType&&8!==r.nodeType&&!Mt.test(f+ot.event.triggered)){if(f.indexOf(".")>=0){h=f.split(".");f=h.shift();h.sort()}s=f.indexOf(":")<0&&"on"+f;e=e[ot.expando]?e:new ot.Event(f,"object"==typeof e&&e);e.isTrigger=n?2:3;e.namespace=h.join(".");e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;e.result=void 0;e.target||(e.target=r);i=null==i?[e]:ot.makeArray(i,[e]);u=ot.event.special[f]||{};if(n||!u.trigger||u.trigger.apply(r,i)!==!1){if(!n&&!u.noBubble&&!ot.isWindow(r)){l=u.delegateType||f;Mt.test(l+f)||(a=a.parentNode);for(;a;a=a.parentNode){d.push(a);p=a}p===(r.ownerDocument||Et)&&d.push(p.defaultView||p.parentWindow||t)}c=0;for(;(a=d[c++])&&!e.isPropagationStopped();){e.type=c>1?l:u.bindType||f;o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle");o&&o.apply(a,i);o=s&&a[s];if(o&&o.apply&&ot.acceptData(a)){e.result=o.apply(a,i);e.result===!1&&e.preventDefault()}}e.type=f;if(!n&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),i)===!1)&&ot.acceptData(r)&&s&&r[f]&&!ot.isWindow(r)){p=r[s];p&&(r[s]=null);ot.event.triggered=f;try{r[f]()}catch(E){}ot.event.triggered=void 0;p&&(r[s]=p)}return e.result}}},dispatch:function(e){e=ot.event.fix(e);var t,i,r,n,o,s=[],a=$.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};a[0]=e;e.delegateTarget=this;if(!u.preDispatch||u.preDispatch.call(this,e)!==!1){s=ot.event.handlers.call(this,e,l);t=0;for(;(n=s[t++])&&!e.isPropagationStopped();){e.currentTarget=n.elem;o=0;for(;(r=n.handlers[o++])&&!e.isImmediatePropagationStopped();)if(!e.namespace_re||e.namespace_re.test(r.namespace)){e.handleObj=r;e.data=r.data;i=((ot.event.special[r.origType]||{}).handle||r.handler).apply(n.elem,a);if(void 0!==i&&(e.result=i)===!1){e.preventDefault();e.stopPropagation()}}}u.postDispatch&&u.postDispatch.call(this,e);return e.result}},handlers:function(e,t){var i,r,n,o,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){n=[];for(o=0;a>o;o++){r=t[o];i=r.selector+" ";void 0===n[i]&&(n[i]=r.needsContext?ot(i,this).index(l)>=0:ot.find(i,this,null,[l]).length);n[i]&&n.push(r)}n.length&&s.push({elem:l,handlers:n})}a<t.length&&s.push({elem:this,handlers:t.slice(a)});return s},fix:function(e){if(e[ot.expando])return e;var t,i,r,n=e.type,o=e,s=this.fixHooks[n];s||(this.fixHooks[n]=s=_t.test(n)?this.mouseHooks:wt.test(n)?this.keyHooks:{});r=s.props?this.props.concat(s.props):this.props;e=new ot.Event(o);t=r.length;for(;t--;){i=r[t];e[i]=o[i]}e.target||(e.target=o.srcElement||Et);3===e.target.nodeType&&(e.target=e.target.parentNode);e.metaKey=!!e.metaKey;return s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode);return e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var i,r,n,o=t.button,s=t.fromElement;if(null==e.pageX&&null!=t.clientX){r=e.target.ownerDocument||Et;n=r.documentElement;i=r.body;e.pageX=t.clientX+(n&&n.scrollLeft||i&&i.scrollLeft||0)-(n&&n.clientLeft||i&&i.clientLeft||0);e.pageY=t.clientY+(n&&n.scrollTop||i&&i.scrollTop||0)-(n&&n.clientTop||i&&i.clientTop||0)}!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?t.toElement:s);e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0);return e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==E()&&this.focus)try{this.focus();return!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){if(this===E()&&this.blur){this.blur();return!1}},delegateType:"focusout"},click:{trigger:function(){if(ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click){this.click();return!1}},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,i,r){var n=ot.extend(new ot.Event,i,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(n,null,t):ot.event.dispatch.call(t,n);n.isDefaultPrevented()&&i.preventDefault()}};ot.removeEvent=Et.removeEventListener?function(e,t,i){e.removeEventListener&&e.removeEventListener(t,i,!1)}:function(e,t,i){var r="on"+t;if(e.detachEvent){typeof e[r]===yt&&(e[r]=null);e.detachEvent(r,i)}};ot.Event=function(e,t){if(!(this instanceof ot.Event))return new ot.Event(e,t);if(e&&e.type){this.originalEvent=e;this.type=e.type;this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:h}else this.type=e;t&&ot.extend(this,t);this.timeStamp=e&&e.timeStamp||ot.now();this[ot.expando]=!0};ot.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f;if(e){e.stopPropagation&&e.stopPropagation();e.cancelBubble=!0}},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f;e&&e.stopImmediatePropagation&&e.stopImmediatePropagation();this.stopPropagation()}};ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var i,r=this,n=e.relatedTarget,o=e.handleObj;if(!n||n!==r&&!ot.contains(r,n)){e.type=o.origType;i=o.handler.apply(this,arguments);e.type=t}return i}}});rt.submitBubbles||(ot.event.special.submit={setup:function(){if(ot.nodeName(this,"form"))return!1;ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,i=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;if(i&&!ot._data(i,"submitBubbles")){ot.event.add(i,"submit._submit",function(e){e._submit_bubble=!0});ot._data(i,"submitBubbles",!0)}});return void 0},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0)}},teardown:function(){if(ot.nodeName(this,"form"))return!1;ot.event.remove(this,"._submit");return void 0}});rt.changeBubbles||(ot.event.special.change={setup:function(){if(Dt.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type){ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)});ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1);ot.event.simulate("change",this,e,!0)})}return!1}ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;if(Dt.test(t.nodeName)&&!ot._data(t,"changeBubbles")){ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)});ot._data(t,"changeBubbles",!0)}})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){ot.event.remove(this,"._change");return!Dt.test(this.nodeName)}});rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var i=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,n=ot._data(r,t);n||r.addEventListener(e,i,!0);ot._data(r,t,(n||0)+1)},teardown:function(){var r=this.ownerDocument||this,n=ot._data(r,t)-1;if(n)ot._data(r,t,n);else{r.removeEventListener(e,i,!0);ot._removeData(r,t)}}}});ot.fn.extend({on:function(e,t,i,r,n){var o,s;if("object"==typeof e){if("string"!=typeof t){i=i||t;t=void 0}for(o in e)this.on(o,t,i,e[o],n);return this}if(null==i&&null==r){r=t;i=t=void 0}else if(null==r)if("string"==typeof t){r=i;i=void 0}else{r=i;i=t;t=void 0}if(r===!1)r=h;else if(!r)return this;if(1===n){s=r;r=function(e){ot().off(e);return s.apply(this,arguments)};r.guid=s.guid||(s.guid=ot.guid++)}return this.each(function(){ot.event.add(this,e,r,i,t)})},one:function(e,t,i,r){return this.on(e,t,i,r,1)},off:function(e,t,i){var r,n;if(e&&e.preventDefault&&e.handleObj){r=e.handleObj;ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler);return this}if("object"==typeof e){for(n in e)this.off(n,t,e[n]);return this}if(t===!1||"function"==typeof t){i=t;t=void 0}i===!1&&(i=h);return this.each(function(){ot.event.remove(this,e,i,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var i=this[0];return i?ot.event.trigger(e,t,i,!0):void 0}});var Gt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Bt=/ jQuery\d+="(?:null|\d+)"/g,Ut=new RegExp("<(?:"+Gt+")[\\s/>]","i"),Vt=/^\s+/,Ft=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ht=/<([\w:]+)/,jt=/<tbody/i,Wt=/<|&#?\w+;/,qt=/<(?:script|style|link)/i,zt=/checked\s*(?:[^=]|=\s*.checked.)/i,Xt=/^$|\/(?:java|ecma)script/i,Yt=/^true\/(.*)/,Kt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,$t={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(Et),Zt=Qt.appendChild(Et.createElement("div"));$t.optgroup=$t.option;$t.tbody=$t.tfoot=$t.colgroup=$t.caption=$t.thead;$t.th=$t.td;ot.extend({clone:function(e,t,i){var r,n,o,s,a,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">"))o=e.cloneNode(!0);else{Zt.innerHTML=e.outerHTML;Zt.removeChild(o=Zt.firstChild)}if(!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e))){r=g(o);a=g(e);for(s=0;null!=(n=a[s]);++s)r[s]&&y(n,r[s])}if(t)if(i){a=a||g(e);r=r||g(o);for(s=0;null!=(n=a[s]);s++)I(n,r[s])}else I(e,o);r=g(o,"script");r.length>0&&L(r,!l&&g(e,"script"));r=a=n=null;return o},buildFragment:function(e,t,i,r){for(var n,o,s,a,l,u,p,c=e.length,d=m(t),f=[],h=0;c>h;h++){o=e[h];if(o||0===o)if("object"===ot.type(o))ot.merge(f,o.nodeType?[o]:o);else if(Wt.test(o)){a=a||d.appendChild(t.createElement("div"));l=(Ht.exec(o)||["",""])[1].toLowerCase();p=$t[l]||$t._default;a.innerHTML=p[1]+o.replace(Ft,"<$1></$2>")+p[2];n=p[0];for(;n--;)a=a.lastChild;!rt.leadingWhitespace&&Vt.test(o)&&f.push(t.createTextNode(Vt.exec(o)[0]));if(!rt.tbody){o="table"!==l||jt.test(o)?"<table>"!==p[1]||jt.test(o)?0:a:a.firstChild;n=o&&o.childNodes.length;for(;n--;)ot.nodeName(u=o.childNodes[n],"tbody")&&!u.childNodes.length&&o.removeChild(u)
}ot.merge(f,a.childNodes);a.textContent="";for(;a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else f.push(t.createTextNode(o))}a&&d.removeChild(a);rt.appendChecked||ot.grep(g(f,"input"),v);h=0;for(;o=f[h++];)if(!r||-1===ot.inArray(o,r)){s=ot.contains(o.ownerDocument,o);a=g(d.appendChild(o),"script");s&&L(a);if(i){n=0;for(;o=a[n++];)Xt.test(o.type||"")&&i.push(o)}}a=null;return d},cleanData:function(e,t){for(var i,r,n,o,s=0,a=ot.expando,l=ot.cache,u=rt.deleteExpando,p=ot.event.special;null!=(i=e[s]);s++)if(t||ot.acceptData(i)){n=i[a];o=n&&l[n];if(o){if(o.events)for(r in o.events)p[r]?ot.event.remove(i,r):ot.removeEvent(i,r,o.handle);if(l[n]){delete l[n];u?delete i[a]:typeof i.removeAttribute!==yt?i.removeAttribute(a):i[a]=null;K.push(n)}}}}});ot.fn.extend({text:function(e){return Ot(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||Et).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var i,r=e?ot.filter(e,this):this,n=0;null!=(i=r[n]);n++){t||1!==i.nodeType||ot.cleanData(g(i));if(i.parentNode){t&&ot.contains(i.ownerDocument,i)&&L(g(i,"script"));i.parentNode.removeChild(i)}}return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){1===e.nodeType&&ot.cleanData(g(e,!1));for(;e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){e=null==e?!1:e;t=null==t?e:t;return this.map(function(){return ot.clone(this,e,t)})},html:function(e){return Ot(this,function(e){var t=this[0]||{},i=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Bt,""):void 0;if(!("string"!=typeof e||qt.test(e)||!rt.htmlSerialize&&Ut.test(e)||!rt.leadingWhitespace&&Vt.test(e)||$t[(Ht.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Ft,"<$1></$2>");try{for(;r>i;i++){t=this[i]||{};if(1===t.nodeType){ot.cleanData(g(t,!1));t.innerHTML=e}}t=0}catch(n){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];this.domManip(arguments,function(t){e=this.parentNode;ot.cleanData(g(this));e&&e.replaceChild(t,this)});return e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=Q.apply([],e);var i,r,n,o,s,a,l=0,u=this.length,p=this,c=u-1,d=e[0],f=ot.isFunction(d);if(f||u>1&&"string"==typeof d&&!rt.checkClone&&zt.test(d))return this.each(function(i){var r=p.eq(i);f&&(e[0]=d.call(this,i,r.html()));r.domManip(e,t)});if(u){a=ot.buildFragment(e,this[0].ownerDocument,!1,this);i=a.firstChild;1===a.childNodes.length&&(a=i);if(i){o=ot.map(g(a,"script"),N);n=o.length;for(;u>l;l++){r=a;if(l!==c){r=ot.clone(r,!0,!0);n&&ot.merge(o,g(r,"script"))}t.call(this[l],r,l)}if(n){s=o[o.length-1].ownerDocument;ot.map(o,T);for(l=0;n>l;l++){r=o[l];Xt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(s,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Kt,"")))}}a=i=null}}return this}});ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var i,r=0,n=[],o=ot(e),s=o.length-1;s>=r;r++){i=r===s?this:this.clone(!0);ot(o[r])[t](i);Z.apply(n,i.get())}return this.pushStack(n)}});var Jt,ei={};(function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1";t.appendChild(Et.createElement("div")).style.width="5px";e=3!==t.offsetWidth}i.removeChild(r);return e}}})();var ti,ii,ri=/^margin/,ni=new RegExp("^("+Ct+")(?!px)[a-z%]+$","i"),oi=/^(top|right|bottom|left)$/;if(t.getComputedStyle){ti=function(e){return e.ownerDocument.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):t.getComputedStyle(e,null)};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i.getPropertyValue(t)||i[t]:void 0;if(i){""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t));if(ni.test(s)&&ri.test(t)){r=a.width;n=a.minWidth;o=a.maxWidth;a.minWidth=a.maxWidth=a.width=s;s=i.width;a.width=r;a.minWidth=n;a.maxWidth=o}}return void 0===s?s:s+""}}else if(Et.documentElement.currentStyle){ti=function(e){return e.currentStyle};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i[t]:void 0;null==s&&a&&a[t]&&(s=a[t]);if(ni.test(s)&&!oi.test(t)){r=a.left;n=e.runtimeStyle;o=n&&n.left;o&&(n.left=e.currentStyle.left);a.left="fontSize"===t?"1em":s;s=a.pixelLeft+"px";a.left=r;o&&(n.left=o)}return void 0===s?s:s+""||"auto"}}(function(){function e(){var e,i,r,n;i=Et.getElementsByTagName("body")[0];if(i&&i.style){e=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(e);e.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";o=s=!1;l=!0;if(t.getComputedStyle){o="1%"!==(t.getComputedStyle(e,null)||{}).top;s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width;n=e.appendChild(Et.createElement("div"));n.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";n.style.marginRight=n.style.width="0";e.style.width="1px";l=!parseFloat((t.getComputedStyle(n,null)||{}).marginRight);e.removeChild(n)}e.innerHTML="<table><tr><td></td><td>t</td></tr></table>";n=e.getElementsByTagName("td");n[0].style.cssText="margin:0;border:0;padding:0;display:none";a=0===n[0].offsetHeight;if(a){n[0].style.display="";n[1].style.display="none";a=0===n[0].offsetHeight}i.removeChild(r)}}var i,r,n,o,s,a,l;i=Et.createElement("div");i.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";n=i.getElementsByTagName("a")[0];r=n&&n.style;if(r){r.cssText="float:left;opacity:.5";rt.opacity="0.5"===r.opacity;rt.cssFloat=!!r.cssFloat;i.style.backgroundClip="content-box";i.cloneNode(!0).style.backgroundClip="";rt.clearCloneStyle="content-box"===i.style.backgroundClip;rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing;ot.extend(rt,{reliableHiddenOffsets:function(){null==a&&e();return a},boxSizingReliable:function(){null==s&&e();return s},pixelPosition:function(){null==o&&e();return o},reliableMarginRight:function(){null==l&&e();return l}})}})();ot.swap=function(e,t,i,r){var n,o,s={};for(o in t){s[o]=e.style[o];e.style[o]=t[o]}n=i.apply(e,r||[]);for(o in t)e.style[o]=s[o];return n};var si=/alpha\([^)]*\)/i,ai=/opacity\s*=\s*([^)]*)/,li=/^(none|table(?!-c[ea]).+)/,ui=new RegExp("^("+Ct+")(.*)$","i"),pi=new RegExp("^([+-])=("+Ct+")","i"),ci={position:"absolute",visibility:"hidden",display:"block"},di={letterSpacing:"0",fontWeight:"400"},fi=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var i=ii(e,"opacity");return""===i?"1":i}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,i,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var n,o,s,a=ot.camelCase(t),l=e.style;t=ot.cssProps[a]||(ot.cssProps[a]=R(l,a));s=ot.cssHooks[t]||ot.cssHooks[a];if(void 0===i)return s&&"get"in s&&void 0!==(n=s.get(e,!1,r))?n:l[t];o=typeof i;if("string"===o&&(n=pi.exec(i))){i=(n[1]+1)*n[2]+parseFloat(ot.css(e,t));o="number"}if(null!=i&&i===i){"number"!==o||ot.cssNumber[a]||(i+="px");rt.clearCloneStyle||""!==i||0!==t.indexOf("background")||(l[t]="inherit");if(!(s&&"set"in s&&void 0===(i=s.set(e,i,r))))try{l[t]=i}catch(u){}}}},css:function(e,t,i,r){var n,o,s,a=ot.camelCase(t);t=ot.cssProps[a]||(ot.cssProps[a]=R(e.style,a));s=ot.cssHooks[t]||ot.cssHooks[a];s&&"get"in s&&(o=s.get(e,!0,i));void 0===o&&(o=ii(e,t,r));"normal"===o&&t in di&&(o=di[t]);if(""===i||i){n=parseFloat(o);return i===!0||ot.isNumeric(n)?n||0:o}return o}});ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,i,r){return i?li.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,ci,function(){return D(e,t,r)}):D(e,t,r):void 0},set:function(e,i,r){var n=r&&ti(e);return O(e,i,r?P(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,n),n):0)}}});rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ai.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var i=e.style,r=e.currentStyle,n=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||i.filter||"";i.zoom=1;if((t>=1||""===t)&&""===ot.trim(o.replace(si,""))&&i.removeAttribute){i.removeAttribute("filter");if(""===t||r&&!r.filter)return}i.filter=si.test(o)?o.replace(si,n):o+" "+n}});ot.cssHooks.marginRight=C(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},ii,[e,"marginRight"]):void 0});ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(i){for(var r=0,n={},o="string"==typeof i?i.split(" "):[i];4>r;r++)n[e+Rt[r]+t]=o[r]||o[r-2]||o[0];return n}};ri.test(e)||(ot.cssHooks[e+t].set=O)});ot.fn.extend({css:function(e,t){return Ot(this,function(e,t,i){var r,n,o={},s=0;if(ot.isArray(t)){r=ti(e);n=t.length;for(;n>s;s++)o[t[s]]=ot.css(e,t[s],!1,r);return o}return void 0!==i?ot.style(e,t,i):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return b(this,!0)},hide:function(){return b(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){bt(this)?ot(this).show():ot(this).hide()})}});ot.Tween=w;w.prototype={constructor:w,init:function(e,t,i,r,n,o){this.elem=e;this.prop=i;this.easing=n||"swing";this.options=t;this.start=this.now=this.cur();this.end=r;this.unit=o||(ot.cssNumber[i]?"":"px")},cur:function(){var e=w.propHooks[this.prop];return e&&e.get?e.get(this):w.propHooks._default.get(this)},run:function(e){var t,i=w.propHooks[this.prop];this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e;this.now=(this.end-this.start)*t+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);i&&i.set?i.set(this):w.propHooks._default.set(this);return this}};w.prototype.init.prototype=w.prototype;w.propHooks={_default:{get:function(e){var t;if(null!=e.elem[e.prop]&&(!e.elem.style||null==e.elem.style[e.prop]))return e.elem[e.prop];t=ot.css(e.elem,e.prop,"");return t&&"auto"!==t?t:0},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}};w.propHooks.scrollTop=w.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}};ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}};ot.fx=w.prototype.init;ot.fx.step={};var hi,Ei,mi=/^(?:toggle|show|hide)$/,gi=new RegExp("^(?:([+-])=|)("+Ct+")([a-z%]*)$","i"),vi=/queueHooks$/,xi=[G],Ni={"*":[function(e,t){var i=this.createTween(e,t),r=i.cur(),n=gi.exec(t),o=n&&n[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+r)&&gi.exec(ot.css(i.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3];n=n||[];s=+r||1;do{a=a||".5";s/=a;ot.style(i.elem,e,s+o)}while(a!==(a=i.cur()/r)&&1!==a&&--l)}if(n){s=i.start=+s||+r||0;i.unit=o;i.end=n[1]?s+(n[1]+1)*n[2]:+n[2]}return i}]};ot.Animation=ot.extend(U,{tweener:function(e,t){if(ot.isFunction(e)){t=e;e=["*"]}else e=e.split(" ");for(var i,r=0,n=e.length;n>r;r++){i=e[r];Ni[i]=Ni[i]||[];Ni[i].unshift(t)}},prefilter:function(e,t){t?xi.unshift(e):xi.push(e)}});ot.speed=function(e,t,i){var r=e&&"object"==typeof e?ot.extend({},e):{complete:i||!i&&t||ot.isFunction(e)&&e,duration:e,easing:i&&t||t&&!ot.isFunction(t)&&t};r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default;(null==r.queue||r.queue===!0)&&(r.queue="fx");r.old=r.complete;r.complete=function(){ot.isFunction(r.old)&&r.old.call(this);r.queue&&ot.dequeue(this,r.queue)};return r};ot.fn.extend({fadeTo:function(e,t,i,r){return this.filter(bt).css("opacity",0).show().end().animate({opacity:t},e,i,r)},animate:function(e,t,i,r){var n=ot.isEmptyObject(e),o=ot.speed(t,i,r),s=function(){var t=U(this,ot.extend({},e),o);(n||ot._data(this,"finish"))&&t.stop(!0)};s.finish=s;return n||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,i){var r=function(e){var t=e.stop;delete e.stop;t(i)};if("string"!=typeof e){i=t;t=e;e=void 0}t&&e!==!1&&this.queue(e||"fx",[]);return this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=ot.timers,s=ot._data(this);if(n)s[n]&&s[n].stop&&r(s[n]);else for(n in s)s[n]&&s[n].stop&&vi.test(n)&&r(s[n]);for(n=o.length;n--;)if(o[n].elem===this&&(null==e||o[n].queue===e)){o[n].anim.stop(i);t=!1;o.splice(n,1)}(t||!i)&&ot.dequeue(this,e)})},finish:function(e){e!==!1&&(e=e||"fx");return this.each(function(){var t,i=ot._data(this),r=i[e+"queue"],n=i[e+"queueHooks"],o=ot.timers,s=r?r.length:0;i.finish=!0;ot.queue(this,e,[]);n&&n.stop&&n.stop.call(this,!0);for(t=o.length;t--;)if(o[t].elem===this&&o[t].queue===e){o[t].anim.stop(!0);o.splice(t,1)}for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete i.finish})}});ot.each(["toggle","show","hide"],function(e,t){var i=ot.fn[t];ot.fn[t]=function(e,r,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(M(t,!0),e,r,n)}});ot.each({slideDown:M("show"),slideUp:M("hide"),slideToggle:M("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,i,r){return this.animate(t,e,i,r)}});ot.timers=[];ot.fx.tick=function(){var e,t=ot.timers,i=0;hi=ot.now();for(;i<t.length;i++){e=t[i];e()||t[i]!==e||t.splice(i--,1)}t.length||ot.fx.stop();hi=void 0};ot.fx.timer=function(e){ot.timers.push(e);e()?ot.fx.start():ot.timers.pop()};ot.fx.interval=13;ot.fx.start=function(){Ei||(Ei=setInterval(ot.fx.tick,ot.fx.interval))};ot.fx.stop=function(){clearInterval(Ei);Ei=null};ot.fx.speeds={slow:600,fast:200,_default:400};ot.fn.delay=function(e,t){e=ot.fx?ot.fx.speeds[e]||e:e;t=t||"fx";return this.queue(t,function(t,i){var r=setTimeout(t,e);i.stop=function(){clearTimeout(r)}})};(function(){var e,t,i,r,n;t=Et.createElement("div");t.setAttribute("className","t");t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";r=t.getElementsByTagName("a")[0];i=Et.createElement("select");n=i.appendChild(Et.createElement("option"));e=t.getElementsByTagName("input")[0];r.style.cssText="top:1px";rt.getSetAttribute="t"!==t.className;rt.style=/top/.test(r.getAttribute("style"));rt.hrefNormalized="/a"===r.getAttribute("href");rt.checkOn=!!e.value;rt.optSelected=n.selected;rt.enctype=!!Et.createElement("form").enctype;i.disabled=!0;rt.optDisabled=!n.disabled;e=Et.createElement("input");e.setAttribute("value","");rt.input=""===e.getAttribute("value");e.value="t";e.setAttribute("type","radio");rt.radioValue="t"===e.value})();var Ti=/\r/g;ot.fn.extend({val:function(e){var t,i,r,n=this[0];if(arguments.length){r=ot.isFunction(e);return this.each(function(i){var n;if(1===this.nodeType){n=r?e.call(this,i,ot(this).val()):e;null==n?n="":"number"==typeof n?n+="":ot.isArray(n)&&(n=ot.map(n,function(e){return null==e?"":e+""}));t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()];t&&"set"in t&&void 0!==t.set(this,n,"value")||(this.value=n)}})}if(n){t=ot.valHooks[n.type]||ot.valHooks[n.nodeName.toLowerCase()];if(t&&"get"in t&&void 0!==(i=t.get(n,"value")))return i;i=n.value;return"string"==typeof i?i.replace(Ti,""):null==i?"":i}}});ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(var t,i,r=e.options,n=e.selectedIndex,o="select-one"===e.type||0>n,s=o?null:[],a=o?n+1:r.length,l=0>n?a:o?n:0;a>l;l++){i=r[l];if(!(!i.selected&&l!==n||(rt.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&ot.nodeName(i.parentNode,"optgroup"))){t=ot(i).val();if(o)return t;s.push(t)}}return s},set:function(e,t){for(var i,r,n=e.options,o=ot.makeArray(t),s=n.length;s--;){r=n[s];if(ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=i=!0}catch(a){r.scrollHeight}else r.selected=!1}i||(e.selectedIndex=-1);return n}}}});ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}};rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Li,Ii,yi=ot.expr.attrHandle,Ai=/^(?:checked|selected)$/i,Si=rt.getSetAttribute,Ci=rt.input;ot.fn.extend({attr:function(e,t){return Ot(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e)})}});ot.extend({attr:function(e,t,i){var r,n,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o){if(typeof e.getAttribute===yt)return ot.prop(e,t,i);if(1!==o||!ot.isXMLDoc(e)){t=t.toLowerCase();r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Ii:Li)}if(void 0===i){if(r&&"get"in r&&null!==(n=r.get(e,t)))return n;n=ot.find.attr(e,t);return null==n?void 0:n}if(null!==i){if(r&&"set"in r&&void 0!==(n=r.set(e,i,t)))return n;e.setAttribute(t,i+"");return i}ot.removeAttr(e,t)}},removeAttr:function(e,t){var i,r,n=0,o=t&&t.match(Nt);if(o&&1===e.nodeType)for(;i=o[n++];){r=ot.propFix[i]||i;ot.expr.match.bool.test(i)?Ci&&Si||!Ai.test(i)?e[r]=!1:e[ot.camelCase("default-"+i)]=e[r]=!1:ot.attr(e,i,"");e.removeAttribute(Si?i:r)}},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var i=e.value;e.setAttribute("type",t);i&&(e.value=i);return t}}}}});Ii={set:function(e,t,i){t===!1?ot.removeAttr(e,i):Ci&&Si||!Ai.test(i)?e.setAttribute(!Si&&ot.propFix[i]||i,i):e[ot.camelCase("default-"+i)]=e[i]=!0;return i}};ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var i=yi[t]||ot.find.attr;yi[t]=Ci&&Si||!Ai.test(t)?function(e,t,r){var n,o;if(!r){o=yi[t];yi[t]=n;n=null!=i(e,t,r)?t.toLowerCase():null;yi[t]=o}return n}:function(e,t,i){return i?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}});Ci&&Si||(ot.attrHooks.value={set:function(e,t,i){if(!ot.nodeName(e,"input"))return Li&&Li.set(e,t,i);e.defaultValue=t;return void 0}});if(!Si){Li={set:function(e,t,i){var r=e.getAttributeNode(i);r||e.setAttributeNode(r=e.ownerDocument.createAttribute(i));r.value=t+="";return"value"===i||t===e.getAttribute(i)?t:void 0}};yi.id=yi.name=yi.coords=function(e,t,i){var r;return i?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null};ot.valHooks.button={get:function(e,t){var i=e.getAttributeNode(t);return i&&i.specified?i.value:void 0},set:Li.set};ot.attrHooks.contenteditable={set:function(e,t,i){Li.set(e,""===t?!1:t,i)}};ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,i){if(""===i){e.setAttribute(t,"auto");return i}}}})}rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Ri=/^(?:input|select|textarea|button|object)$/i,bi=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Ot(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){e=ot.propFix[e]||e;return this.each(function(){try{this[e]=void 0;delete this[e]}catch(t){}})}});ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,i){var r,n,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s){o=1!==s||!ot.isXMLDoc(e);if(o){t=ot.propFix[t]||t;n=ot.propHooks[t]}return void 0!==i?n&&"set"in n&&void 0!==(r=n.set(e,i,t))?r:e[t]=i:n&&"get"in n&&null!==(r=n.get(e,t))?r:e[t]}},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Ri.test(e.nodeName)||bi.test(e.nodeName)&&e.href?0:-1}}}});rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}});rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;if(t){t.selectedIndex;t.parentNode&&t.parentNode.selectedIndex}return null}});ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this});rt.enctype||(ot.propFix.enctype="encoding");var Oi=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):" ");if(r){o=0;for(;n=t[o++];)r.indexOf(" "+n+" ")<0&&(r+=n+" ");s=ot.trim(r);i.className!==s&&(i.className=s)}}}return this},removeClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):"");if(r){o=0;for(;n=t[o++];)for(;r.indexOf(" "+n+" ")>=0;)r=r.replace(" "+n+" "," ");s=e?ot.trim(r):"";i.className!==s&&(i.className=s)}}}return this},toggleClass:function(e,t){var i=typeof e;return"boolean"==typeof t&&"string"===i?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(i){ot(this).toggleClass(e.call(this,i,this.className,t),t)}:function(){if("string"===i)for(var t,r=0,n=ot(this),o=e.match(Nt)||[];t=o[r++];)n.hasClass(t)?n.removeClass(t):n.addClass(t);else if(i===yt||"boolean"===i){this.className&&ot._data(this,"__className__",this.className);this.className=this.className||e===!1?"":ot._data(this,"__className__")||""}})},hasClass:function(e){for(var t=" "+e+" ",i=0,r=this.length;r>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(Oi," ").indexOf(t)>=0)return!0;return!1}});ot.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ot.fn[t]=function(e,i){return arguments.length>0?this.on(t,null,e,i):this.trigger(t)}});ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,i){return this.on(e,null,t,i)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,i,r){return this.on(t,e,i,r)},undelegate:function(e,t,i){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",i)}});var Pi=ot.now(),Di=/\?/,wi=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var i,r=null,n=ot.trim(e+"");return n&&!ot.trim(n.replace(wi,function(e,t,n,o){i&&t&&(r=0);if(0===r)return e;i=n||t;r+=!o-!n;return""}))?Function("return "+n)():ot.error("Invalid JSON: "+e)};ot.parseXML=function(e){var i,r;if(!e||"string"!=typeof e)return null;try{if(t.DOMParser){r=new DOMParser;i=r.parseFromString(e,"text/xml")}else{i=new ActiveXObject("Microsoft.XMLDOM");i.async="false";i.loadXML(e)}}catch(n){i=void 0}i&&i.documentElement&&!i.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e);return i};var _i,Mi,ki=/#.*$/,Gi=/([?&])_=[^&]*/,Bi=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ui=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vi=/^(?:GET|HEAD)$/,Fi=/^\/\//,Hi=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,ji={},Wi={},qi="*/".concat("*");try{Mi=location.href}catch(zi){Mi=Et.createElement("a");Mi.href="";Mi=Mi.href}_i=Hi.exec(Mi.toLowerCase())||[];ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mi,type:"GET",isLocal:Ui.test(_i[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qi,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?H(H(e,ot.ajaxSettings),t):H(ot.ajaxSettings,e)},ajaxPrefilter:V(ji),ajaxTransport:V(Wi),ajax:function(e,t){function i(e,t,i,r){var n,p,g,v,N,L=t;if(2!==x){x=2;a&&clearTimeout(a);u=void 0;s=r||"";T.readyState=e>0?4:0;n=e>=200&&300>e||304===e;i&&(v=j(c,T,i));v=W(c,v,T,n);if(n){if(c.ifModified){N=T.getResponseHeader("Last-Modified");N&&(ot.lastModified[o]=N);N=T.getResponseHeader("etag");N&&(ot.etag[o]=N)}if(204===e||"HEAD"===c.type)L="nocontent";else if(304===e)L="notmodified";else{L=v.state;p=v.data;g=v.error;n=!g}}else{g=L;if(e||!L){L="error";0>e&&(e=0)}}T.status=e;T.statusText=(t||L)+"";n?h.resolveWith(d,[p,L,T]):h.rejectWith(d,[T,L,g]);T.statusCode(m);m=void 0;l&&f.trigger(n?"ajaxSuccess":"ajaxError",[T,c,n?p:g]);E.fireWith(d,[T,L]);if(l){f.trigger("ajaxComplete",[T,c]);--ot.active||ot.event.trigger("ajaxStop")}}}if("object"==typeof e){t=e;e=void 0}t=t||{};var r,n,o,s,a,l,u,p,c=ot.ajaxSetup({},t),d=c.context||c,f=c.context&&(d.nodeType||d.jquery)?ot(d):ot.event,h=ot.Deferred(),E=ot.Callbacks("once memory"),m=c.statusCode||{},g={},v={},x=0,N="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!p){p={};for(;t=Bi.exec(s);)p[t[1].toLowerCase()]=t[2]}t=p[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var i=e.toLowerCase();if(!x){e=v[i]=v[i]||e;g[e]=t}return this},overrideMimeType:function(e){x||(c.mimeType=e);return this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||N;u&&u.abort(t);i(0,t);return this}};h.promise(T).complete=E.add;T.success=T.done;T.error=T.fail;c.url=((e||c.url||Mi)+"").replace(ki,"").replace(Fi,_i[1]+"//");c.type=t.method||t.type||c.method||c.type;c.dataTypes=ot.trim(c.dataType||"*").toLowerCase().match(Nt)||[""];if(null==c.crossDomain){r=Hi.exec(c.url.toLowerCase());c.crossDomain=!(!r||r[1]===_i[1]&&r[2]===_i[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(_i[3]||("http:"===_i[1]?"80":"443")))}c.data&&c.processData&&"string"!=typeof c.data&&(c.data=ot.param(c.data,c.traditional));F(ji,c,t,T);if(2===x)return T;l=ot.event&&c.global;l&&0===ot.active++&&ot.event.trigger("ajaxStart");c.type=c.type.toUpperCase();c.hasContent=!Vi.test(c.type);o=c.url;if(!c.hasContent){if(c.data){o=c.url+=(Di.test(o)?"&":"?")+c.data;delete c.data}c.cache===!1&&(c.url=Gi.test(o)?o.replace(Gi,"$1_="+Pi++):o+(Di.test(o)?"&":"?")+"_="+Pi++)}if(c.ifModified){ot.lastModified[o]&&T.setRequestHeader("If-Modified-Since",ot.lastModified[o]);ot.etag[o]&&T.setRequestHeader("If-None-Match",ot.etag[o])}(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType);T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+qi+"; q=0.01":""):c.accepts["*"]);for(n in c.headers)T.setRequestHeader(n,c.headers[n]);if(c.beforeSend&&(c.beforeSend.call(d,T,c)===!1||2===x))return T.abort();N="abort";for(n in{success:1,error:1,complete:1})T[n](c[n]);u=F(Wi,c,t,T);if(u){T.readyState=1;l&&f.trigger("ajaxSend",[T,c]);c.async&&c.timeout>0&&(a=setTimeout(function(){T.abort("timeout")},c.timeout));try{x=1;u.send(g,i)}catch(L){if(!(2>x))throw L;i(-1,L)}}else i(-1,"No Transport");return T},getJSON:function(e,t,i){return ot.get(e,t,i,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}});ot.each(["get","post"],function(e,t){ot[t]=function(e,i,r,n){if(ot.isFunction(i)){n=n||r;r=i;i=void 0}return ot.ajax({url:e,type:t,dataType:n,data:i,success:r})}});ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})};ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]);t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),i=t.contents();i.length?i.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(i){ot(this).wrapAll(t?e.call(this,i):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}});ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))};ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xi=/%20/g,Yi=/\[\]$/,Ki=/\r?\n/g,$i=/^(?:submit|button|image|reset|file)$/i,Qi=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var i,r=[],n=function(e,t){t=ot.isFunction(t)?t():null==t?"":t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional);if(ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){n(this.name,this.value)});else for(i in e)q(i,e[i],t,n);return r.join("&").replace(Xi,"+")};ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qi.test(this.nodeName)&&!$i.test(e)&&(this.checked||!Pt.test(e))}).map(function(e,t){var i=ot(this).val();return null==i?null:ot.isArray(i)?ot.map(i,function(e){return{name:t.name,value:e.replace(Ki,"\r\n")}}):{name:t.name,value:i.replace(Ki,"\r\n")}}).get()}});ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&z()||X()}:z;var Zi=0,Ji={},er=ot.ajaxSettings.xhr();t.attachEvent&&t.attachEvent("onunload",function(){for(var e in Ji)Ji[e](void 0,!0)});rt.cors=!!er&&"withCredentials"in er;er=rt.ajax=!!er;er&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(i,r){var n,o=e.xhr(),s=++Zi;o.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields)for(n in e.xhrFields)o[n]=e.xhrFields[n];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType);e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(n in i)void 0!==i[n]&&o.setRequestHeader(n,i[n]+"");o.send(e.hasContent&&e.data||null);t=function(i,n){var a,l,u;if(t&&(n||4===o.readyState)){delete Ji[s];t=void 0;o.onreadystatechange=ot.noop;if(n)4!==o.readyState&&o.abort();else{u={};a=o.status;"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText
}catch(p){l=""}a||!e.isLocal||e.crossDomain?1223===a&&(a=204):a=u.text?200:404}}u&&r(a,l,u,o.getAllResponseHeaders())};e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Ji[s]=t:t()},abort:function(){t&&t(void 0,!0)}}}});ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){ot.globalEval(e);return e}}});ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1);if(e.crossDomain){e.type="GET";e.global=!1}});ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,i=Et.head||ot("head")[0]||Et.documentElement;return{send:function(r,n){t=Et.createElement("script");t.async=!0;e.scriptCharset&&(t.charset=e.scriptCharset);t.src=e.url;t.onload=t.onreadystatechange=function(e,i){if(i||!t.readyState||/loaded|complete/.test(t.readyState)){t.onload=t.onreadystatechange=null;t.parentNode&&t.parentNode.removeChild(t);t=null;i||n(200,"success")}};i.insertBefore(t,i.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],ir=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||ot.expando+"_"+Pi++;this[e]=!0;return e}});ot.ajaxPrefilter("json jsonp",function(e,i,r){var n,o,s,a=e.jsonp!==!1&&(ir.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&ir.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0]){n=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback;a?e[a]=e[a].replace(ir,"$1"+n):e.jsonp!==!1&&(e.url+=(Di.test(e.url)?"&":"?")+e.jsonp+"="+n);e.converters["script json"]=function(){s||ot.error(n+" was not called");return s[0]};e.dataTypes[0]="json";o=t[n];t[n]=function(){s=arguments};r.always(function(){t[n]=o;if(e[n]){e.jsonpCallback=i.jsonpCallback;tr.push(n)}s&&ot.isFunction(o)&&o(s[0]);s=o=void 0});return"script"}});ot.parseHTML=function(e,t,i){if(!e||"string"!=typeof e)return null;if("boolean"==typeof t){i=t;t=!1}t=t||Et;var r=dt.exec(e),n=!i&&[];if(r)return[t.createElement(r[1])];r=ot.buildFragment([e],t,n);n&&n.length&&ot(n).remove();return ot.merge([],r.childNodes)};var rr=ot.fn.load;ot.fn.load=function(e,t,i){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,n,o,s=this,a=e.indexOf(" ");if(a>=0){r=ot.trim(e.slice(a,e.length));e=e.slice(0,a)}if(ot.isFunction(t)){i=t;t=void 0}else t&&"object"==typeof t&&(o="POST");s.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){n=arguments;s.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(i&&function(e,t){s.each(i,n||[e.responseText,t,e])});return this};ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}});ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var nr=t.document.documentElement;ot.offset={setOffset:function(e,t,i){var r,n,o,s,a,l,u,p=ot.css(e,"position"),c=ot(e),d={};"static"===p&&(e.style.position="relative");a=c.offset();o=ot.css(e,"top");l=ot.css(e,"left");u=("absolute"===p||"fixed"===p)&&ot.inArray("auto",[o,l])>-1;if(u){r=c.position();s=r.top;n=r.left}else{s=parseFloat(o)||0;n=parseFloat(l)||0}ot.isFunction(t)&&(t=t.call(e,i,a));null!=t.top&&(d.top=t.top-a.top+s);null!=t.left&&(d.left=t.left-a.left+n);"using"in t?t.using.call(e,d):c.css(d)}};ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,i,r={top:0,left:0},n=this[0],o=n&&n.ownerDocument;if(o){t=o.documentElement;if(!ot.contains(t,n))return r;typeof n.getBoundingClientRect!==yt&&(r=n.getBoundingClientRect());i=Y(o);return{top:r.top+(i.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(i.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}}},position:function(){if(this[0]){var e,t,i={top:0,left:0},r=this[0];if("fixed"===ot.css(r,"position"))t=r.getBoundingClientRect();else{e=this.offsetParent();t=this.offset();ot.nodeName(e[0],"html")||(i=e.offset());i.top+=ot.css(e[0],"borderTopWidth",!0);i.left+=ot.css(e[0],"borderLeftWidth",!0)}return{top:t.top-i.top-ot.css(r,"marginTop",!0),left:t.left-i.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||nr;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||nr})}});ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var i=/Y/.test(t);ot.fn[e]=function(r){return Ot(this,function(e,r,n){var o=Y(e);if(void 0===n)return o?t in o?o[t]:o.document.documentElement[r]:e[r];o?o.scrollTo(i?ot(o).scrollLeft():n,i?n:ot(o).scrollTop()):e[r]=n;return void 0},e,r,arguments.length,null)}});ot.each(["top","left"],function(e,t){ot.cssHooks[t]=C(rt.pixelPosition,function(e,i){if(i){i=ii(e,t);return ni.test(i)?ot(e).position()[t]+"px":i}})});ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(i,r){ot.fn[r]=function(r,n){var o=arguments.length&&(i||"boolean"!=typeof r),s=i||(r===!0||n===!0?"margin":"border");return Ot(this,function(t,i,r){var n;if(ot.isWindow(t))return t.document.documentElement["client"+e];if(9===t.nodeType){n=t.documentElement;return Math.max(t.body["scroll"+e],n["scroll"+e],t.body["offset"+e],n["offset"+e],n["client"+e])}return void 0===r?ot.css(t,i,s):ot.style(t,i,r,s)},t,o?r:void 0,o,null)}})});ot.fn.size=function(){return this.length};ot.fn.andSelf=ot.fn.addBack;"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var or=t.jQuery,sr=t.$;ot.noConflict=function(e){t.$===ot&&(t.$=sr);e&&t.jQuery===ot&&(t.jQuery=or);return ot};typeof i===yt&&(t.jQuery=t.$=ot);return ot})},{}],16:[function(t,i){(function(t){function r(){try{return l in t&&t[l]}catch(e){return!1}}function n(e){return e.replace(/^d/,"___$&").replace(h,"___")}var o,s={},a=t.document,l="localStorage",u="script";s.disabled=!1;s.version="1.3.17";s.set=function(){};s.get=function(){};s.has=function(e){return void 0!==s.get(e)};s.remove=function(){};s.clear=function(){};s.transact=function(e,t,i){if(null==i){i=t;t=null}null==t&&(t={});var r=s.get(e,t);i(r);s.set(e,r)};s.getAll=function(){};s.forEach=function(){};s.serialize=function(e){return JSON.stringify(e)};s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}};if(r()){o=t[l];s.set=function(e,t){if(void 0===t)return s.remove(e);o.setItem(e,s.serialize(t));return t};s.get=function(e,t){var i=s.deserialize(o.getItem(e));return void 0===i?t:i};s.remove=function(e){o.removeItem(e)};s.clear=function(){o.clear()};s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=function(e){for(var t=0;t<o.length;t++){var i=o.key(t);e(i,s.get(i))}}}else if(a.documentElement.addBehavior){var p,c;try{c=new ActiveXObject("htmlfile");c.open();c.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');c.close();p=c.w.frames[0].document;o=p.createElement("div")}catch(d){o=a.createElement("div");p=a.body}var f=function(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(o);p.appendChild(o);o.addBehavior("#default#userData");o.load(l);var i=e.apply(s,t);p.removeChild(o);return i}},h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=f(function(e,t,i){t=n(t);if(void 0===i)return s.remove(t);e.setAttribute(t,s.serialize(i));e.save(l);return i});s.get=f(function(e,t,i){t=n(t);var r=s.deserialize(e.getAttribute(t));return void 0===r?i:r});s.remove=f(function(e,t){t=n(t);e.removeAttribute(t);e.save(l)});s.clear=f(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(l);for(var i,r=0;i=t[r];r++)e.removeAttribute(i.name);e.save(l)});s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=f(function(e,t){for(var i,r=e.XMLDocument.documentElement.attributes,n=0;i=r[n];++n)t(i.name,s.deserialize(e.getAttribute(i.name)))})}try{var E="__storejs__";s.set(E,E);s.get(E)!=E&&(s.disabled=!0);s.remove(E)}catch(d){s.disabled=!0}s.enabled=!s.disabled;"undefined"!=typeof i&&i.exports&&this.module!==i?i.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s})(Function("return this")())},{}],17:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],18:[function(e,t){window.console=window.console||{log:function(){}};t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":17,"./storage.js":19,"./svg.js":20}],19:[function(e,t){{var i=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,n){if(i.enabled&&e&&t){"string"==typeof n&&(n=r[n]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));i.set(e,{val:t,exp:n,time:(new Date).getTime()})}},remove:function(e){i.enabled&&e&&i.remove(e)},get:function(e){if(!i.enabled)return null;if(e){var t=i.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}return null}}}},{store:16}],20:[function(e,t){t.exports={draw:function(e,i){if(e){var r=t.exports.getElement(i);r&&(e.append?e.append(r):e.appendChild(r))}},getElement:function(e){if(e&&0==e.indexOf("<svg")){var t=new DOMParser,i=t.parseFromString(e,"text/xml"),r=i.documentElement,n=document.createElement("div");n.className="svgImg";n.appendChild(r);return n}return!1}}},{}],21:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.3.7",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasqe.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasqe.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],22:[function(e,t){"use strict";var i=e("jquery"),r=e("../utils.js"),n=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e,t){var a={},l={},u={};t.on("cursorActivity",function(){d(!0)});t.on("change",function(){var e=[];for(var r in a)a[r].is(":visible")&&e.push(a[r]);if(e.length>0){var n=i(t.getWrapperElement()).find(".CodeMirror-vscrollbar"),o=0;n.is(":visible")&&(o=n.outerWidth());e.forEach(function(e){e.css("right",o)})}});var p=function(e,i){u[e.name]=new o;for(var s=0;s<i.length;s++)u[e.name].insert(i[s]);var a=r.getPersistencyId(t,e.persistent);a&&n.storage.set(a,i,"month")},c=function(e,i){var o=l[e]=new i(t,e);o.name=e;if(o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&p(o,e)};if(o.get instanceof Array)s(o.get);else{var a=null,u=r.getPersistencyId(t,o.persistent);u&&(a=n.storage.get(u));a&&a.length>0?s(a):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},d=function(r){if(!t.somethingSelected()){var n=function(i){if(r&&(!i.autoShow||!i.bulk&&i.async))return!1;var n={closeCharacters:/(?=a)b/,completeSingle:!1};!i.bulk&&i.async&&(n.async=!0);{var o=function(e,t){return f(i,t)};e.showHint(t,o,n)}return!0};for(var o in l)if(-1!=i.inArray(o,t.options.autocompleters)){var s=l[o];if(s.isValidCompletionPosition)if(s.isValidCompletionPosition()){if(!s.callbacks||!s.callbacks.validPosition||s.callbacks.validPosition(t,s)!==!1){var a=n(s);if(a)break}}else s.callbacks&&s.callbacks.invalidPosition&&s.callbacks.invalidPosition(t,s)}}},f=function(e,i){var r=function(t){var i=t.autocompletionString||t.string,r=[];if(u[e.name])r=u[e.name].autoComplete(i);else if("function"==typeof e.get&&0==e.async)r=e.get(i);else if("object"==typeof e.get)for(var n=i.length,o=0;o<e.get.length;o++){var s=e.get[o];s.slice(0,n)==i&&r.push(s)}return h(r,e,t)},n=t.getCompleteToken();e.preProcessToken&&(n=e.preProcessToken(n));if(n){if(e.bulk||!e.async)return r(n);var o=function(t){i(h(t,e,n))};e.get(n,o)}},h=function(e,i,r){for(var n=[],o=0;o<e.length;o++){var a=e[o];i.postProcessToken&&(a=i.postProcessToken(r,a));n.push({text:a,displayText:a,hint:s})}var l=t.getCursor(),u={completionToken:r.string,list:n,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(i.callbacks)for(var p in i.callbacks)i.callbacks[p]&&t.on(u,p,i.callbacks[p]);return u};return{init:c,completers:l,notifications:{getEl:function(e){return i(a[e.name])},show:function(e,t){if(!t.autoshow){a[t.name]||(a[t.name]=i("<div class='completionNotification'></div>"));a[t.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(i(e.getWrapperElement()))}},hide:function(e,t){a[t.name]&&a[t.name].hide()}},autoComplete:d,getTrie:function(e){return"string"==typeof e?u[e]:u[e.name]}}};var s=function(e,t,i){i.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(i.text,t.from,t.to)}},{"../../lib/trie.js":4,"../utils.js":35,jquery:15,"yasgui-utils":18}],23:[function(e,t){"use strict";e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.indexOf("?"))return!1;var i=e.getCursor(),r=e.getPreviousNonWsToken(i.line,t);return"a"==r.string?!0:"rdf:type"==r.string?!0:"rdfs:domain"==r.string?!0:"rdfs:range"==r.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":26,"./utils.js":26,jquery:15}],24:[function(e,t){"use strict";var i=e("jquery"),r={"string-2":"prefixed",atom:"var"};t.exports=function(e,r){e.on("change",function(){t.exports.appendPrefixIfNeeded(e,r)});return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(e)},get:function(e,t){i.get("http://prefix.cc/popular/all.file.json",function(e){var i=[];for(var r in e)if("bif"!=r){var n=r+": <"+e[r]+">";i.push(n)}i.sort();t(i)})},preProcessToken:function(i){return t.exports.preprocessPrefixTokenForCompletion(e,i)},async:!0,bulk:!0,autoShow:!0,persistent:r}};t.exports.isValidCompletionPosition=function(e){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;"ws"!=r.type&&(r=e.getCompleteToken());if(0==!r.string.indexOf("a")&&-1==i.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var n=e.getPreviousNonWsToken(t.line,r);return n&&"PREFIX"==n.string.toUpperCase()?!0:!1};t.exports.preprocessPrefixTokenForCompletion=function(e,t){var i=e.getPreviousNonWsToken(e.getCursor().line,t);i&&i.string&&":"==i.string.slice(-1)&&(t={start:i.start,end:t.end,string:i.string+" "+t.string,state:t.state});return t};t.exports.appendPrefixIfNeeded=function(e,t){if(e.autocompleters.getTrie(t)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(t)){var i=e.getCursor(),n=e.getTokenAt(i);if("prefixed"==r[n.type]){var o=n.string.indexOf(":");if(-1!==o){var s=e.getPreviousNonWsToken(i.line,n).string.toUpperCase(),a=e.getTokenAt({line:i.line,ch:n.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var l=n.string.substring(0,o+1),u=e.getPrefixesFromQuery();if(null==u[l.slice(0,-1)]){var p=e.autocompleters.getTrie(t).autoComplete(l);p.length>0&&e.addPrefixes(p[0])}}}}}}},{jquery:15}],25:[function(e,t){"use strict";var i=e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(i.inArray("a",t.state.possibleCurrent)>=0)return!0;var r=e.getCursor(),n=e.getPreviousNonWsToken(r.line,t);return"rdfs:subPropertyOf"==n.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":26,"./utils.js":26,jquery:15}],26:[function(e,t){"use strict";var i=e("jquery"),r=(e("./utils.js"),e("yasgui-utils")),n=function(e,t){var i=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")){t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1);null!=i[t.tokenPrefix.slice(0,-1)]&&(t.tokenPrefixUri=i[t.tokenPrefix.slice(0,-1)])}t.autocompletionString=t.string.trim();if(0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in i)if(0==t.string.indexOf(r)){t.autocompletionString=i[r];t.autocompletionString+=t.string.substring(r.length+1);break}0==t.autocompletionString.indexOf("<")&&(t.autocompletionString=t.autocompletionString.substring(1));-1!==t.autocompletionString.indexOf(">",t.length-1)&&(t.autocompletionString=t.autocompletionString.substring(0,t.autocompletionString.length-1));return t},o=function(e,t,i){i=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+i.substring(t.tokenPrefixUri.length):"<"+i+">";return i},s=function(t,n,o,s){if(!o||!o.string||0==o.string.trim().length){t.autocompleters.notifications.getEl(n).empty().append("Nothing to autocomplete yet!");return!1}var a=50,l={q:o.autocompletionString,page:1};l.type="classes"==n.name?"class":"property";var u=[],p="",c=function(){p="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+i.param(l)};c();var d=function(){l.page++;c()},f=function(){i.get(p,function(e){for(var r=0;r<e.results.length;r++)u.push(i.isArray(e.results[r].uri)&&e.results[r].uri.length>0?e.results[r].uri[0]:e.results[r].uri);if(u.length<e.total_results&&u.length<a){d();f()}else{u.length>0?t.autocompleters.notifications.hide(t,n):t.autocompleters.notifications.getEl(n).text("0 matches found...");s(u)}}).fail(function(){t.autocompleters.notifications.getEl(n).empty().append("Failed fetching suggestions..")})};t.autocompleters.notifications.getEl(n).empty().append(i("<span>Fetchting autocompletions </span>")).append(i(r.svg.getElement(e("../imgs.js").loader)).addClass("notificationLoader"));f()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:n,postprocessResourceTokenForCompletion:o}},{"../imgs.js":29,"./utils.js":26,jquery:15,"yasgui-utils":18}],27:[function(e,t){"use strict";var i=e("jquery");t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());if("ws"!=t.type){t=e.getCompleteToken(t);if(t&&0==t.string.indexOf("?"))return!0}return!1},get:function(t){if(0==t.trim().length)return[];var r={};i(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var n=i(this).next(),o=n.attr("class");o&&n.attr("class").indexOf("cm-atom")>=0&&(e+=n.text());if(e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var n=[];for(var o in r)n.push(o);n.sort();return n},async:!1,bulk:!1,autoShow:!0}}},{jquery:15}],28:[function(e){var t=e("jquery"),i=e("./main.js");i.defaults=t.extend(!0,{},i.defaults,{mode:"sparql11",value:"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nSELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,lineWrapping:!0,foldGutter:{rangeFinder:i.fold.brace},gutters:["gutterErrorBar","CodeMirror-linenumbers","CodeMirror-foldgutter"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":i.autoComplete,"Cmd-Space":i.autoComplete,"Ctrl-D":i.deleteLine,"Ctrl-K":i.deleteLine,"Cmd-D":i.deleteLine,"Cmd-K":i.deleteLine,"Ctrl-/":i.commentLines,"Cmd-/":i.commentLines,"Ctrl-Alt-Down":i.copyLineDown,"Ctrl-Alt-Up":i.copyLineUp,"Cmd-Alt-Down":i.copyLineDown,"Cmd-Alt-Up":i.copyLineUp,"Shift-Ctrl-F":i.doAutoFormat,"Shift-Cmd-F":i.doAutoFormat,"Ctrl-]":i.indentMore,"Cmd-]":i.indentMore,"Ctrl-[":i.indentLess,"Cmd-[":i.indentLess,"Ctrl-S":i.storeQuery,"Cmd-S":i.storeQuery,"Ctrl-Enter":i.executeQuery,"Cmd-Enter":i.executeQuery,F11:function(e){e.setOption("fullScreen",!e.getOption("fullScreen"))},Esc:function(e){e.getOption("fullScreen")&&e.setOption("fullScreen",!1)}},cursorHeight:.9,createShareLink:i.createShareLink,consumeShareLink:i.consumeShareLink,persistent:function(e){return"yasqe_"+t(e.getWrapperElement()).closest("[id]").attr("id")+"_queryVal"},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})},{"./main.js":30,jquery:15}],29:[function(e,t){"use strict";t.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g ></g><g > <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="warning.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" inkscape:zoom="3.1936344" inkscape:cx="36.8135" inkscape:cy="36.9485" inkscape:window-x="2625" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /><g transform="translate(-2.995,-2.411)" /><g transform="translate(-2.995,-2.411)" ><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" inkscape:connector-curvature="0" /></g><path d="M 66.129381,65.903784 H 49.769875 c -1.64721,0 -2.889385,-0.581146 -3.498678,-1.63595 -0.609293,-1.055608 -0.491079,-2.422161 0.332391,-3.848223 l 8.179753,-14.167069 c 0.822934,-1.42633 1.9477,-2.211737 3.166018,-2.211737 1.218319,0 2.343086,0.785407 3.166019,2.211737 l 8.179751,14.167069 c 0.823472,1.426062 0.941686,2.792615 0.33239,3.848223 -0.609023,1.054804 -1.851197,1.63595 -3.498138,1.63595 z M 59.618815,60.91766 c 0,-0.850276 -0.68944,-1.539719 -1.539717,-1.539719 -0.850276,0 -1.539718,0.689443 -1.539718,1.539719 0,0.850277 0.689442,1.539718 1.539718,1.539718 0.850277,0 1.539717,-0.689441 1.539717,-1.539718 z m 0.04155,-9.265919 c 0,-0.873061 -0.707939,-1.580998 -1.580999,-1.580998 -0.873061,0 -1.580999,0.707937 -1.580999,1.580998 l 0.373403,5.610965 h 0.0051 c 0.05415,0.619747 0.568548,1.10761 1.202504,1.10761 0.586239,0 1.075443,-0.415756 1.188563,-0.968489 0.0092,-0.04476 0.0099,-0.09248 0.01392,-0.138854 h 0.01072 l 0.367776,-5.611232 z" inkscape:connector-curvature="0" style="fill:#aa8800" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g ></g><g > <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}
},{}],30:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var i=e("jquery"),r=e("codemirror"),n=e("./utils.js"),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/hint/show-hint.js");e("codemirror/addon/search/searchcursor.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/addon/runmode/runmode.js");e("codemirror/addon/display/fullscreen.js");e("../lib/flint.js");var a=t.exports=function(e,t){var n=i("<div>",{"class":"yasqe"}).appendTo(i(e));t=l(t);var o=u(r(n[0],t));d(o);return o},l=function(e){var t=i.extend(!0,{},a.defaults,e);return t},u=function(t){t.autocompleters=e("./autocompleters/autocompleterBase.js")(a,t);t.options.autocompleters&&t.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])});t.getCompleteToken=function(i,r){return e("./tokenUtils.js").getCompleteToken(t,i,r)};t.getPreviousNonWsToken=function(i,r){return e("./tokenUtils.js").getPreviousNonWsToken(t,i,r)};t.getNextNonWsToken=function(i,r){return e("./tokenUtils.js").getNextNonWsToken(t,i,r)};t.query=function(e){a.executeQuery(t,e)};t.getUrlArguments=function(e){return a.getUrlArguments(t,e)};t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)};t.addPrefixes=function(i){return e("./prefixUtils.js").addPrefixes(t,i)};t.removePrefixes=function(i){return e("./prefixUtils.js").removePrefixes(t,i)};t.getValueWithoutComments=function(){var e="";a.runMode(t.getValue(),"sparql11",function(t,i){"comment"!=i&&(e+=t)});return e};t.getQueryType=function(){return t.queryType};t.getQueryMode=function(){var e=t.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"};t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e;h(t)};t.enableCompleter=function(e){p(t.options,e);a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])};t.disableCompleter=function(e){c(t.options,e)};return t},p=function(e,t){e.autocompleters||(e.autocompleters=[]);e.autocompleters.push(t)},c=function(e,t){if("object"==typeof e.autocompleters){var r=i.inArray(t,e.autocompleters);if(r>=0){e.autocompleters.splice(r,1);c(e,t)}}},d=function(e){var t=n.getPersistencyId(e,e.options.persistent);if(t){var r=o.storage.get(t);r&&e.setValue(r)}a.drawButtons(e);e.on("blur",function(e){a.storeQuery(e)});e.on("change",function(e){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("changes",function(){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("cursorActivity",function(e){f(e)});e.prevQueryValid=!1;h(e);a.positionButtons(e);if(e.options.consumeShareLink){var s=i.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},f=function(e){e.cursor=i(".CodeMirror-cursor");e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(n.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},h=function(t,r){t.queryValid=!0;t.clearGutter("gutterErrorBar");for(var n=null,a=0;a<t.lineCount();++a){var l=!1;t.prevQueryValid||(l=!0);var u=t.getTokenAt({line:a,ch:t.getLine(a).length},l),n=u.state;t.queryType=n.queryType;if(0==n.OK){if(!t.options.syntaxErrorCheck){i(t.getWrapperElement).find(".sp-error").css("color","black");return}var p=o.svg.getElement(s.warning);n.possibleCurrent&&n.possibleCurrent.length>0&&e("./tooltip")(t,p,function(){var e=[];n.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+i("<div/>").text(t).html()+"</strong>")});return"This line is invalid. Expected: "+e.join(", ")});p.style.marginTop="2px";p.style.marginLeft="2px";p.className="parseErrorIcon";t.setGutterMarker(a,"gutterErrorBar",p);t.queryValid=!1;break}}t.prevQueryValid=t.queryValid;if(r&&null!=n&&void 0!=n.stack){var c=n.stack,d=n.stack.length;d>1?t.queryValid=!1:1==d&&"solutionModifier"!=c[0]&&"?limitOffsetClauses"!=c[0]&&"?offsetClause"!=c[0]&&(t.queryValid=!1)}};i.extend(a,r);a.Autocompleters={};a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t;p(a.defaults,e)};a.autoComplete=function(e){e.autocompleters.autoComplete(!1)};a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js"));a.registerAutocompleter("properties",e("./autocompleters/properties.js"));a.registerAutocompleter("classes",e("./autocompleters/classes.js"));a.registerAutocompleter("variables",e("./autocompleters/variables.js"));a.positionButtons=function(e){var t=i(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),r=0;t.is(":visible")&&(r=t.outerWidth());e.buttons.is(":visible")&&e.buttons.css("right",r+6)};a.createShareLink=function(e){var t=i.deparam(window.location.search.substring(1));t.query=e.getValue();return t};a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)};a.drawButtons=function(e){e.buttons=i("<div class='yasqe_buttons'></div>").appendTo(i(e.getWrapperElement()));if(e.options.createShareLink){var t=i(o.svg.getElement(s.share));t.click(function(r){r.stopPropagation();var n=i("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);i("html").click(function(){n&&n.remove()});n.click(function(e){e.stopPropagation()});var o=i("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+i.param(e.options.createShareLink(e)));o.focus(function(){var e=i(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});n.empty().append(o);var s=t.position();n.css("top",s.top+t.outerHeight()+"px").css("left",s.left+t.outerWidth()-n.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}var r=i("<div>",{"class":"fullscreenToggleBtns"}).append(i(o.svg.getElement(s.fullscreen)).addClass("yasqe_fullscreenBtn").attr("title","Set editor full screen").click(function(){e.setOption("fullScreen",!0)})).append(i(o.svg.getElement(s.smallscreen)).addClass("yasqe_smallscreenBtn").attr("title","Set editor to normale size").click(function(){e.setOption("fullScreen",!1)}));e.buttons.append(r);if(e.options.sparql.showQueryButton){i("<div>",{"class":"yasqe_queryButton"}).click(function(){if(i(this).hasClass("query_busy")){e.xhr&&e.xhr.abort();a.updateQueryButton(e)}else e.query()}).appendTo(e.buttons);a.updateQueryButton(e)}};var E={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var r=i(e.getWrapperElement()).find(".yasqe_queryButton");if(0!=r.length){if(!t){t="valid";e.queryValid===!1&&(t="error")}if(t!=e.queryStatus&&("busy"==t||"valid"==t||"error"==t)){r.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t);o.svg.draw(r,s[E[t]]);e.queryStatus=t}}};a.fromTextArea=function(e,t){t=l(t);var n=(i("<div>",{"class":"yasqe"}).insertBefore(i(e)).append(i(e)),u(r.fromTextArea(e,t)));d(n);return n};a.storeQuery=function(e){var t=n.getPersistencyId(e,e.options.persistent);t&&o.storage.set(t,e.getValue(),"month")};a.commentLines=function(e){for(var t=e.getCursor(!0).line,i=e.getCursor(!1).line,r=Math.min(t,i),n=Math.max(t,i),o=!0,s=r;n>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;n>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})};a.copyLineUp=function(e){var t=e.getCursor(),i=e.lineCount();e.replaceRange("\n",{line:i-1,ch:e.getLine(i-1).length});for(var r=i;r>t.line;r--){var n=e.getLine(r-1);e.replaceRange(n,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}};a.copyLineDown=function(e){a.copyLineUp(e);var t=e.getCursor();t.line++;e.setCursor(t)};a.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};m(e,e.getCursor(!0),t)}else{var i=e.lineCount(),r=e.getTextArea().value.length;m(e,{line:0,ch:0},{line:i,ch:r})}};var m=function(e,t,i){var r=e.indexFromPos(t),n=e.indexFromPos(i),o=g(e.getValue(),r,n);e.operation(function(){e.replaceRange(o,t,i);for(var n=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=n;s>=a;a++)e.indentLine(a,"smart")})},g=function(e,t,n){e=e.substring(t,n);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=i.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];r.runMode(e,"sparql11",function(e,t){c.push(t);var i=l(e,t);if(0!=i){if(1==i){u+=e+"\n";p=""}else{u+="\n"+e;p=e}c=[]}else{p+=e;u+=e}1==c.length&&"sp-ws"==c[0]&&(c=[])});return i.trim(u.replace(/\n\s*\n/g,"\n"))};e("./sparql.js"),e("./defaults.js");a.version={CodeMirror:r.version,YASQE:e("../package.json").version,jquery:i.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":2,"../lib/flint.js":3,"../package.json":21,"./autocompleters/autocompleterBase.js":22,"./autocompleters/classes.js":23,"./autocompleters/prefixes.js":24,"./autocompleters/properties.js":25,"./autocompleters/variables.js":27,"./defaults.js":28,"./imgs.js":29,"./prefixUtils.js":31,"./sparql.js":32,"./tokenUtils.js":33,"./tooltip":34,"./utils.js":35,codemirror:14,"codemirror/addon/display/fullscreen.js":5,"codemirror/addon/edit/matchbrackets.js":6,"codemirror/addon/fold/brace-fold.js":7,"codemirror/addon/fold/foldcode.js":8,"codemirror/addon/fold/foldgutter.js":9,"codemirror/addon/fold/xml-fold.js":10,"codemirror/addon/hint/show-hint.js":11,"codemirror/addon/runmode/runmode.js":12,"codemirror/addon/search/searchcursor.js":13,jquery:15,"yasgui-utils":18}],31:[function(e,t){"use strict";var i=function(e,t){var i=e.getPrefixesFromQuery();if("string"==typeof t)r(e,t);else for(var n in t)n in i||r(e,n+": <"+t[n]+">")},r=function(e,t){for(var i=null,r=0,n=e.lineCount(),o=0;n>o;o++){var a=e.getNextNonWsToken(o);if(null!=a&&("PREFIX"==a.string||"BASE"==a.string)){i=a;r=o}}if(null==i)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=s(e,r);e.replaceRange("\n"+l+"PREFIX "+t,{line:r})}},n=function(e,t){var i=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var r in t)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+r+":\\s*"+i("<"+t[r]+">")+"\\s*","ig"),""))},o=function(e){for(var t={},i=!0,r=function(n,s){if(i){s||(s=1);var a=e.getNextNonWsToken(o,s);if(a){-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(i=!1);if("PREFIX"==a.string.toUpperCase()){var l=e.getNextNonWsToken(o,a.end+1);if(l){var u=e.getNextNonWsToken(o,l.end+1);if(u){var p=u.string;0==p.indexOf("<")&&(p=p.substring(1));">"==p.slice(-1)&&(p=p.substring(0,p.length-1));t[l.string.slice(0,-1)]=p;r(n,u.end+1)}else r(n,l.end+1)}else r(n,a.end+1)}else r(n,a.end+1)}}},n=e.lineCount(),o=0;n>o&&i;o++)r(o);return t},s=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||"ws"!=r.type?"":r.string+s(e,t,r.end+1)};t.exports={addPrefixes:i,getPrefixesFromQuery:o,removePrefixes:n}},{}],32:[function(e){"use strict";var t=e("jquery"),i=e("./main.js");i.executeQuery=function(e,n){var o="function"==typeof n?n:null,s="object"==typeof n?n:{};e.options.sparql&&(s=t.extend({},e.options.sparql,s));s.handlers&&t.extend(!0,s.callbacks,s.handlers);if(s.endpoint&&0!=s.endpoint.length){var a={url:"function"==typeof s.endpoint?s.endpoint(e):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(e):s.requestMethod,headers:{Accept:r(e,s)}},l=!1;if(s.callbacks)for(var u in s.callbacks)if(s.callbacks[u]){l=!0;a[u]=s.callbacks[u]}a.data=e.getUrlArguments(s);if(l||o){o&&(a.complete=o);s.headers&&!t.isEmptyObject(s.headers)&&t.extend(a.headers,s.headers);i.updateQueryButton(e,"busy");var p=function(){i.updateQueryButton(e)};a.complete=a.complete?[p,a.complete]:p;e.xhr=t.ajax(a)}}};i.getUrlArguments=function(e,i){var r=e.getQueryMode(),n=[{name:e.getQueryMode(),value:e.getValue()}];if(i.namedGraphs&&i.namedGraphs.length>0)for(var o="query"==r?"named-graph-uri":"using-named-graph-uri ",s=0;s<i.namedGraphs.length;s++)n.push({name:o,value:i.namedGraphs[s]});if(i.defaultGraphs&&i.defaultGraphs.length>0)for(var o="query"==r?"default-graph-uri":"using-graph-uri ",s=0;s<i.defaultGraphs.length;s++)n.push({name:o,value:i.defaultGraphs[s]});i.args&&i.args.length>0&&t.merge(n,i.args);return n};var r=function(e,t){var i=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())i="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var r=e.getQueryType();i="DESCRIBE"==r||"CONSTRUCT"==r?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else i="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return i}},{"./main.js":30,jquery:15}],33:[function(e,t){"use strict";var i=function(e,t,r){r||(r=e.getCursor());t||(t=e.getTokenAt(r));var n=e.getTokenAt({line:r.line,ch:t.start});if(null!=n.type&&"ws"!=n.type&&null!=t.type&&"ws"!=t.type){t.start=n.start;t.string=n.string+t.string;return i(e,t,{line:r.line,ch:n.start})}if(null!=t.type&&"ws"==t.type){t.start=t.start+1;t.string=t.string.substring(1);return t}return t},r=function(e,t,i){var n=e.getTokenAt({line:t,ch:i.start});null!=n&&"ws"==n.type&&(n=r(e,t,n));return n},n=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||r.end<i?null:"ws"==r.type?n(e,t,r.end+1):r};t.exports={getPreviousNonWsToken:r,getCompleteToken:i,getNextNonWsToken:n}},{}],34:[function(e,t){"use strict";{var i=e("jquery");e("./utils.js")}t.exports=function(e,t,r){var n,t=i(t);t.hover(function(){"function"==typeof r&&(r=r());n=i("<div>").addClass("yasqe_tooltip").html(r).appendTo(t);o()},function(){i(".yasqe_tooltip").remove()});var o=function(){if(i(e.getWrapperElement()).offset().top>=n.offset().top){n.css("bottom","auto");n.css("top","26px")}}}},{"./utils.js":35,jquery:15}],35:[function(e,t){"use strict";var i=e("jquery"),r=function(e,t){var i=!1;try{void 0!==e[t]&&(i=!0)}catch(r){}return i},n=function(e,t){var i=null;t&&(i="string"==typeof t?t:t(e));return i},o=function(){function e(e){var t,r,n;t=i(e).offset();r=i(e).width();n=i(e).height();return[[t.left,t.left+r],[t.top,t.top+n]]}function t(e,t){var i,r;i=e[0]<t[0]?e:t;r=e[0]<t[0]?t:e;return i[1]>r[0]||i[0]===r[0]}return function(i,r){var n=e(i),o=e(r);return t(n[0],o[0])&&t(n[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:n,elementsOverlap:o}},{jquery:15}]},{},[1])(1)});
//# sourceMappingURL=yasqe.bundled.min.js.map |
src/modules/about-maizuo/community/index.js | skydaya/react-sell | /**
* Created by dllo on 17/8/29.
*/
import React from 'react'
import ReactDOM from 'react-dom'
import App from './app'
ReactDOM.render(
<App />,
document.getElementById('community')
) |
src/js/components/Drop/stories/Meter.js | grommet/grommet | import React, { useEffect, useRef, useState } from 'react';
import { Box, Drop, Meter } from 'grommet';
const align = { top: 'bottom', left: 'left' };
const TestDrop = () => {
const targetRef = useRef();
const [, setShowDrop] = useState(false);
useEffect(() => setShowDrop(true), []);
return (
// Uncomment <Grommet> lines when using outside of storybook
// <Grommet theme={...}>
<Box fill align="center" justify="center" pad="large">
<Meter
ref={targetRef}
size="small"
background="light-2"
values={[{ value: 20, color: 'brand' }]}
/>
{targetRef.current && (
<Drop
id="test-drop-with-svg"
plain
align={align}
target={targetRef.current}
>
<Box pad="large">target is an svg</Box>
</Drop>
)}
</Box>
// </Grommet>
);
};
export const SVGChild = () => <TestDrop />;
SVGChild.parameters = {
chromatic: { disable: true },
};
SVGChild.storyName = 'SVG child';
SVGChild.args = {
full: true,
};
export default {
title: 'Controls/Drop/SVG child',
};
|
examples/counter/containers/CounterApp.js | wescravens/redux-devtools | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/CounterActions';
class CounterApp extends Component {
render() {
const { counter, dispatch } = this.props;
return (
<Counter counter={counter}
{...bindActionCreators(CounterActions, dispatch)} />
);
}
}
function select(state) {
return {
counter: state.counter
};
}
export default connect(select)(CounterApp);
|
src/js/list/ListGroup.js | remobile/remobile | var React = require('react');
module.exports = React.createClass({
render() {
return (
<div className="list-group">
<ul>
{this.props.children}
</ul>
</div>
);
}
});
|
packages/wix-style-react/src/Breadcrumbs/test/Breadcrumbs.spec.js | wix/wix-style-react | import React from 'react';
import {
createRendererWithDriver,
createRendererWithUniDriver,
cleanup,
} from '../../../test/utils/react';
import breadcrumbsDriverFactory from '../Breadcrumbs.driver';
import breadcrumbsPrivateDriverFactory from './Breadcrumbs.private.driver';
import { breadcrumbsUniDriverFactory } from '../Breadcrumbs.uni.driver';
import Breadcrumbs from '../Breadcrumbs';
const items = [
{ id: 0, value: 'Option 1' },
{ id: 1, value: 'Option 2' },
];
let onClick;
describe('Breadcrumbs', () => {
describe('[sync]', () => {
runTests(createRendererWithDriver(breadcrumbsDriverFactory));
});
describe('[async]', () => {
runTests(createRendererWithUniDriver(breadcrumbsUniDriverFactory));
});
function runTests(render) {
beforeEach(() => {
onClick = jest.fn();
});
afterEach(() => cleanup());
it('should have correct text on each breadcrumb', async () => {
const { driver } = render(<Breadcrumbs {...{ onClick, items }} />);
expect(await driver.breadcrumbsLength()).toBe(items.length);
expect(await driver.breadcrumbContentAt(0)).toBe(items[0].value);
expect(await driver.breadcrumbContentAt(1)).toBe(items[1].value);
});
it('should call onClick callback on click with correct item', async () => {
const { driver } = render(<Breadcrumbs {...{ onClick, items }} />);
const itemIndex = 1;
await driver.clickBreadcrumbAt(itemIndex);
expect(onClick).toBeCalledWith({
id: items[itemIndex].id,
value: 'Option 2',
});
});
it('should get correct size from props', async () => {
const size = 'large';
const { driver } = render(<Breadcrumbs {...{ onClick, items, size }} />);
expect(await driver.isLarge()).toBe(true);
});
it('should use medium size as default', async () => {
const { driver } = render(<Breadcrumbs {...{ onClick, items }} />);
expect(await driver.isMedium()).toBe(true);
});
it('should get theme from props', async () => {
const theme = 'onWhiteBackground';
const { driver } = render(<Breadcrumbs {...{ onClick, items, theme }} />);
expect(await driver.isOnWhiteBackground()).toBe(true);
});
it('should use default theme gray background', async () => {
const { driver } = render(<Breadcrumbs {...{ onClick, items }} />);
expect(await driver.isOnGrayBackground()).toBe(true);
});
it('should get active id from props and have correct class', async () => {
const itemIndex = 1;
const { driver } = render(
<Breadcrumbs {...{ onClick, items, activeId: items[itemIndex].id }} />,
);
expect(await driver.getActiveItemId()).toBe(itemIndex);
});
it('should return null if not exists active id', async () => {
const { driver } = render(<Breadcrumbs {...{ onClick, items }} />);
expect(await driver.getActiveItemId()).toBe(null);
});
describe('item with link attribute', () => {
const linkItems = [
{ id: 0, value: 'Option 1', link: '//www.wix.com' },
{ id: 1, value: 'Option 2', link: '//www.facebook.com' },
];
it('should not have links if link attribute is not given', async () => {
const { driver } = render(<Breadcrumbs {...{ items }} />);
expect(await driver.isActiveLinkAt(0)).toBe(false);
expect(await driver.isActiveLinkAt(1)).toBe(false);
});
it('should be a link if no activeId is given', async () => {
const { driver } = render(<Breadcrumbs {...{ items: linkItems }} />);
expect(await driver.isActiveLinkAt(0)).toBe(true);
expect(await driver.isActiveLinkAt(1)).toBe(true);
});
it('should not be a link if it is the item with activeId', async () => {
const { driver } = render(
<Breadcrumbs {...{ items: linkItems, activeId: 0 }} />,
);
expect(await driver.isActiveLinkAt(0)).toBe(false);
expect(await driver.isActiveLinkAt(1)).toBe(true);
});
});
describe('customElement attribute', () => {
const customItems = [
{
id: 0,
value: 'Option 1',
customElement: <a href="//www.wix.com">Option 1</a>,
},
{
id: 1,
value: 'Option 2',
customElement: <a href="//www.facebook.com">Option 2</a>,
},
];
const customItemsWithLinks = [
{
id: 0,
value: 'value',
customElement: <a href="//www.wix.com">Custom value</a>,
link: 'www.bla.com',
},
];
it('should render the customElement when given', async () => {
const { driver } = render(<Breadcrumbs {...{ items: customItems }} />);
expect(await driver.breadcrumbsLength()).toBe(customItems.length);
expect(await driver.breadcrumbContentAt(0)).toBe(customItems[0].value);
expect(await driver.breadcrumbContentAt(1)).toBe(customItems[1].value);
});
it('should render the customElement even if link attribute is given', async () => {
const { driver } = render(
<Breadcrumbs {...{ items: customItemsWithLinks }} />,
);
expect(await driver.breadcrumbsLength()).toBe(
customItemsWithLinks.length,
);
expect(await driver.breadcrumbContentAt(0)).toBe('Custom value');
});
it('should render the value attribute of the item when this is the activeId', async () => {
const { driver } = render(
<Breadcrumbs {...{ items: customItemsWithLinks, activeId: 0 }} />,
);
expect(await driver.breadcrumbContentAt(0)).toBe(
customItemsWithLinks[0].value,
);
});
});
it('should have correct classNames', async () => {
const { driver } = render(<Breadcrumbs {...{ items }} />);
expect(await driver.getLabelClassList(0)).toMatch(/Text/);
});
}
describe('fullwidth', () => {
it('should be true when given only one item', async () => {
const render = createRendererWithDriver(breadcrumbsPrivateDriverFactory);
const items = [{ id: 0, value: 'Option 1' }];
const { driver } = render(<Breadcrumbs {...{ items }} />);
expect(await driver.isItemFullWidth()).toBe(true);
});
it('should be false when given multiple items', async () => {
const render = createRendererWithDriver(breadcrumbsPrivateDriverFactory);
const { driver } = render(<Breadcrumbs {...{ items }} />);
expect(await driver.isItemFullWidth()).toBe(false);
});
});
});
|
tests/routes/Projects/components/DeleteDialog.spec.js | prescottprue/devshare-site | import React from 'react'
import DeleteDialog from 'routes/Projects/components/DeleteDialog/DeleteDialog'
import { shallow } from 'enzyme'
describe.skip('(Projects:Component) DeleteDialog', () => {
let _component
beforeEach(() => {
_component = shallow(
<DeleteDialog
open={false}
name={'testDelete'}
onRequestClose={() => console.log('request close')}
/>
)
})
it('Renders Dialog', () => {
const dialog = _component.find('Dialog')
expect(dialog).to.exist
})
})
|
ajax/libs/forerunnerdb/1.3.304/fdb-legacy.js | jonathantneal/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind'),
Grid = _dereq_('../lib/Grid');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":10,"../lib/Highchart":11,"../lib/OldView":26,"../lib/OldView.Bind":25,"../lib/Overview":29,"../lib/Persist":31,"../lib/View":36}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
var sortKey;
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
for (sortKey in orderBy) {
if (orderBy.hasOwnProperty(sortKey)) {
this._keyArr.push({
key: sortKey,
dir: orderBy[sortKey]
});
}
}
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof obj[sortType.key];
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.dir === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.dir === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += obj[sortType.key];
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Shared":35}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (!(index instanceof Array)) {
// Convert the index object to an array of key val objects
index = this.keys(index);
}
}
return this.$super.call(this, index);
});
BinaryTree.prototype.keys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return true;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._index.length; i++) {
indexData = this._index[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._index.length; i++) {
indexData = this._index[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._index[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'key':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._key,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Shared":35}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = JSON.stringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
this._updateIncrement(doc, i, update[i]);
updated = true;
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = JSON.stringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (JSON.stringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
* @private
*/
Collection.prototype.deferEmit = function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.emit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = JSON.stringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = JSON.stringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = JSON.stringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; }
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
return new Path(query.substr(3, query.length - 3)).value(item)[0];
}
return new Path(query).value(item)[0];
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":7,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":28,"./Path":30,"./ReactorIO":34,"./Shared":35}],5:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function () {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":4,"./Shared":35}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
callback();
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":15,"./Overload":28,"./Shared":35}],7:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":15,"./Overload":28,"./Shared":35}],9:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
this.updateObject(this._data, update, query, options);
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function () {
if (!this.isDropped()) {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance.
* @func document
* @memberof Db
* @param {String} documentName The name of the document to create.
* @returns {*}
*/
Db.prototype.document = function (documentName) {
if (documentName) {
// Handle being passed an instance
if (documentName instanceof FdbDocument) {
if (documentName.state() !== 'droppped') {
return documentName;
} else {
documentName = documentName.name();
}
}
this._document = this._document || {};
this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this);
return this._document[documentName];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":4,"./Shared":35}],10:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function () {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener );
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
template: [
'<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">',
'<input type="search" class="form-control gridFilterSearch" placeholder="Search...">',
'<span class="input-group-btn">',
'<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',
'</span>',
'</li>',
'<li role="presentation" class="divider"></li>',
'<li role="presentation" data-val="$all">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox" checked> All',
'</a>',
'</li>',
'<li role="presentation" class="divider"></li>',
'{^{for options}}',
'<li role="presentation" data-link="data-val{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":34,"./Shared":35,"./View":36}],11:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
}
seriesData.push({
name: seriesName,
data: seriesValues
});
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () { self._changeListener.apply(self, arguments); });
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () { self.drop.apply(self, arguments); });
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if(typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy
);
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":28,"./Shared":35}],12:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":30,"./Shared":35}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":30,"./Shared":35}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":35}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":27,"./Shared":35}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Common;
Common = {
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return JSON.parse(JSON.stringify(data));
} else {
var i,
json = JSON.stringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(JSON.parse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":28}],19:[function(_dereq_,module,exports){
"use strict";
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
}
};
module.exports = Events;
},{"./Overload":28}],21:[function(_dereq_,module,exports){
"use strict";
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) {
return true;
} else if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
}
return -1;
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":28}],24:[function(_dereq_,module,exports){
"use strict";
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],25:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = this;
this._binds = [];
this._renderStart = 0;
this._renderEnd = 0;
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
_bindInsert: [],
_bindUpdate: [],
_bindRemove: [],
_bindUpsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100,
_bindInsert: 100,
_bindUpdate: 100,
_bindRemove: 100,
_bindUpsert: 100
};
this._deferTime = {
insert: 100,
update: 1,
remove: 1,
upsert: 1,
_bindInsert: 100,
_bindUpdate: 1,
_bindRemove: 1,
_bindUpsert: 1
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":35}],26:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
DbInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._oldViews = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":4,"./CollectionGroup":5,"./Shared":35}],27:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":30,"./Shared":35}],28:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],29:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
delete this._name;
this.emit('drop', this);
}
return true;
};
Db.prototype.overview = function (overviewName) {
if (overviewName) {
// Handle being passed an instance
if (overviewName instanceof Overview) {
return overviewName;
}
this._overview = this._overview || {};
this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this);
return this._overview[overviewName];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":4,"./Document":9,"./Shared":35}],30:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":35}],31:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
this._encodeSteps = [
this._encode
];
this._decodeSteps = [
this._decode
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
callback(false, val, {});
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
callback(false, val, {});
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = JSON.parse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = JSON.parse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + JSON.stringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) {
callback('No data handler or unrecognised data type.');
}
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '::' + this._name);
this._db.persist.drop(this._db._name + '::' + this._name + '::metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.apply(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '::' + this._name, function () {
self._db.persist.drop(self._db._name + '::' + self._name + '::metaData', callback);
});
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
}
// Call the original method
CollectionDrop.apply(this, callback);
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '::' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '::' + self._name + '::metaData', self.metaData(), function (err, data, metaStats) {
if (callback) {
callback(err, data, tableStats, metaStats);
}
});
} else {
if (callback) {
callback(err);
}
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) {
callback('Cannot save a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot save a collection with no assigned name!');
}
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '::' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '::' + self._name + '::metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) {
callback(err, tableStats, metaStats);
}
});
} else {
if (callback) {
callback(err);
}
}
});
} else {
if (callback) {
callback('Cannot load a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot load a collection with no assigned name!');
}
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Db.prototype.load = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
obj[index].load(loadCallback);
}
}
};
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Db.prototype.save = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
obj[index].save(saveCallback);
}
}
};
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":32,"./PersistCrypto":33,"./Shared":35,"async":37,"localforage":79}],32:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, JSON.stringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = JSON.parse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":35,"pako":81}],33:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype._jsonFormatter = {
stringify: function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return JSON.stringify(jsonObj);
},
parse: function (jsonStr) {
// parse json string
var jsonObj = JSON.parse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
}
};
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: this._jsonFormatter
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, JSON.stringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var data;
if (wrapper) {
wrapper = JSON.parse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: this._jsonFormatter
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":35,"crypto-js":46}],34:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactoreOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":35}],35:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.304',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":28}],36:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._transformPrimaryKey(source.primaryKey());
this._transformSetData(collData);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
//tempData,
//dataIsArray,
updates,
//finalUpdates,
primaryKey,
tQuery,
item,
currentIndex,
i;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
// Modify transform data
this._transformSetData(collData);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
if (this._transformEnabled && this._transformIn) {
primaryKey = this._publicData.primaryKey();
for (i = 0; i < updates.length; i++) {
tQuery = {};
item = updates[i];
tQuery[primaryKey] = item[primaryKey];
this._transformUpdate(tQuery, item);
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Modify transform data
this._transformRemove(chainPacket.data.query, chainPacket.options);
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._privateData.distinct.apply(this._privateData, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._privateData.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function () {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
// Update the transformed data object
this._transformPrimaryKey(this.privateData().primaryKey());
this._transformSetData(this.privateData().find());
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
/**
* Updates the public data object to match data from the private data object
* by running private data through the dataIn method provided in
* the transform() call.
* @private
*/
View.prototype._transformSetData = function (data) {
if (this._transformEnabled) {
// Clear existing data
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
this._publicData.setData(data);
}
};
View.prototype._transformInsert = function (data, index) {
if (this._transformEnabled && this._publicData) {
this._publicData.insert(data, index);
}
};
View.prototype._transformUpdate = function (query, update, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.update(query, update, options);
}
};
View.prototype._transformRemove = function (query, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.remove(query, options);
}
};
View.prototype._transformPrimaryKey = function (key) {
if (this._transformEnabled && this._publicData) {
this._publicData.primaryKey(key);
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
// Handle being passed an instance
if (viewName instanceof View) {
return viewName;
}
if (!this._view[viewName]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":34,"./Shared":35}],37:[function(_dereq_,module,exports){
(function (process){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
/*jshint onevar: false, indent:4 */
/*global setImmediate: false, setTimeout: false, console: false */
(function () {
var async = {};
// global on the server, window in the browser
var root, previous_async;
root = this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
var called = false;
return function() {
if (called) throw new Error("Callback was already called.");
called = true;
fn.apply(root, arguments);
}
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
var _each = function (arr, iterator) {
for (var i = 0; i < arr.length; i += 1) {
iterator(arr[i], i, arr);
}
};
var _map = function (arr, iterator) {
if (arr.map) {
return arr.map(iterator);
}
var results = [];
_each(arr, function (x, i, a) {
results.push(iterator(x, i, a));
});
return results;
};
var _reduce = function (arr, iterator, memo) {
if (arr.reduce) {
return arr.reduce(iterator, memo);
}
_each(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
};
var _keys = function (obj) {
if (Object.keys) {
return Object.keys(obj);
}
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
if (typeof process === 'undefined' || !(process.nextTick)) {
if (typeof setImmediate === 'function') {
async.nextTick = function (fn) {
// not a direct alias for IE10 compatibility
setImmediate(fn);
};
async.setImmediate = async.nextTick;
}
else {
async.nextTick = function (fn) {
setTimeout(fn, 0);
};
async.setImmediate = async.nextTick;
}
}
else {
async.nextTick = process.nextTick;
if (typeof setImmediate !== 'undefined') {
async.setImmediate = function (fn) {
// not a direct alias for IE10 compatibility
setImmediate(fn);
};
}
else {
async.setImmediate = async.nextTick;
}
}
async.each = function (arr, iterator, callback) {
callback = callback || function () {};
if (!arr.length) {
return callback();
}
var completed = 0;
_each(arr, function (x) {
iterator(x, only_once(done) );
});
function done(err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
if (completed >= arr.length) {
callback();
}
}
}
};
async.forEach = async.each;
async.eachSeries = function (arr, iterator, callback) {
callback = callback || function () {};
if (!arr.length) {
return callback();
}
var completed = 0;
var iterate = function () {
iterator(arr[completed], function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
if (completed >= arr.length) {
callback();
}
else {
iterate();
}
}
});
};
iterate();
};
async.forEachSeries = async.eachSeries;
async.eachLimit = function (arr, limit, iterator, callback) {
var fn = _eachLimit(limit);
fn.apply(null, [arr, iterator, callback]);
};
async.forEachLimit = async.eachLimit;
var _eachLimit = function (limit) {
return function (arr, iterator, callback) {
callback = callback || function () {};
if (!arr.length || limit <= 0) {
return callback();
}
var completed = 0;
var started = 0;
var running = 0;
(function replenish () {
if (completed >= arr.length) {
return callback();
}
while (running < limit && started < arr.length) {
started += 1;
running += 1;
iterator(arr[started - 1], function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
running -= 1;
if (completed >= arr.length) {
callback();
}
else {
replenish();
}
}
});
}
})();
};
};
var doParallel = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [async.each].concat(args));
};
};
var doParallelLimit = function(limit, fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [_eachLimit(limit)].concat(args));
};
};
var doSeries = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [async.eachSeries].concat(args));
};
};
var _asyncMap = function (eachfn, arr, iterator, callback) {
arr = _map(arr, function (x, i) {
return {index: i, value: x};
});
if (!callback) {
eachfn(arr, function (x, callback) {
iterator(x.value, function (err) {
callback(err);
});
});
} else {
var results = [];
eachfn(arr, function (x, callback) {
iterator(x.value, function (err, v) {
results[x.index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
};
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = function (arr, limit, iterator, callback) {
return _mapLimit(limit)(arr, iterator, callback);
};
var _mapLimit = function(limit) {
return doParallelLimit(limit, _asyncMap);
};
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.reduce = function (arr, memo, iterator, callback) {
async.eachSeries(arr, function (x, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
// inject alias
async.inject = async.reduce;
// foldl alias
async.foldl = async.reduce;
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, function (x) {
return x;
}).reverse();
async.reduce(reversed, memo, iterator, callback);
};
// foldr alias
async.foldr = async.reduceRight;
var _filter = function (eachfn, arr, iterator, callback) {
var results = [];
arr = _map(arr, function (x, i) {
return {index: i, value: x};
});
eachfn(arr, function (x, callback) {
iterator(x.value, function (v) {
if (v) {
results.push(x);
}
callback();
});
}, function (err) {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
};
async.filter = doParallel(_filter);
async.filterSeries = doSeries(_filter);
// select alias
async.select = async.filter;
async.selectSeries = async.filterSeries;
var _reject = function (eachfn, arr, iterator, callback) {
var results = [];
arr = _map(arr, function (x, i) {
return {index: i, value: x};
});
eachfn(arr, function (x, callback) {
iterator(x.value, function (v) {
if (!v) {
results.push(x);
}
callback();
});
}, function (err) {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
};
async.reject = doParallel(_reject);
async.rejectSeries = doSeries(_reject);
var _detect = function (eachfn, arr, iterator, main_callback) {
eachfn(arr, function (x, callback) {
iterator(x, function (result) {
if (result) {
main_callback(x);
main_callback = function () {};
}
else {
callback();
}
});
}, function (err) {
main_callback();
});
};
async.detect = doParallel(_detect);
async.detectSeries = doSeries(_detect);
async.some = function (arr, iterator, main_callback) {
async.each(arr, function (x, callback) {
iterator(x, function (v) {
if (v) {
main_callback(true);
main_callback = function () {};
}
callback();
});
}, function (err) {
main_callback(false);
});
};
// any alias
async.any = async.some;
async.every = function (arr, iterator, main_callback) {
async.each(arr, function (x, callback) {
iterator(x, function (v) {
if (!v) {
main_callback(false);
main_callback = function () {};
}
callback();
});
}, function (err) {
main_callback(true);
});
};
// all alias
async.all = async.every;
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
var fn = function (left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
};
callback(null, _map(results.sort(fn), function (x) {
return x.value;
}));
}
});
};
async.auto = function (tasks, callback) {
callback = callback || function () {};
var keys = _keys(tasks);
var remainingTasks = keys.length
if (!remainingTasks) {
return callback();
}
var results = {};
var listeners = [];
var addListener = function (fn) {
listeners.unshift(fn);
};
var removeListener = function (fn) {
for (var i = 0; i < listeners.length; i += 1) {
if (listeners[i] === fn) {
listeners.splice(i, 1);
return;
}
}
};
var taskComplete = function () {
remainingTasks--
_each(listeners.slice(0), function (fn) {
fn();
});
};
addListener(function () {
if (!remainingTasks) {
var theCallback = callback;
// prevent final callback from calling itself if it errors
callback = function () {};
theCallback(null, results);
}
});
_each(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = function (err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_each(_keys(results), function(rkey) {
safeResults[rkey] = results[rkey];
});
safeResults[k] = args;
callback(err, safeResults);
// stop subsequent errors hitting callback multiple times
callback = function () {};
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
};
var requires = task.slice(0, Math.abs(task.length - 1)) || [];
var ready = function () {
return _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
};
if (ready()) {
task[task.length - 1](taskCallback, results);
}
else {
var listener = function () {
if (ready()) {
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
};
addListener(listener);
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var attempts = [];
// Use defaults if times not passed
if (typeof times === 'function') {
callback = task;
task = times;
times = DEFAULT_TIMES;
}
// Make sure times is a number
times = parseInt(times, 10) || DEFAULT_TIMES;
var wrappedTask = function(wrappedCallback, wrappedResults) {
var retryAttempt = function(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
};
while (times) {
attempts.push(retryAttempt(task, !(times-=1)));
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return callback ? wrappedTask() : wrappedTask
};
async.waterfall = function (tasks, callback) {
callback = callback || function () {};
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
var wrapIterator = function (iterator) {
return function (err) {
if (err) {
callback.apply(null, arguments);
callback = function () {};
}
else {
var args = Array.prototype.slice.call(arguments, 1);
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
async.setImmediate(function () {
iterator.apply(null, args);
});
}
};
};
wrapIterator(async.iterator(tasks))();
};
var _parallel = function(eachfn, tasks, callback) {
callback = callback || function () {};
if (_isArray(tasks)) {
eachfn.map(tasks, function (fn, callback) {
if (fn) {
fn(function (err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
callback.call(null, err, args);
});
}
}, callback);
}
else {
var results = {};
eachfn.each(_keys(tasks), function (k, callback) {
tasks[k](function (err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
results[k] = args;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
};
async.parallel = function (tasks, callback) {
_parallel({ map: async.map, each: async.each }, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
};
async.series = function (tasks, callback) {
callback = callback || function () {};
if (_isArray(tasks)) {
async.mapSeries(tasks, function (fn, callback) {
if (fn) {
fn(function (err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
callback.call(null, err, args);
});
}
}, callback);
}
else {
var results = {};
async.eachSeries(_keys(tasks), function (k, callback) {
tasks[k](function (err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
results[k] = args;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
};
async.iterator = function (tasks) {
var makeCallback = function (index) {
var fn = function () {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
};
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
};
return makeCallback(0);
};
async.apply = function (fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return fn.apply(
null, args.concat(Array.prototype.slice.call(arguments))
);
};
};
var _concat = function (eachfn, arr, fn, callback) {
var r = [];
eachfn(arr, function (x, cb) {
fn(x, function (err, y) {
r = r.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, r);
});
};
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
if (test()) {
iterator(function (err) {
if (err) {
return callback(err);
}
async.whilst(test, iterator, callback);
});
}
else {
callback();
}
};
async.doWhilst = function (iterator, test, callback) {
iterator(function (err) {
if (err) {
return callback(err);
}
var args = Array.prototype.slice.call(arguments, 1);
if (test.apply(null, args)) {
async.doWhilst(iterator, test, callback);
}
else {
callback();
}
});
};
async.until = function (test, iterator, callback) {
if (!test()) {
iterator(function (err) {
if (err) {
return callback(err);
}
async.until(test, iterator, callback);
});
}
else {
callback();
}
};
async.doUntil = function (iterator, test, callback) {
iterator(function (err) {
if (err) {
return callback(err);
}
var args = Array.prototype.slice.call(arguments, 1);
if (!test.apply(null, args)) {
async.doUntil(iterator, test, callback);
}
else {
callback();
}
});
};
async.queue = function (worker, concurrency) {
if (concurrency === undefined) {
concurrency = 1;
}
function _insert(q, data, pos, callback) {
if (!q.started){
q.started = true;
}
if (!_isArray(data)) {
data = [data];
}
if(data.length == 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
if (q.drain) {
q.drain();
}
});
}
_each(data, function(task) {
var item = {
data: task,
callback: typeof callback === 'function' ? callback : null
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.saturated && q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
var workers = 0;
var q = {
tasks: [],
concurrency: concurrency,
saturated: null,
empty: null,
drain: null,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = null;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
var task = q.tasks.shift();
if (q.empty && q.tasks.length === 0) {
q.empty();
}
workers += 1;
var next = function () {
workers -= 1;
if (task.callback) {
task.callback.apply(task, arguments);
}
if (q.drain && q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
var cb = only_once(next);
worker(task.data, cb);
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
if (q.paused === true) { return; }
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= q.concurrency; w++) {
async.setImmediate(q.process);
}
}
};
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
};
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (!q.started){
q.started = true;
}
if (!_isArray(data)) {
data = [data];
}
if(data.length == 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
if (q.drain) {
q.drain();
}
});
}
_each(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : null
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.saturated && q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
var working = false,
tasks = [];
var cargo = {
tasks: tasks,
payload: payload,
saturated: null,
empty: null,
drain: null,
drained: true,
push: function (data, callback) {
if (!_isArray(data)) {
data = [data];
}
_each(data, function(task) {
tasks.push({
data: task,
callback: typeof callback === 'function' ? callback : null
});
cargo.drained = false;
if (cargo.saturated && tasks.length === payload) {
cargo.saturated();
}
});
async.setImmediate(cargo.process);
},
process: function process() {
if (working) return;
if (tasks.length === 0) {
if(cargo.drain && !cargo.drained) cargo.drain();
cargo.drained = true;
return;
}
var ts = typeof payload === 'number'
? tasks.splice(0, payload)
: tasks.splice(0, tasks.length);
var ds = _map(ts, function (task) {
return task.data;
});
if(cargo.empty) cargo.empty();
working = true;
worker(ds, function () {
working = false;
var args = arguments;
_each(ts, function (data) {
if (data.callback) {
data.callback.apply(null, args);
}
});
process();
});
},
length: function () {
return tasks.length;
},
running: function () {
return working;
}
};
return cargo;
};
var _console_fn = function (name) {
return function (fn) {
var args = Array.prototype.slice.call(arguments, 1);
fn.apply(null, args.concat([function (err) {
var args = Array.prototype.slice.call(arguments, 1);
if (typeof console !== 'undefined') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_each(args, function (x) {
console[name](x);
});
}
}
}]));
};
};
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || function (x) {
return x;
};
var memoized = function () {
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.nextTick(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([function () {
memo[key] = arguments;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, arguments);
}
}]));
}
};
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
async.times = function (count, iterator, callback) {
var counter = [];
for (var i = 0; i < count; i++) {
counter.push(i);
}
return async.map(counter, iterator, callback);
};
async.timesSeries = function (count, iterator, callback) {
var counter = [];
for (var i = 0; i < count; i++) {
counter.push(i);
}
return async.mapSeries(counter, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return function () {
var that = this;
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([function () {
var err = arguments[0];
var nextargs = Array.prototype.slice.call(arguments, 1);
cb(err, nextargs);
}]))
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
};
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
var _applyEach = function (eachfn, fns /*args...*/) {
var go = function () {
var that = this;
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
return eachfn(fns, function (fn, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
};
if (arguments.length > 2) {
var args = Array.prototype.slice.call(arguments, 2);
return go.apply(this, args);
}
else {
return go;
}
};
async.applyEach = doParallel(_applyEach);
async.applyEachSeries = doSeries(_applyEach);
async.forever = function (fn, callback) {
function next(err) {
if (err) {
if (callback) {
return callback(err);
}
throw err;
}
fn(next);
}
next();
};
// Node.js
if (typeof module !== 'undefined' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define !== 'undefined' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'))
},{"_process":72}],38:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 () {
// Shortcuts
var key = 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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],39:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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":40}],40:[function(_dereq_,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) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
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
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('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;
}));
},{}],41:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":40}],42:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":40}],43:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./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":40,"./hmac":45,"./sha1":64}],44:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":39,"./core":40}],45:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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":40}],46:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":38,"./cipher-core":39,"./core":40,"./enc-base64":41,"./enc-utf16":42,"./evpkdf":43,"./format-hex":44,"./hmac":45,"./lib-typedarrays":47,"./md5":48,"./mode-cfb":49,"./mode-ctr":51,"./mode-ctr-gladman":50,"./mode-ecb":52,"./mode-ofb":53,"./pad-ansix923":54,"./pad-iso10126":55,"./pad-iso97971":56,"./pad-nopadding":57,"./pad-zeropadding":58,"./pbkdf2":59,"./rabbit":61,"./rabbit-legacy":60,"./rc4":62,"./ripemd160":63,"./sha1":64,"./sha224":65,"./sha256":66,"./sha3":67,"./sha384":68,"./sha512":69,"./tripledes":70,"./x64-core":71}],47:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":40}],48:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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":40}],49:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
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);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":39,"./core":40}],50:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby [email protected]
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":39,"./core":40}],51:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":39,"./core":40}],52:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":39,"./core":40}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":39,"./core":40}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
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;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":39,"./core":40}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
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;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":39,"./core":40}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":39,"./core":40}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":39,"./core":40}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":39,"./core":40}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./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 SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
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.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @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 HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @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.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":40,"./hmac":45,"./sha1":64}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],63:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(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 _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_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];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_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] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 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 < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
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 f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* 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.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* 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.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":40}],64:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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":40}],65:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], 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_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* 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.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* 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.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":40,"./sha256":66}],66:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./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;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_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];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// 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;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 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.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* 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.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":40}],67:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-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_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].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.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* 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.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":40,"./x64-core":71}],68:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* 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.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* 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.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":40,"./sha512":69,"./x64-core":71}],69:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 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 + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* 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.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* 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.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":40,"./x64-core":71}],70:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./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 WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],71:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":40}],72:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
currentQueue[queueIndex].run();
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],73:[function(_dereq_,module,exports){
'use strict';
var asap = _dereq_('asap')
module.exports = Promise
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
if (typeof fn !== 'function') throw new TypeError('not a function')
var state = null
var value = null
var deferreds = []
var self = this
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject))
})
}
function handle(deferred) {
if (state === null) {
deferreds.push(deferred)
return
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value)
return
}
var ret
try {
ret = cb(value)
}
catch (e) {
deferred.reject(e)
return
}
deferred.resolve(ret)
})
}
function resolve(newValue) {
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.')
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then
if (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject)
return
}
}
state = true
value = newValue
finale()
} catch (e) { reject(e) }
}
function reject(newValue) {
state = false
value = newValue
finale()
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i])
deferreds = null
}
doResolve(fn, resolve, reject)
}
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.resolve = resolve
this.reject = reject
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return
done = true
onFulfilled(value)
}, function (reason) {
if (done) return
done = true
onRejected(reason)
})
} catch (ex) {
if (done) return
done = true
onRejected(ex)
}
}
},{"asap":75}],74:[function(_dereq_,module,exports){
'use strict';
//This file contains then/promise specific extensions to the core promise API
var Promise = _dereq_('./core.js')
var asap = _dereq_('asap')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Object.create(Promise.prototype)
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.from = Promise.cast = function (value) {
var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead')
err.name = 'Warning'
console.warn(err.stack)
return Promise.resolve(value)
}
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
fn.apply(self, args)
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
try {
return fn.apply(this, arguments).nodeify(callback)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback(ex)
})
}
}
}
}
Promise.all = function () {
var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0])
var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments)
if (!calledWithArray) {
var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated')
err.name = 'Warning'
console.warn(err.stack)
}
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val) }, reject)
return
}
}
args[i] = val
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex)
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i])
}
})
}
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
asap(function () {
throw err
})
})
}
Promise.prototype.nodeify = function (callback) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback(null, value)
})
}, function (err) {
asap(function () {
callback(err)
})
})
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":73,"asap":75}],75:[function(_dereq_,module,exports){
(function (process){
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestFlush = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestFlush = setImmediate.bind(window, flush);
} else {
requestFlush = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
channel.port1.onmessage = flush;
requestFlush = function () {
channel.port2.postMessage(0);
};
} else {
// old browsers
requestFlush = function () {
setTimeout(flush, 0);
};
}
function asap(task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestFlush();
}
};
module.exports = asap;
}).call(this,_dereq_('_process'))
},{"_process":72}],76:[function(_dereq_,module,exports){
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
(function() {
'use strict';
// Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB ||
this.mozIndexedDB || this.OIndexedDB ||
this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = window.BlobBuilder ||
window.MSBlobBuilder ||
window.MozBlobBuilder ||
window.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({status: xhr.status, response: xhr.response});
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function(resolve, reject) {
var blob = _createBlob([''], {type: 'image/png'});
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function() {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE],
'readwrite');
var getBlobReq = blobTxn.objectStore(
DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function(e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function(res) {
resolve(!!(res && res.type === 'image/png'));
}, function() {
resolve(false);
}).then(function() {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function() {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function(value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function(e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type});
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
return new Promise(function(resolve, reject) {
var openreq = indexedDB.open(dbInfo.name, dbInfo.version);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function(e) {
// First time setup: create an empty object store
openreq.result.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// added when support for blob shims was added
openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
};
openreq.onsuccess = function() {
dbInfo.db = openreq.result;
self._dbInfo = dbInfo;
resolve();
};
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function() {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void(0)) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
var dbInfo;
self.ready().then(function() {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function(blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function(value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function() {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function() {
resolve();
};
transaction.onerror = function() {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function() {
resolve();
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function() {
resolve(req.result);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = asyncStorage;
} else if (typeof define === 'function' && define.amd) {
define('asyncStorage', function() {
return asyncStorage;
});
} else {
this.asyncStorage = asyncStorage;
}
}).call(window);
},{"promise":74}],77:[function(_dereq_,module,exports){
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
self._dbInfo = dbInfo;
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
return serializerPromise.then(function(lib) {
serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), i + 1);
if (value !== void(0)) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function(keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function(resolve, reject) {
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
try {
var dbInfo = self._dbInfo;
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.EXPORT) {
module.exports = localStorageWrapper;
} else if (moduleType === ModuleType.DEFINE) {
define('localStorageWrapper', function() {
return localStorageWrapper;
});
} else {
this.localStorageWrapper = localStorageWrapper;
}
}).call(window);
},{"./../utils/serializer":80,"promise":74}],78:[function(_dereq_,module,exports){
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof(options[i]) !== 'string' ?
options[i].toString() : options[i];
}
}
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
var dbInfoPromise = new Promise(function(resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version),
dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function() {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function(t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName +
' (id INTEGER PRIMARY KEY, key unique, value)', [],
function() {
self._dbInfo = dbInfo;
resolve();
}, function(t, error) {
reject(error);
});
});
});
return serializerPromise.then(function(lib) {
serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName +
' WHERE key = ? LIMIT 1', [key],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = serializer.deserialize(result);
}
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [],
function(t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void(0)) {
resolve(result);
return;
}
}
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('INSERT OR REPLACE INTO ' +
dbInfo.storeName +
' (key, value) VALUES (?, ?)',
[key, value], function() {
resolve(originalValue);
}, function(t, error) {
reject(error);
});
}, function(sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName +
' WHERE key = ?', [key],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' +
dbInfo.storeName, [], function(t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName +
' WHERE id = ? LIMIT 1', [n + 1],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).key : null;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [],
function(t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.DEFINE) {
define('webSQLStorage', function() {
return webSQLStorage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = webSQLStorage;
} else {
this.webSQLStorage = webSQLStorage;
}
}).call(window);
},{"./../utils/serializer":80,"promise":74}],79:[function(_dereq_,module,exports){
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports &&
typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [
DriverType.INDEXEDDB,
DriverType.WEBSQL,
DriverType.LOCALSTORAGE
];
var LibraryMethods = [
'clear',
'getItem',
'iterate',
'key',
'keys',
'length',
'removeItem',
'setItem'
];
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function(self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB ||
self.mozIndexedDB || self.OIndexedDB ||
self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function() {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator &&
self.navigator.userAgent &&
/Safari/.test(self.navigator.userAgent) &&
!/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB &&
typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function() {
try {
return (self.localStorage &&
('setItem' in self.localStorage) &&
(self.localStorage.setItem));
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function() {
var _args = arguments;
return localForageInstance.ready().then(function() {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) &&
DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var globalObject = this;
function LocalForage(options) {
this._config = extend({}, DefaultConfig, options);
this._driverSet = null;
this._ready = false;
this._dbInfo = null;
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
this.setDriver(this._config.driver);
}
LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB;
LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE;
LocalForage.prototype.WEBSQL = DriverType.WEBSQL;
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof(options) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " +
'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof(options) === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function(driverObject, callback,
errorCallback) {
var defineDriver = new Promise(function(resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error(
'Custom driver not compliant; see ' +
'https://mozilla.github.io/localForage/#definedriver'
);
var namingError = new Error(
'Custom driver name already in use: ' + driverObject._driver
);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod ||
!driverObject[customDriverMethod] ||
typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function(supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
defineDriver.then(callback, errorCallback);
return defineDriver;
};
LocalForage.prototype.driver = function() {
return this._driver || null;
};
LocalForage.prototype.ready = function(callback) {
var self = this;
var ready = new Promise(function(resolve, reject) {
self._driverSet.then(function() {
if (self._ready === null) {
self._ready = self._initStorage(self._config);
}
self._ready.then(resolve, reject);
})['catch'](reject);
});
ready.then(callback, callback);
return ready;
};
LocalForage.prototype.setDriver = function(drivers, callback,
errorCallback) {
var self = this;
if (typeof drivers === 'string') {
drivers = [drivers];
}
this._driverSet = new Promise(function(resolve, reject) {
var driverName = self._getFirstSupportedDriver(drivers);
var error = new Error('No available storage method found.');
if (!driverName) {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
self._dbInfo = null;
self._ready = null;
if (isLibraryDriver(driverName)) {
var driverPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_([driverName], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
switch (driverName) {
case self.INDEXEDDB:
resolve(_dereq_('./drivers/indexeddb'));
break;
case self.LOCALSTORAGE:
resolve(_dereq_('./drivers/localstorage'));
break;
case self.WEBSQL:
resolve(_dereq_('./drivers/websql'));
break;
}
} else {
resolve(globalObject[driverName]);
}
});
driverPromise.then(function(driver) {
self._extend(driver);
resolve();
});
} else if (CustomDrivers[driverName]) {
self._extend(CustomDrivers[driverName]);
resolve();
} else {
self._driverSet = Promise.reject(error);
reject(error);
}
});
function setDriverToConfig() {
self._config.driver = self.driver();
}
this._driverSet.then(setDriverToConfig, setDriverToConfig);
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
// Used to determine which driver we should use as the backend for this
// instance of localForage.
LocalForage.prototype._getFirstSupportedDriver = function(drivers) {
if (drivers && isArray(drivers)) {
for (var i = 0; i < drivers.length; i++) {
var driver = drivers[i];
if (this.supports(driver)) {
return driver;
}
}
}
return null;
};
LocalForage.prototype.createInstance = function(options) {
return new LocalForage(options);
};
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localForage = new LocalForage();
// We allow localForage to be declared as a module or as a library
// available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
define('localforage', function() {
return localForage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = localForage;
} else {
this.localforage = localForage;
}
}).call(window);
},{"./drivers/indexeddb":76,"./drivers/localstorage":77,"./drivers/websql":78,"promise":74}],80:[function(_dereq_,module,exports){
(function() {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH +
TYPE_ARRAYBUFFER.length;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder ||
globalObject.MSBlobBuilder ||
globalObject.MozBlobBuilder ||
globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' ||
value.buffer &&
value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function() {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' +
bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ",
value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0,
SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], {type: blobType});
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i+=4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i+1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i+2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i+3]);
/*jslint bitwise: true */
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if ((bytes.length % 3) === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = localforageSerializer;
} else if (typeof define === 'function' && define.amd) {
define('localforageSerializer', function() {
return localforageSerializer;
});
} else {
this.localforageSerializer = localforageSerializer;
}
}).call(window);
},{}],81:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":82,"./lib/inflate":83,"./lib/utils/common":84,"./lib/zlib/constants":87}],82:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":84,"./utils/strings":85,"./zlib/deflate.js":89,"./zlib/messages":94,"./zlib/zstream":96}],83:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force sWindow size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if sWindow size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
} while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":84,"./utils/strings":85,"./zlib/constants":87,"./zlib/gzheader":90,"./zlib/inflate.js":92,"./zlib/messages":94,"./zlib/zstream":96}],84:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],85:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":84}],86:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],87:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],88:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],89:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 sWindow */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.sWindow; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of sWindow index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->sWindow+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the sWindow when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the sWindow is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.sWindow, s.sWindow, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.sWindow, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.sWindow[str];
/* UPDATE_HASH(s, s->ins_h, s->sWindow[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->sWindow[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of sWindow, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->sWindow + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of sWindow, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->sWindow + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* sWindow to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the sWindow as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string sWindow[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of sWindow index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.sWindow[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.sWindow[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.sWindow[s.strstart]));
/*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.sWindow[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next sWindow position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string sWindow[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of sWindow index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->sWindow[s->strstart-1]));
/*** _tr_tally_lit(s, s.sWindow[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.sWindow[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->sWindow[s->strstart-1]));
/*** _tr_tally_lit(s, s.sWindow[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.sWindow[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.sWindow;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->sWindow+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->sWindow[s->strstart]));
/*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.sWindow[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->sWindow[s->strstart]));
/*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.sWindow[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 sWindow size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.sWindow = null;
/* Sliding sWindow. Input bytes are read into the second half of the sWindow,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of sWindow: 2*wSize, except when the user input buffer
* is directly used as sliding sWindow.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a sWindow index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* sWindow position at the beginning of the current output block. Gets
* negative when the sWindow is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in sWindow */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the sWindow so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of sWindow left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for sWindow memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in sWindow for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte sWindow bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.sWindow = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->sWindow yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":84,"./adler32":86,"./crc32":88,"./messages":94,"./trees":95}],90:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],91:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* sWindow size or zero if not using sWindow */
var whave; /* valid bytes in the sWindow */
var wnext; /* sWindow write index */
var sWindow; /* allocated sliding sWindow, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* sWindow position, sWindow bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
sWindow = state.sWindow;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from sWindow */
op = dist - op; /* distance back in sWindow */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // sWindow index
from_source = sWindow;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from sWindow */
len -= op;
do {
output[_out++] = sWindow[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around sWindow */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of sWindow */
len -= op;
do {
output[_out++] = sWindow[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of sWindow */
op = wnext;
len -= op;
do {
output[_out++] = sWindow[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in sWindow */
from += wnext - op;
if (op < len) { /* some from sWindow */
len -= op;
do {
output[_out++] = sWindow[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],92:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 sWindow */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding sWindow */
this.wbits = 0; /* log base 2 of requested sWindow size */
this.wsize = 0; /* sWindow size or zero if not using sWindow */
this.whave = 0; /* valid bytes in the sWindow */
this.wnext = 0; /* sWindow write index */
this.sWindow = null; /* allocated sliding sWindow, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of sWindow bits, free sWindow if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.sWindow !== null && state.wbits !== windowBits) {
state.sWindow = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.sWindow = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the sWindow with the last wsize (normally 32K) bytes written before
returning. If sWindow does not exist yet, create it. This is only called
when a sWindow is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a sWindow for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding sWindow
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the sWindow */
if (state.sWindow === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.sWindow = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular sWindow */
if (copy >= state.wsize) {
utils.arraySet(state.sWindow,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->sWindow + state->wnext, end - copy, dist);
utils.arraySet(state.sWindow,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->sWindow, end - copy, copy);
utils.arraySet(state.sWindow,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid sWindow size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from sWindow */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.sWindow;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the sWindow state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.sWindow) {
state.sWindow = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":84,"./adler32":86,"./crc32":88,"./inffast":91,"./inftrees":93}],93:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":84}],94:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],95:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.sWindow, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":84}],96:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
|
node_modules/react-icons/fa/meanpath.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const FaMeanpath = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m32.3 18.8v2.5q0 0.6-0.3 0.9t-0.9 0.3h-4.5q-0.5 0-0.8-0.3t-0.3-0.9v-2.5q0-0.5 0.3-0.9t0.8-0.3h4.5q0.6 0 0.9 0.3t0.3 0.9z m-11 5.1v-5.5q0-1.2-0.7-2t-1.9-0.7h-3q-1.5 0-2.1 1.2-0.6-1.2-2.2-1.2h-2.9q-1.1 0-1.9 0.7t-0.7 2v5.5q0 0.5 0.5 0.5h1.2q0.5 0 0.5-0.5v-5.1q0-0.5 0.3-0.9t0.9-0.3h2q0.6 0 0.9 0.3t0.3 0.9v5.1q0 0.5 0.5 0.5h1.2q0.5 0 0.5-0.5v-5.1q0-0.5 0.3-0.9t0.8-0.3h2.2q0.5 0 0.8 0.3t0.3 0.9v5.1q0 0.5 0.5 0.5h1.3q0.4 0 0.4-0.5z m13.2-2.1v-3.5q0-1.1-0.8-1.9t-1.9-0.7h-5.9q-1.2 0-1.9 0.7t-0.7 1.9v9.2q0 0.5 0.5 0.5h1.2q0.5 0 0.5-0.5v-4q0.6 0.9 2.1 0.9h4.2q1.2 0 1.9-0.7t0.8-1.9z m2.8-13.8v24q0 2.1-1.5 3.6t-3.7 1.5h-23.9q-2.2 0-3.7-1.5t-1.5-3.6v-24q0-2.1 1.5-3.6t3.7-1.5h23.9q2.1 0 3.7 1.5t1.5 3.6z"/></g>
</Icon>
)
export default FaMeanpath
|