blob: ba0864d9f1a63ee3a1b8c70a8a774f3c930dee45 [file] [log] [blame]
// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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){
/**
* Module dependencies.
*/
var fmt = require('printf');
/**
* Expose `histogram()`.
*/
module.exports = histogram;
/**
* Return ascii histogram of `data`.
*
* @param {Object} data
* @param {Object} [opts]
* @return {String}
* @api public
*/
function histogram(data, opts) {
opts = opts || {};
// options
var width = opts.width || 60;
var barc = opts.bar || '#';
var map = opts.map || noop;
// normalize data
var data = toArray(data);
if (opts.sort) data = data.sort(descending);
var maxKey = max(data.map(function(d){ return d.key.length }));
var maxVal = max(data.map(function(d){ return d.val }));
var str = '';
// blah blah histo
for (var i = 0; i < data.length; i++) {
var d = data[i];
var p = (d.val / maxVal) || 1;
var shown = Math.round(width * p);
var blank = width - shown
var bar = Array(shown + 1).join(barc);
bar += Array(blank + 1).join(' ');
str += fmt(' %*s | %s | %s\n', d.key, maxKey, bar, map(d.val));
}
return str;
}
/**
* Sort descending.
*/
function descending(a, b) {
return b.val - a.val;
}
/**
* Return max in array.
*/
function max(data) {
var n = data[0];
for (var i = 1; i < data.length; i++) {
n = data[i] > n ? data[i] : n;
}
return n;
}
/**
* Turn object into an array.
*/
function toArray(obj) {
return Object.keys(obj).map(function(key){
return {
key: key,
val: obj[key]
}
})
}
/**
* Noop map function.
*/
function noop(val) {
return val;
}
},{"printf":2}],2:[function(require,module,exports){
var util = require('util');
var tokenize = function(/*String*/ str, /*RegExp*/ re, /*Function?*/ parseDelim, /*Object?*/ instance){
// summary:
// Split a string by a regular expression with the ability to capture the delimeters
// parseDelim:
// Each group (excluding the 0 group) is passed as a parameter. If the function returns
// a value, it's added to the list of tokens.
// instance:
// Used as the "this' instance when calling parseDelim
var tokens = [];
var match, content, lastIndex = 0;
while(match = re.exec(str)){
content = str.slice(lastIndex, re.lastIndex - match[0].length);
if(content.length){
tokens.push(content);
}
if(parseDelim){
var parsed = parseDelim.apply(instance, match.slice(1).concat(tokens.length));
if(typeof parsed != 'undefined'){
if(parsed.specifier === '%'){
tokens.push('%');
}else{
tokens.push(parsed);
}
}
}
lastIndex = re.lastIndex;
}
content = str.slice(lastIndex);
if(content.length){
tokens.push(content);
}
return tokens;
}
var Formatter = function(/*String*/ format){
var tokens = [];
this._mapped = false;
this._format = format;
this._tokens = tokenize(format, this._re, this._parseDelim, this);
}
Formatter.prototype._re = /\%(?:\(([\w_]+)\)|([1-9]\d*)\$)?([0 +\-\#]*)(\*|\d+)?(\.)?(\*|\d+)?[hlL]?([\%AbscdeEfFgGioOuxX])/g;
Formatter.prototype._parseDelim = function(mapping, intmapping, flags, minWidth, period, precision, specifier){
if(mapping){
this._mapped = true;
}
return {
mapping: mapping,
intmapping: intmapping,
flags: flags,
_minWidth: minWidth, // May be dependent on parameters
period: period,
_precision: precision, // May be dependent on parameters
specifier: specifier
};
};
Formatter.prototype._specifiers = {
b: {
base: 2,
isInt: true
},
o: {
base: 8,
isInt: true
},
x: {
base: 16,
isInt: true
},
X: {
extend: ['x'],
toUpper: true
},
d: {
base: 10,
isInt: true
},
i: {
extend: ['d']
},
u: {
extend: ['d'],
isUnsigned: true
},
c: {
setArg: function(token){
if(!isNaN(token.arg)){
var num = parseInt(token.arg);
if(num < 0 || num > 127){
throw new Error('invalid character code passed to %c in printf');
}
token.arg = isNaN(num) ? '' + num : String.fromCharCode(num);
}
}
},
s: {
setMaxWidth: function(token){
token.maxWidth = (token.period == '.') ? token.precision : -1;
}
},
e: {
isDouble: true,
doubleNotation: 'e'
},
E: {
extend: ['e'],
toUpper: true
},
f: {
isDouble: true,
doubleNotation: 'f'
},
F: {
extend: ['f']
},
g: {
isDouble: true,
doubleNotation: 'g'
},
G: {
extend: ['g'],
toUpper: true
},
O: {
isObject: true,
showNonEnumerable: true
},
A: {
isObject: true,
showNonEnumerable: false
},
};
Formatter.prototype.format = function(/*mixed...*/ filler){
if(this._mapped && typeof filler != 'object'){
throw new Error('format requires a mapping');
}
var str = '';
var position = 0;
for(var i = 0, token; i < this._tokens.length; i++){
token = this._tokens[i];
if(typeof token == 'string'){
str += token;
}else{
if(this._mapped){
if(typeof filler[token.mapping] == 'undefined'){
throw new Error('missing key ' + token.mapping);
}
token.arg = filler[token.mapping];
}else{
if(token.intmapping){
var position = parseInt(token.intmapping) - 1;
}
if(position >= arguments.length){
throw new Error('got ' + arguments.length + ' printf arguments, insufficient for \'' + this._format + '\'');
}
token.arg = arguments[position++];
}
if(!token.compiled){
token.compiled = true;
token.sign = '';
token.zeroPad = false;
token.rightJustify = false;
token.alternative = false;
var flags = {};
for(var fi = token.flags.length; fi--;){
var flag = token.flags.charAt(fi);
flags[flag] = true;
switch(flag){
case ' ':
token.sign = ' ';
break;
case '+':
token.sign = '+';
break;
case '0':
token.zeroPad = (flags['-']) ? false : true;
break;
case '-':
token.rightJustify = true;
token.zeroPad = false;
break;
case '\#':
token.alternative = true;
break;
default:
throw Error('bad formatting flag \'' + token.flags.charAt(fi) + '\'');
}
}
token.minWidth = (token._minWidth) ? parseInt(token._minWidth) : 0;
token.maxWidth = -1;
token.toUpper = false;
token.isUnsigned = false;
token.isInt = false;
token.isDouble = false;
token.isObject = false;
token.precision = 1;
if(token.period == '.'){
if(token._precision){
token.precision = parseInt(token._precision);
}else{
token.precision = 0;
}
}
var mixins = this._specifiers[token.specifier];
if(typeof mixins == 'undefined'){
throw new Error('unexpected specifier \'' + token.specifier + '\'');
}
if(mixins.extend){
var s = this._specifiers[mixins.extend];
for(var k in s){
mixins[k] = s[k]
}
delete mixins.extend;
}
for(var k in mixins){
token[k] = mixins[k];
}
}
if(typeof token.setArg == 'function'){
token.setArg(token);
}
if(typeof token.setMaxWidth == 'function'){
token.setMaxWidth(token);
}
if(token._minWidth == '*'){
if(this._mapped){
throw new Error('* width not supported in mapped formats');
}
token.minWidth = parseInt(arguments[position++]);
if(isNaN(token.minWidth)){
throw new Error('the argument for * width at position ' + position + ' is not a number in ' + this._format);
}
// negative width means rightJustify
if (token.minWidth < 0) {
token.rightJustify = true;
token.minWidth = -token.minWidth;
}
}
if(token._precision == '*' && token.period == '.'){
if(this._mapped){
throw new Error('* precision not supported in mapped formats');
}
token.precision = parseInt(arguments[position++]);
if(isNaN(token.precision)){
throw Error('the argument for * precision at position ' + position + ' is not a number in ' + this._format);
}
// negative precision means unspecified
if (token.precision < 0) {
token.precision = 1;
token.period = '';
}
}
if(token.isInt){
// a specified precision means no zero padding
if(token.period == '.'){
token.zeroPad = false;
}
this.formatInt(token);
}else if(token.isDouble){
if(token.period != '.'){
token.precision = 6;
}
this.formatDouble(token);
}else if(token.isObject){
this.formatObject(token);
}
this.fitField(token);
str += '' + token.arg;
}
}
return str;
};
Formatter.prototype._zeros10 = '0000000000';
Formatter.prototype._spaces10 = ' ';
Formatter.prototype.formatInt = function(token) {
var i = parseInt(token.arg);
if(!isFinite(i)){ // isNaN(f) || f == Number.POSITIVE_INFINITY || f == Number.NEGATIVE_INFINITY)
// allow this only if arg is number
if(typeof token.arg != 'number'){
throw new Error('format argument \'' + token.arg + '\' not an integer; parseInt returned ' + i);
}
//return '' + i;
i = 0;
}
// if not base 10, make negatives be positive
// otherwise, (-10).toString(16) is '-a' instead of 'fffffff6'
if(i < 0 && (token.isUnsigned || token.base != 10)){
i = 0xffffffff + i + 1;
}
if(i < 0){
token.arg = (- i).toString(token.base);
this.zeroPad(token);
token.arg = '-' + token.arg;
}else{
token.arg = i.toString(token.base);
// need to make sure that argument 0 with precision==0 is formatted as ''
if(!i && !token.precision){
token.arg = '';
}else{
this.zeroPad(token);
}
if(token.sign){
token.arg = token.sign + token.arg;
}
}
if(token.base == 16){
if(token.alternative){
token.arg = '0x' + token.arg;
}
token.arg = token.toUpper ? token.arg.toUpperCase() : token.arg.toLowerCase();
}
if(token.base == 8){
if(token.alternative && token.arg.charAt(0) != '0'){
token.arg = '0' + token.arg;
}
}
};
Formatter.prototype.formatDouble = function(token) {
var f = parseFloat(token.arg);
if(!isFinite(f)){ // isNaN(f) || f == Number.POSITIVE_INFINITY || f == Number.NEGATIVE_INFINITY)
// allow this only if arg is number
if(typeof token.arg != 'number'){
throw new Error('format argument \'' + token.arg + '\' not a float; parseFloat returned ' + f);
}
// C99 says that for 'f':
// infinity -> '[-]inf' or '[-]infinity' ('[-]INF' or '[-]INFINITY' for 'F')
// NaN -> a string starting with 'nan' ('NAN' for 'F')
// this is not commonly implemented though.
//return '' + f;
f = 0;
}
switch(token.doubleNotation) {
case 'e': {
token.arg = f.toExponential(token.precision);
break;
}
case 'f': {
token.arg = f.toFixed(token.precision);
break;
}
case 'g': {
// C says use 'e' notation if exponent is < -4 or is >= prec
// ECMAScript for toPrecision says use exponential notation if exponent is >= prec,
// though step 17 of toPrecision indicates a test for < -6 to force exponential.
if(Math.abs(f) < 0.0001){
//print('forcing exponential notation for f=' + f);
token.arg = f.toExponential(token.precision > 0 ? token.precision - 1 : token.precision);
}else{
token.arg = f.toPrecision(token.precision);
}
// In C, unlike 'f', 'gG' removes trailing 0s from fractional part, unless alternative format flag ('#').
// But ECMAScript formats toPrecision as 0.00100000. So remove trailing 0s.
if(!token.alternative){
//print('replacing trailing 0 in \'' + s + '\'');
token.arg = token.arg.replace(/(\..*[^0])0*e/, '$1e');
// if fractional part is entirely 0, remove it and decimal point
token.arg = token.arg.replace(/\.0*e/, 'e').replace(/\.0$/,'');
}
break;
}
default: throw new Error('unexpected double notation \'' + token.doubleNotation + '\'');
}
// C says that exponent must have at least two digits.
// But ECMAScript does not; toExponential results in things like '1.000000e-8' and '1.000000e+8'.
// Note that s.replace(/e([\+\-])(\d)/, 'e$10$2') won't work because of the '$10' instead of '$1'.
// And replace(re, func) isn't supported on IE50 or Safari1.
token.arg = token.arg.replace(/e\+(\d)$/, 'e+0$1').replace(/e\-(\d)$/, 'e-0$1');
// if alt, ensure a decimal point
if(token.alternative){
token.arg = token.arg.replace(/^(\d+)$/,'$1.');
token.arg = token.arg.replace(/^(\d+)e/,'$1.e');
}
if(f >= 0 && token.sign){
token.arg = token.sign + token.arg;
}
token.arg = token.toUpper ? token.arg.toUpperCase() : token.arg.toLowerCase();
};
Formatter.prototype.formatObject = function(token) {
// If no precision is specified, then reset it to null (infinite depth).
var precision = (token.period === '.') ? token.precision : null;
token.arg = util.inspect(token.arg, token.showNonEnumerable, precision);
};
Formatter.prototype.zeroPad = function(token, /*Int*/ length) {
length = (arguments.length == 2) ? length : token.precision;
var negative = false;
if(typeof token.arg != "string"){
token.arg = "" + token.arg;
}
if (token.arg.substr(0,1) === '-') {
negative = true;
token.arg = token.arg.substr(1);
}
var tenless = length - 10;
while(token.arg.length < tenless){
token.arg = (token.rightJustify) ? token.arg + this._zeros10 : this._zeros10 + token.arg;
}
var pad = length - token.arg.length;
token.arg = (token.rightJustify) ? token.arg + this._zeros10.substring(0, pad) : this._zeros10.substring(0, pad) + token.arg;
if (negative) token.arg = '-' + token.arg;
};
Formatter.prototype.fitField = function(token) {
if(token.maxWidth >= 0 && token.arg.length > token.maxWidth){
return token.arg.substring(0, token.maxWidth);
}
if(token.zeroPad){
this.zeroPad(token, token.minWidth);
return;
}
this.spacePad(token);
};
Formatter.prototype.spacePad = function(token, /*Int*/ length) {
length = (arguments.length == 2) ? length : token.minWidth;
if(typeof token.arg != 'string'){
token.arg = '' + token.arg;
}
var tenless = length - 10;
while(token.arg.length < tenless){
token.arg = (token.rightJustify) ? token.arg + this._spaces10 : this._spaces10 + token.arg;
}
var pad = length - token.arg.length;
token.arg = (token.rightJustify) ? token.arg + this._spaces10.substring(0, pad) : this._spaces10.substring(0, pad) + token.arg;
};
module.exports = function(){
var args = Array.prototype.slice.call(arguments),
stream, format;
if(args[0] instanceof require('stream').Stream){
stream = args.shift();
}
format = args.shift();
var formatter = new Formatter(format);
var string = formatter.format.apply(formatter, args);
if(stream){
stream.write(string);
}else{
return string;
}
};
module.exports.Formatter = Formatter;
},{"stream":28,"util":31}],3:[function(require,module,exports){
},{}],4:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = Buffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
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() && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding, noZero) {
if (!(this instanceof Buffer))
return new Buffer(subject, encoding, noZero)
var type = typeof subject
// Find the length
var length
if (type === 'number')
length = subject > 0 ? subject >>> 0 : 0
else if (type === 'string') {
if (encoding === 'base64')
subject = base64clean(subject)
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) { // assume object is array-like
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 (this.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) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
buf = Buffer._augment(new Uint8Array(length))
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
buf = this
buf.length = length
buf._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
buf._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
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
}
}
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
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
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)
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
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
}
}
// must be an even number of digits
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, 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, offset, length, 2)
return charsWritten
}
Buffer.prototype.write = function (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
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] <= 0x7F) {
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])
}
return ret
}
function binarySlice (buf, start, end) {
return asciiSlice(buf, start, end)
}
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
if (Buffer.TYPED_ARRAY_SUPPORT) {
return Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
var newBuf = new Buffer(sliceLen, undefined, true)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
return newBuf
}
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0)
throw new RangeError('offset is not uint')
if (offset + ext > length)
throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.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] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readInt8 = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80))
return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function (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 TypeError('value is out of bounds')
if (offset + ext > buf.length) throw new TypeError('index out of range')
}
Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
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, 0xffff, 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 = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} 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, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else objectWriteUInt32(this, value, offset, false)
return offset + 4
}
Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
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, 0x7fff, -0x8000)
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, 0x7fffffff, -0x80000000)
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, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else objectWriteUInt32(this, value, offset, false)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new TypeError('value is out of bounds')
if (offset + ext > buf.length) throw new TypeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert)
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function (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.7976931348623157E+308, -1.7976931348623157E+308)
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)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
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_start = 0
// Copy 0 bytes; we're done
if (end === start) return
if (target.length === 0 || source.length === 0) return
// Fatal error conditions
if (end < start) throw new TypeError('sourceEnd < sourceStart')
if (target_start < 0 || target_start >= target.length)
throw new TypeError('targetStart out of bounds')
if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
// Are we oob?
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 < 1000 || !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)
}
}
// fill(value, start=0, end=buffer.length)
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 TypeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
if (end < 0 || end > this.length) throw new TypeError('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
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
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')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array get/set methods before overwriting
arr._get = arr.get
arr._set = arr.set
// deprecated, will be removed in node 0.13+
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.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
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.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
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) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function 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 (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
var b = str.charCodeAt(i)
if (b <= 0x7F) {
byteArray.push(b)
} else {
var start = i
if (b >= 0xD800 && b <= 0xDFFF) i++
var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
for (var j = 0; j < h.length; j++) {
byteArray.push(parseInt(h[j], 16))
}
}
}
return byteArray
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(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(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":5,"ieee754":6,"is-array":7}],5:[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)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS)
return 62 // '+'
if (code === SLASH)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
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')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
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 & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} 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) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
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)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],6:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],7:[function(require,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],8:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
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 = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
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') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.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;
}
},{}],9:[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
}
}
},{}],10:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
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');
};
},{}],11:[function(require,module,exports){
(function (global){
/*! http://mths.be/punycode v1.2.4 by @mathias */
;(function(root) {
/** Detect free variables */
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;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
while (length--) {
array[length] = fn(array[length]);
}
return array;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings.
* @private
* @param {String} domain The domain name.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
return map(string.split(regexSeparators), fn).join('.');
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <http://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* http://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols to a Punycode string of ASCII-only
* symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name to Unicode. Only the
* Punycoded parts of the domain name will be converted, i.e. it doesn't
* matter if you call it on a string that has already been converted to
* Unicode.
* @memberOf punycode
* @param {String} domain The Punycode domain name to convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(domain) {
return mapDomain(domain, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name to Punycode. Only the
* non-ASCII parts of the domain name will be converted, i.e. it doesn't
* matter if you call it with a domain that's already in ASCII.
* @memberOf punycode
* @param {String} domain The domain name to convert, as a Unicode string.
* @returns {String} The Punycode representation of the given domain name.
*/
function toASCII(domain) {
return mapDomain(domain, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.2.4',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <http://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = punycode;
} else { // in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else { // in Rhino or a web browser
root.punycode = punycode;
}
}(this));
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],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';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],13:[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;
};
},{}],14:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":12,"./encode":13}],15:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":16}],16:[function(require,module,exports){
(function (process){
// 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
module.exports = Duplex;
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
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);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
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("FWaASH"))
},{"./_stream_readable":18,"./_stream_writable":20,"FWaASH":10,"core-util-is":21,"inherits":9}],17:[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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
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":19,"core-util-is":21,"inherits":9}],18:[function(require,module,exports){
(function (process){
// 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.
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
/*<replacement>*/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
var Stream = require('stream');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var StringDecoder;
/*<replacement>*/
var debug = require('util');
if (debug && debug.debuglog) {
debug = debug.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.readableObjectMode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
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) {
var Duplex = require('./_stream_duplex');
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (util.isString(chunk) && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
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 (util.isNullOrUndefined(chunk)) {
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);
if (!addToFront)
state.reading = false;
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront)
state.buffer.unshift(chunk);
else
state.buffer.push(chunk);
if (state.needReadable)
emitReadable(stream);
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
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 (isNaN(n) || util.isNull(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
debug('read', n);
var state = this._readableState;
var nOrig = n;
if (!util.isNumber(n) || n > 0)
state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended)
endReadable(this);
else
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0)
endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
}
if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0)
state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
}
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (doRead && !state.reading)
n = howMuchToRead(nOrig, state);
var ret;
if (n > 0)
ret = fromList(n, state);
else
ret = null;
if (util.isNull(ret)) {
state.needReadable = true;
n = 0;
}
state.length -= n;
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (state.length === 0 && !state.ended)
state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended && state.length === 0)
endReadable(this);
if (!util.isNull(ret))
this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!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;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync)
process.nextTick(function() {
emitReadable_(stream);
});
else
emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
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) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;
else
len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
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;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
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) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
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);
src.removeListener('data', ondata);
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain &&
(!dest._writableState || dest._writableState.needDrain))
ondrain();
}
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
var ret = dest.write(chunk);
if (false === ret) {
debug('false write response, pause',
src._readableState.awaitDrain);
src._readableState.awaitDrain++;
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EE.listenerCount(dest, 'error') === 0)
dest.emit('error', er);
}
// This is a brutally ugly hack to make sure that our error handler
// is attached before any userland ones. NEVER DO THIS.
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];
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function() {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain)
state.awaitDrain--;
if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function(dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0)
return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes)
return this;
if (!dest)
dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest)
dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++)
dests[i].emit('unpipe', this);
return this;
}
// try to find the right one.
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;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
// If listening to data, and it has not explicitly been paused,
// then call resume to start the flow of data on the next tick.
if (ev === 'data' && false !== this._readableState.flowing) {
this.resume();
}
if (ev === 'readable' && this.readable) {
var state = this._readableState;
if (!state.readableListening) {
state.readableListening = true;
state.emittedReadable = false;
state.needReadable = true;
if (!state.reading) {
var self = this;
process.nextTick(function() {
debug('readable nexttick read 0');
self.read(0);
});
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
if (!state.reading) {
debug('resume read 0');
this.read(0);
}
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
process.nextTick(function() {
resume_(stream, state);
});
}
}
function resume_(stream, state) {
state.resumeScheduled = false;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading)
stream.read(0);
}
Readable.prototype.pause = function() {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
if (state.flowing) {
do {
var chunk = stream.read();
} while (null !== chunk && state.flowing);
}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function() {
debug('wrapped end');
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) {
debug('wrapped data');
if (state.decoder)
chunk = state.decoder.write(chunk);
if (!chunk || !state.objectMode && !chunk.length)
return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments);
}}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function(ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function(n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
var list = state.buffer;
var length = state.length;
var stringMode = !!state.decoder;
var objectMode = !!state.objectMode;
var ret;
// nothing in the list, definitely empty.
if (list.length === 0)
return null;
if (length === 0)
ret = null;
else if (objectMode)
ret = list.shift();
else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode)
ret = list.join('');
else
ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
// slice is the same for buffers and strings.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
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 we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0)
throw new Error('endReadable called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
process.nextTick(function() {
// Check that we didn't get one last unshift.
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("FWaASH"))
},{"./_stream_duplex":16,"FWaASH":10,"buffer":4,"core-util-is":21,"events":8,"inherits":9,"isarray":22,"stream":28,"string_decoder/":23,"util":3}],19:[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.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
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 (!util.isNullOrUndefined(data))
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);
this._transformState = new TransformState(options, this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
this.once('prefinish', function() {
if (util.isFunction(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);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
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);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
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":16,"core-util-is":21,"inherits":9}],20:[function(require,module,exports){
(function (process){
// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
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) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.writableObjectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
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');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!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 (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (util.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (!util.isFunction(cb))
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function() {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function() {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing &&
!state.corked &&
!state.finished &&
!state.bufferProcessing &&
state.buffer.length)
clearBuffer(this, state);
}
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
util.isString(chunk)) {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing || state.corked)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, false, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev)
stream._writev(chunk, state.onwrite);
else
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
state.pendingcb--;
cb(er);
});
else {
state.pendingcb--;
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 {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished &&
!state.corked &&
!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);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
if (stream._writev && state.buffer.length > 1) {
// Fast case, write everything using _writev()
var cbs = [];
for (var c = 0; c < state.buffer.length; c++)
cbs.push(state.buffer[c].callback);
// count the one we are adding, as well.
// TODO(isaacs) clean this up
state.pendingcb++;
doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
for (var i = 0; i < cbs.length; i++) {
state.pendingcb--;
cbs[i](err);
}
});
// Clear buffer
state.buffer = [];
} else {
// Slow case, write chunks one-by-one
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, false, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
state.bufferProcessing = false;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (util.isFunction(chunk)) {
cb = chunk;
chunk = null;
encoding = null;
} else if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (!util.isNullOrUndefined(chunk))
this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else
prefinish(stream, state);
}
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("FWaASH"))
},{"./_stream_duplex":16,"FWaASH":10,"buffer":4,"core-util-is":21,"inherits":9,"stream":28}],21:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,require("buffer").Buffer)
},{"buffer":4}],22:[function(require,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],23:[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.
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);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
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);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
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);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
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":4}],24:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":17}],25:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = require('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":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"stream":28}],26:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":19}],27:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":20}],28:[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.
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');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
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 the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
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();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
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);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":8,"inherits":9,"readable-stream/duplex.js":15,"readable-stream/passthrough.js":24,"readable-stream/readable.js":25,"readable-stream/transform.js":26,"readable-stream/writable.js":27}],29:[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.
var punycode = require('punycode');
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = require('querystring');
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && isObject(url) && url instanceof Url) return url;
var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (!isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] &&
(slashes || (proto && !slashedProtocol[proto]))) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a puny coded representation of "domain".
// It only converts the part of the domain name that
// has non ASCII characters. I.e. it dosent matter if
// you call it with a domain that already is in ASCII.
var domainArray = this.hostname.split('.');
var newOut = [];
for (var i = 0; i < domainArray.length; ++i) {
var s = domainArray[i];
newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
'xn--' + punycode.encode(s) : s);
}
this.hostname = newOut.join('.');
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
}
Url.prototype.format = function() {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ?
this.hostname :
'[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query &&
isObject(this.query) &&
Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes ||
(!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function(match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function(relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function(relative) {
if (isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
Object.keys(this).forEach(function(k) {
result[k] = this[k];
}, this);
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
Object.keys(relative).forEach(function(k) {
if (k !== 'protocol')
result[k] = relative[k];
});
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] &&
result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
Object.keys(relative).forEach(function(k) {
result[k] = relative[k];
});
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
isRelAbs = (
relative.host ||
relative.pathname && relative.pathname.charAt(0) === '/'
),
mustEndAbs = (isRelAbs || isSourceAbs ||
(result.host && relative.pathname)),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;
else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;
else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = (relative.host || relative.host === '') ?
relative.host : result.host;
result.hostname = (relative.hostname || relative.hostname === '') ?
relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especialy happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!isNull(result.pathname) || !isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host) && (last === '.' || last === '..') ||
last === '');
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last == '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' &&
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' ||
(srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especialy happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!isNull(result.pathname) || !isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function() {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};
function isString(arg) {
return typeof arg === "string";
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isNull(arg) {
return arg === null;
}
function isNullOrUndefined(arg) {
return arg == null;
}
},{"punycode":11,"querystring":14}],30:[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';
}
},{}],31:[function(require,module,exports){
(function (process,global){
// 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.
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;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
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];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
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;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
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]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + 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) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
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 = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
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');
// For some reason typeof null is "object", so special case here.
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];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
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' || // ES6 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'];
// 26 Feb 16:19:34
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(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
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("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":30,"FWaASH":10,"inherits":9}],32:[function(require,module,exports){
!function() {
var d3 = {
version: "3.5.16"
};
var d3_arraySlice = [].slice, d3_array = function(list) {
return d3_arraySlice.call(list);
};
var d3_document = this.document;
function d3_documentElement(node) {
return node && (node.ownerDocument || node.document || node).documentElement;
}
function d3_window(node) {
return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
}
if (d3_document) {
try {
d3_array(d3_document.documentElement.childNodes)[0].nodeType;
} catch (e) {
d3_array = function(list) {
var i = list.length, array = new Array(i);
while (i--) array[i] = list[i];
return array;
};
}
}
if (!Date.now) Date.now = function() {
return +new Date();
};
if (d3_document) {
try {
d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
} catch (error) {
var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
d3_element_prototype.setAttribute = function(name, value) {
d3_element_setAttribute.call(this, name, value + "");
};
d3_element_prototype.setAttributeNS = function(space, local, value) {
d3_element_setAttributeNS.call(this, space, local, value + "");
};
d3_style_prototype.setProperty = function(name, value, priority) {
d3_style_setProperty.call(this, name, value + "", priority);
};
}
}
d3.ascending = d3_ascending;
function d3_ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
d3.descending = function(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
};
d3.min = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n) if ((b = array[i]) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = array[i]) != null && a > b) a = b;
} else {
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
}
return a;
};
d3.max = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n) if ((b = array[i]) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = array[i]) != null && b > a) a = b;
} else {
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
}
return a;
};
d3.extent = function(array, f) {
var i = -1, n = array.length, a, b, c;
if (arguments.length === 1) {
while (++i < n) if ((b = array[i]) != null && b >= b) {
a = c = b;
break;
}
while (++i < n) if ((b = array[i]) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
} else {
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
a = c = b;
break;
}
while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
}
return [ a, c ];
};
function d3_number(x) {
return x === null ? NaN : +x;
}
function d3_numeric(x) {
return !isNaN(x);
}
d3.sum = function(array, f) {
var s = 0, n = array.length, a, i = -1;
if (arguments.length === 1) {
while (++i < n) if (d3_numeric(a = +array[i])) s += a;
} else {
while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
}
return s;
};
d3.mean = function(array, f) {
var s = 0, n = array.length, a, i = -1, j = n;
if (arguments.length === 1) {
while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j;
} else {
while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j;
}
if (j) return s / j;
};
d3.quantile = function(values, p) {
var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
return e ? v + e * (values[h] - v) : v;
};
d3.median = function(array, f) {
var numbers = [], n = array.length, a, i = -1;
if (arguments.length === 1) {
while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
} else {
while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
}
if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5);
};
d3.variance = function(array, f) {
var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
if (arguments.length === 1) {
while (++i < n) {
if (d3_numeric(a = d3_number(array[i]))) {
d = a - m;
m += d / ++j;
s += d * (a - m);
}
}
} else {
while (++i < n) {
if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
d = a - m;
m += d / ++j;
s += d * (a - m);
}
}
}
if (j > 1) return s / (j - 1);
};
d3.deviation = function() {
var v = d3.variance.apply(this, arguments);
return v ? Math.sqrt(v) : v;
};
function d3_bisector(compare) {
return {
left: function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid;
}
return lo;
},
right: function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1;
}
return lo;
}
};
}
var d3_bisect = d3_bisector(d3_ascending);
d3.bisectLeft = d3_bisect.left;
d3.bisect = d3.bisectRight = d3_bisect.right;
d3.bisector = function(f) {
return d3_bisector(f.length === 1 ? function(d, x) {
return d3_ascending(f(d), x);
} : f);
};
d3.shuffle = function(array, i0, i1) {
if ((m = arguments.length) < 3) {
i1 = array.length;
if (m < 2) i0 = 0;
}
var m = i1 - i0, t, i;
while (m) {
i = Math.random() * m-- | 0;
t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
}
return array;
};
d3.permute = function(array, indexes) {
var i = indexes.length, permutes = new Array(i);
while (i--) permutes[i] = array[indexes[i]];
return permutes;
};
d3.pairs = function(array) {
var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
return pairs;
};
d3.transpose = function(matrix) {
if (!(n = matrix.length)) return [];
for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) {
for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) {
row[j] = matrix[j][i];
}
}
return transpose;
};
function d3_transposeLength(d) {
return d.length;
}
d3.zip = function() {
return d3.transpose(arguments);
};
d3.keys = function(map) {
var keys = [];
for (var key in map) keys.push(key);
return keys;
};
d3.values = function(map) {
var values = [];
for (var key in map) values.push(map[key]);
return values;
};
d3.entries = function(map) {
var entries = [];
for (var key in map) entries.push({
key: key,
value: map[key]
});
return entries;
};
d3.merge = function(arrays) {
var n = arrays.length, m, i = -1, j = 0, merged, array;
while (++i < n) j += arrays[i].length;
merged = new Array(j);
while (--n >= 0) {
array = arrays[n];
m = array.length;
while (--m >= 0) {
merged[--j] = array[m];
}
}
return merged;
};
var abs = Math.abs;
d3.range = function(start, stop, step) {
if (arguments.length < 3) {
step = 1;
if (arguments.length < 2) {
stop = start;
start = 0;
}
}
if ((stop - start) / step === Infinity) throw new Error("infinite range");
var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
start *= k, stop *= k, step *= k;
if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
return range;
};
function d3_range_integerScale(x) {
var k = 1;
while (x * k % 1) k *= 10;
return k;
}
function d3_class(ctor, properties) {
for (var key in properties) {
Object.defineProperty(ctor.prototype, key, {
value: properties[key],
enumerable: false
});
}
}
d3.map = function(object, f) {
var map = new d3_Map();
if (object instanceof d3_Map) {
object.forEach(function(key, value) {
map.set(key, value);
});
} else if (Array.isArray(object)) {
var i = -1, n = object.length, o;
if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o);
} else {
for (var key in object) map.set(key, object[key]);
}
return map;
};
function d3_Map() {
this._ = Object.create(null);
}
var d3_map_proto = "__proto__", d3_map_zero = "\x00";
d3_class(d3_Map, {
has: d3_map_has,
get: function(key) {
return this._[d3_map_escape(key)];
},
set: function(key, value) {
return this._[d3_map_escape(key)] = value;
},
remove: d3_map_remove,
keys: d3_map_keys,
values: function() {
var values = [];
for (var key in this._) values.push(this._[key]);
return values;
},
entries: function() {
var entries = [];
for (var key in this._) entries.push({
key: d3_map_unescape(key),
value: this._[key]
});
return entries;
},
size: d3_map_size,
empty: d3_map_empty,
forEach: function(f) {
for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
}
});
function d3_map_escape(key) {
return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
}
function d3_map_unescape(key) {
return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
}
function d3_map_has(key) {
return d3_map_escape(key) in this._;
}
function d3_map_remove(key) {
return (key = d3_map_escape(key)) in this._ && delete this._[key];
}
function d3_map_keys() {
var keys = [];
for (var key in this._) keys.push(d3_map_unescape(key));
return keys;
}
function d3_map_size() {
var size = 0;
for (var key in this._) ++size;
return size;
}
function d3_map_empty() {
for (var key in this._) return false;
return true;
}
d3.nest = function() {
var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
function map(mapType, array, depth) {
if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
while (++i < n) {
if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
values.push(object);
} else {
valuesByKey.set(keyValue, [ object ]);
}
}
if (mapType) {
object = mapType();
setter = function(keyValue, values) {
object.set(keyValue, map(mapType, values, depth));
};
} else {
object = {};
setter = function(keyValue, values) {
object[keyValue] = map(mapType, values, depth);
};
}
valuesByKey.forEach(setter);
return object;
}
function entries(map, depth) {
if (depth >= keys.length) return map;
var array = [], sortKey = sortKeys[depth++];
map.forEach(function(key, keyMap) {
array.push({
key: key,
values: entries(keyMap, depth)
});
});
return sortKey ? array.sort(function(a, b) {
return sortKey(a.key, b.key);
}) : array;
}
nest.map = function(array, mapType) {
return map(mapType, array, 0);
};
nest.entries = function(array) {
return entries(map(d3.map, array, 0), 0);
};
nest.key = function(d) {
keys.push(d);
return nest;
};
nest.sortKeys = function(order) {
sortKeys[keys.length - 1] = order;
return nest;
};
nest.sortValues = function(order) {
sortValues = order;
return nest;
};
nest.rollup = function(f) {
rollup = f;
return nest;
};
return nest;
};
d3.set = function(array) {
var set = new d3_Set();
if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
return set;
};
function d3_Set() {
this._ = Object.create(null);
}
d3_class(d3_Set, {
has: d3_map_has,
add: function(key) {
this._[d3_map_escape(key += "")] = true;
return key;
},
remove: d3_map_remove,
values: d3_map_keys,
size: d3_map_size,
empty: d3_map_empty,
forEach: function(f) {
for (var key in this._) f.call(this, d3_map_unescape(key));
}
});
d3.behavior = {};
function d3_identity(d) {
return d;
}
d3.rebind = function(target, source) {
var i = 1, n = arguments.length, method;
while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
return target;
};
function d3_rebind(target, source, method) {
return function() {
var value = method.apply(source, arguments);
return value === source ? target : value;
};
}
function d3_vendorSymbol(object, name) {
if (name in object) return name;
name = name.charAt(0).toUpperCase() + name.slice(1);
for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
var prefixName = d3_vendorPrefixes[i] + name;
if (prefixName in object) return prefixName;
}
}
var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
function d3_noop() {}
d3.dispatch = function() {
var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
return dispatch;
};
function d3_dispatch() {}
d3_dispatch.prototype.on = function(type, listener) {
var i = type.indexOf("."), name = "";
if (i >= 0) {
name = type.slice(i + 1);
type = type.slice(0, i);
}
if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
if (arguments.length === 2) {
if (listener == null) for (type in this) {
if (this.hasOwnProperty(type)) this[type].on(name, null);
}
return this;
}
};
function d3_dispatch_event(dispatch) {
var listeners = [], listenerByName = new d3_Map();
function event() {
var z = listeners, i = -1, n = z.length, l;
while (++i < n) if (l = z[i].on) l.apply(this, arguments);
return dispatch;
}
event.on = function(name, listener) {
var l = listenerByName.get(name), i;
if (arguments.length < 2) return l && l.on;
if (l) {
l.on = null;
listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
listenerByName.remove(name);
}
if (listener) listeners.push(listenerByName.set(name, {
on: listener
}));
return dispatch;
};
return event;
}
d3.event = null;
function d3_eventPreventDefault() {
d3.event.preventDefault();
}
function d3_eventSource() {
var e = d3.event, s;
while (s = e.sourceEvent) e = s;
return e;
}
function d3_eventDispatch(target) {
var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
dispatch.of = function(thiz, argumentz) {
return function(e1) {
try {
var e0 = e1.sourceEvent = d3.event;
e1.target = target;
d3.event = e1;
dispatch[e1.type].apply(thiz, argumentz);
} finally {
d3.event = e0;
}
};
};
return dispatch;
}
d3.requote = function(s) {
return s.replace(d3_requote_re, "\\$&");
};
var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
var d3_subclass = {}.__proto__ ? function(object, prototype) {
object.__proto__ = prototype;
} : function(object, prototype) {
for (var property in prototype) object[property] = prototype[property];
};
function d3_selection(groups) {
d3_subclass(groups, d3_selectionPrototype);
return groups;
}
var d3_select = function(s, n) {
return n.querySelector(s);
}, d3_selectAll = function(s, n) {
return n.querySelectorAll(s);
}, d3_selectMatches = function(n, s) {
var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
d3_selectMatches = function(n, s) {
return d3_selectMatcher.call(n, s);
};
return d3_selectMatches(n, s);
};
if (typeof Sizzle === "function") {
d3_select = function(s, n) {
return Sizzle(s, n)[0] || null;
};
d3_selectAll = Sizzle;
d3_selectMatches = Sizzle.matchesSelector;
}
d3.selection = function() {
return d3.select(d3_document.documentElement);
};
var d3_selectionPrototype = d3.selection.prototype = [];
d3_selectionPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, group, node;
selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroup.push(subnode = selector.call(node, node.__data__, i, j));
if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selector(selector) {
return typeof selector === "function" ? selector : function() {
return d3_select(selector, this);
};
}
d3_selectionPrototype.selectAll = function(selector) {
var subgroups = [], subgroup, node;
selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
subgroup.parentNode = node;
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selectorAll(selector) {
return typeof selector === "function" ? selector : function() {
return d3_selectAll(selector, this);
};
}
var d3_nsXhtml = "http://www.w3.org/1999/xhtml";
var d3_nsPrefix = {
svg: "http://www.w3.org/2000/svg",
xhtml: d3_nsXhtml,
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
};
d3.ns = {
prefix: d3_nsPrefix,
qualify: function(name) {
var i = name.indexOf(":"), prefix = name;
if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
return d3_nsPrefix.hasOwnProperty(prefix) ? {
space: d3_nsPrefix[prefix],
local: name
} : name;
}
};
d3_selectionPrototype.attr = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") {
var node = this.node();
name = d3.ns.qualify(name);
return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
}
for (value in name) this.each(d3_selection_attr(value, name[value]));
return this;
}
return this.each(d3_selection_attr(name, value));
};
function d3_selection_attr(name, value) {
name = d3.ns.qualify(name);
function attrNull() {
this.removeAttribute(name);
}
function attrNullNS() {
this.removeAttributeNS(name.space, name.local);
}
function attrConstant() {
this.setAttribute(name, value);
}
function attrConstantNS() {
this.setAttributeNS(name.space, name.local, value);
}
function attrFunction() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
}
function attrFunctionNS() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
}
return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
}
function d3_collapse(s) {
return s.trim().replace(/\s+/g, " ");
}
d3_selectionPrototype.classed = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") {
var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1;
if (value = node.classList) {
while (++i < n) if (!value.contains(name[i])) return false;
} else {
value = node.getAttribute("class");
while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
}
return true;
}
for (value in name) this.each(d3_selection_classed(value, name[value]));
return this;
}
return this.each(d3_selection_classed(name, value));
};
function d3_selection_classedRe(name) {
return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
}
function d3_selection_classes(name) {
return (name + "").trim().split(/^|\s+/);
}
function d3_selection_classed(name, value) {
name = d3_selection_classes(name).map(d3_selection_classedName);
var n = name.length;
function classedConstant() {
var i = -1;
while (++i < n) name[i](this, value);
}
function classedFunction() {
var i = -1, x = value.apply(this, arguments);
while (++i < n) name[i](this, x);
}
return typeof value === "function" ? classedFunction : classedConstant;
}
function d3_selection_classedName(name) {
var re = d3_selection_classedRe(name);
return function(node, value) {
if (c = node.classList) return value ? c.add(name) : c.remove(name);
var c = node.getAttribute("class") || "";
if (value) {
re.lastIndex = 0;
if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
} else {
node.setAttribute("class", d3_collapse(c.replace(re, " ")));
}
};
}
d3_selectionPrototype.style = function(name, value, priority) {
var n = arguments.length;
if (n < 3) {
if (typeof name !== "string") {
if (n < 2) value = "";
for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
return this;
}
if (n < 2) {
var node = this.node();
return d3_window(node).getComputedStyle(node, null).getPropertyValue(name);
}
priority = "";
}
return this.each(d3_selection_style(name, value, priority));
};
function d3_selection_style(name, value, priority) {
function styleNull() {
this.style.removeProperty(name);
}
function styleConstant() {
this.style.setProperty(name, value, priority);
}
function styleFunction() {
var x = value.apply(this, arguments);
if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
}
return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
}
d3_selectionPrototype.property = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") return this.node()[name];
for (value in name) this.each(d3_selection_property(value, name[value]));
return this;
}
return this.each(d3_selection_property(name, value));
};
function d3_selection_property(name, value) {
function propertyNull() {
delete this[name];
}
function propertyConstant() {
this[name] = value;
}
function propertyFunction() {
var x = value.apply(this, arguments);
if (x == null) delete this[name]; else this[name] = x;
}
return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
}
d3_selectionPrototype.text = function(value) {
return arguments.length ? this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
} : value == null ? function() {
this.textContent = "";
} : function() {
this.textContent = value;
}) : this.node().textContent;
};
d3_selectionPrototype.html = function(value) {
return arguments.length ? this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.innerHTML = v == null ? "" : v;
} : value == null ? function() {
this.innerHTML = "";
} : function() {
this.innerHTML = value;
}) : this.node().innerHTML;
};
d3_selectionPrototype.append = function(name) {
name = d3_selection_creator(name);
return this.select(function() {
return this.appendChild(name.apply(this, arguments));
});
};
function d3_selection_creator(name) {
function create() {
var document = this.ownerDocument, namespace = this.namespaceURI;
return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name);
}
function createNS() {
return this.ownerDocument.createElementNS(name.space, name.local);
}
return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create;
}
d3_selectionPrototype.insert = function(name, before) {
name = d3_selection_creator(name);
before = d3_selection_selector(before);
return this.select(function() {
return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
});
};
d3_selectionPrototype.remove = function() {
return this.each(d3_selectionRemove);
};
function d3_selectionRemove() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
}
d3_selectionPrototype.data = function(value, key) {
var i = -1, n = this.length, group, node;
if (!arguments.length) {
value = new Array(n = (group = this[0]).length);
while (++i < n) {
if (node = group[i]) {
value[i] = node.__data__;
}
}
return value;
}
function bind(group, groupData) {
var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
if (key) {
var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue;
for (i = -1; ++i < n; ) {
if (node = group[i]) {
if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) {
exitNodes[i] = node;
} else {
nodeByKeyValue.set(keyValue, node);
}
keyValues[i] = keyValue;
}
}
for (i = -1; ++i < m; ) {
if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) {
enterNodes[i] = d3_selection_dataNode(nodeData);
} else if (node !== true) {
updateNodes[i] = node;
node.__data__ = nodeData;
}
nodeByKeyValue.set(keyValue, true);
}
for (i = -1; ++i < n; ) {
if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) {
exitNodes[i] = group[i];
}
}
} else {
for (i = -1; ++i < n0; ) {
node = group[i];
nodeData = groupData[i];
if (node) {
node.__data__ = nodeData;
updateNodes[i] = node;
} else {
enterNodes[i] = d3_selection_dataNode(nodeData);
}
}
for (;i < m; ++i) {
enterNodes[i] = d3_selection_dataNode(groupData[i]);
}
for (;i < n; ++i) {
exitNodes[i] = group[i];
}
}
enterNodes.update = updateNodes;
enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
enter.push(enterNodes);
update.push(updateNodes);
exit.push(exitNodes);
}
var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
if (typeof value === "function") {
while (++i < n) {
bind(group = this[i], value.call(group, group.parentNode.__data__, i));
}
} else {
while (++i < n) {
bind(group = this[i], value);
}
}
update.enter = function() {
return enter;
};
update.exit = function() {
return exit;
};
return update;
};
function d3_selection_dataNode(data) {
return {
__data__: data
};
}
d3_selectionPrototype.datum = function(value) {
return arguments.length ? this.property("__data__", value) : this.property("__data__");
};
d3_selectionPrototype.filter = function(filter) {
var subgroups = [], subgroup, group, node;
if (typeof filter !== "function") filter = d3_selection_filter(filter);
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
subgroup.push(node);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_filter(selector) {
return function() {
return d3_selectMatches(this, selector);
};
}
d3_selectionPrototype.order = function() {
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
if (node = group[i]) {
if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
next = node;
}
}
}
return this;
};
d3_selectionPrototype.sort = function(comparator) {
comparator = d3_selection_sortComparator.apply(this, arguments);
for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
return this.order();
};
function d3_selection_sortComparator(comparator) {
if (!arguments.length) comparator = d3_ascending;
return function(a, b) {
return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
};
}
d3_selectionPrototype.each = function(callback) {
return d3_selection_each(this, function(node, i, j) {
callback.call(node, node.__data__, i, j);
});
};
function d3_selection_each(groups, callback) {
for (var j = 0, m = groups.length; j < m; j++) {
for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
if (node = group[i]) callback(node, i, j);
}
}
return groups;
}
d3_selectionPrototype.call = function(callback) {
var args = d3_array(arguments);
callback.apply(args[0] = this, args);
return this;
};
d3_selectionPrototype.empty = function() {
return !this.node();
};
d3_selectionPrototype.node = function() {
for (var j = 0, m = this.length; j < m; j++) {
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
var node = group[i];
if (node) return node;
}
}
return null;
};
d3_selectionPrototype.size = function() {
var n = 0;
d3_selection_each(this, function() {
++n;
});
return n;
};
function d3_selection_enter(selection) {
d3_subclass(selection, d3_selection_enterPrototype);
return selection;
}
var d3_selection_enterPrototype = [];
d3.selection.enter = d3_selection_enter;
d3.selection.enter.prototype = d3_selection_enterPrototype;
d3_selection_enterPrototype.append = d3_selectionPrototype.append;
d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
d3_selection_enterPrototype.node = d3_selectionPrototype.node;
d3_selection_enterPrototype.call = d3_selectionPrototype.call;
d3_selection_enterPrototype.size = d3_selectionPrototype.size;
d3_selection_enterPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, upgroup, group, node;
for (var j = -1, m = this.length; ++j < m; ) {
upgroup = (group = this[j]).update;
subgroups.push(subgroup = []);
subgroup.parentNode = group.parentNode;
for (var i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
d3_selection_enterPrototype.insert = function(name, before) {
if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
return d3_selectionPrototype.insert.call(this, name, before);
};
function d3_selection_enterInsertBefore(enter) {
var i0, j0;
return function(d, i, j) {
var group = enter[j].update, n = group.length, node;
if (j != j0) j0 = j, i0 = 0;
if (i >= i0) i0 = i + 1;
while (!(node = group[i0]) && ++i0 < n) ;
return node;
};
}
d3.select = function(node) {
var group;
if (typeof node === "string") {
group = [ d3_select(node, d3_document) ];
group.parentNode = d3_document.documentElement;
} else {
group = [ node ];
group.parentNode = d3_documentElement(node);
}
return d3_selection([ group ]);
};
d3.selectAll = function(nodes) {
var group;
if (typeof nodes === "string") {
group = d3_array(d3_selectAll(nodes, d3_document));
group.parentNode = d3_document.documentElement;
} else {
group = d3_array(nodes);
group.parentNode = null;
}
return d3_selection([ group ]);
};
d3_selectionPrototype.on = function(type, listener, capture) {
var n = arguments.length;
if (n < 3) {
if (typeof type !== "string") {
if (n < 2) listener = false;
for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
return this;
}
if (n < 2) return (n = this.node()["__on" + type]) && n._;
capture = false;
}
return this.each(d3_selection_on(type, listener, capture));
};
function d3_selection_on(type, listener, capture) {
var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
if (i > 0) type = type.slice(0, i);
var filter = d3_selection_onFilters.get(type);
if (filter) type = filter, wrap = d3_selection_onFilter;
function onRemove() {
var l = this[name];
if (l) {
this.removeEventListener(type, l, l.$);
delete this[name];
}
}
function onAdd() {
var l = wrap(listener, d3_array(arguments));
onRemove.call(this);
this.addEventListener(type, this[name] = l, l.$ = capture);
l._ = listener;
}
function removeAll() {
var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
for (var name in this) {
if (match = name.match(re)) {
var l = this[name];
this.removeEventListener(match[1], l, l.$);
delete this[name];
}
}
}
return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
}
var d3_selection_onFilters = d3.map({
mouseenter: "mouseover",
mouseleave: "mouseout"
});
if (d3_document) {
d3_selection_onFilters.forEach(function(k) {
if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
});
}
function d3_selection_onListener(listener, argumentz) {
return function(e) {
var o = d3.event;
d3.event = e;
argumentz[0] = this.__data__;
try {
listener.apply(this, argumentz);
} finally {
d3.event = o;
}
};
}
function d3_selection_onFilter(listener, argumentz) {
var l = d3_selection_onListener(listener, argumentz);
return function(e) {
var target = this, related = e.relatedTarget;
if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
l.call(target, e);
}
};
}
var d3_event_dragSelect, d3_event_dragId = 0;
function d3_event_dragSuppress(node) {
var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
if (d3_event_dragSelect == null) {
d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
}
if (d3_event_dragSelect) {
var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
style[d3_event_dragSelect] = "none";
}
return function(suppressClick) {
w.on(name, null);
if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
if (suppressClick) {
var off = function() {
w.on(click, null);
};
w.on(click, function() {
d3_eventPreventDefault();
off();
}, true);
setTimeout(off, 0);
}
};
}
d3.mouse = function(container) {
return d3_mousePoint(container, d3_eventSource());
};
var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
function d3_mousePoint(container, e) {
if (e.changedTouches) e = e.changedTouches[0];
var svg = container.ownerSVGElement || container;
if (svg.createSVGPoint) {
var point = svg.createSVGPoint();
if (d3_mouse_bug44083 < 0) {
var window = d3_window(container);
if (window.scrollX || window.scrollY) {
svg = d3.select("body").append("svg").style({
position: "absolute",
top: 0,
left: 0,
margin: 0,
padding: 0,
border: "none"
}, "important");
var ctm = svg[0][0].getScreenCTM();
d3_mouse_bug44083 = !(ctm.f || ctm.e);
svg.remove();
}
}
if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX,
point.y = e.clientY;
point = point.matrixTransform(container.getScreenCTM().inverse());
return [ point.x, point.y ];
}
var rect = container.getBoundingClientRect();
return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
}
d3.touch = function(container, touches, identifier) {
if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
if ((touch = touches[i]).identifier === identifier) {
return d3_mousePoint(container, touch);
}
}
};
d3.behavior.drag = function() {
var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
function drag() {
this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
}
function dragstart(id, position, subject, move, end) {
return function() {
var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
if (origin) {
dragOffset = origin.apply(that, arguments);
dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ];
} else {
dragOffset = [ 0, 0 ];
}
dispatch({
type: "dragstart"
});
function moved() {
var position1 = position(parent, dragId), dx, dy;
if (!position1) return;
dx = position1[0] - position0[0];
dy = position1[1] - position0[1];
dragged |= dx | dy;
position0 = position1;
dispatch({
type: "drag",
x: position1[0] + dragOffset[0],
y: position1[1] + dragOffset[1],
dx: dx,
dy: dy
});
}
function ended() {
if (!position(parent, dragId)) return;
dragSubject.on(move + dragName, null).on(end + dragName, null);
dragRestore(dragged);
dispatch({
type: "dragend"
});
}
};
}
drag.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
return drag;
};
return d3.rebind(drag, event, "on");
};
function d3_behavior_dragTouchId() {
return d3.event.changedTouches[0].identifier;
}
d3.touches = function(container, touches) {
if (arguments.length < 2) touches = d3_eventSource().touches;
return touches ? d3_array(touches).map(function(touch) {
var point = d3_mousePoint(container, touch);
point.identifier = touch.identifier;
return point;
}) : [];
};
var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
function d3_sgn(x) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
}
function d3_cross2d(a, b, c) {
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
}
function d3_acos(x) {
return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
}
function d3_asin(x) {
return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
}
function d3_sinh(x) {
return ((x = Math.exp(x)) - 1 / x) / 2;
}
function d3_cosh(x) {
return ((x = Math.exp(x)) + 1 / x) / 2;
}
function d3_tanh(x) {
return ((x = Math.exp(2 * x)) - 1) / (x + 1);
}
function d3_haversin(x) {
return (x = Math.sin(x / 2)) * x;
}
var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4;
d3.interpolateZoom = function(p0, p1) {
var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
if (d2 < ε2) {
S = Math.log(w1 / w0) / ρ;
i = function(t) {
return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ];
};
} else {
var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
S = (r1 - r0) / ρ;
i = function(t) {
var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0));
return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ];
};
}
i.duration = S * 1e3;
return i;
};
d3.behavior.zoom = function() {
var view = {
x: 0,
y: 0,
k: 1
}, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
if (!d3_behavior_zoomWheel) {
d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
}, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
return d3.event.wheelDelta;
}, "mousewheel") : (d3_behavior_zoomDelta = function() {
return -d3.event.detail;
}, "MozMousePixelScroll");
}
function zoom(g) {
g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
}
zoom.event = function(g) {
g.each(function() {
var dispatch = event.of(this, arguments), view1 = view;
if (d3_transitionInheritId) {
d3.select(this).transition().each("start.zoom", function() {
view = this.__chart__ || {
x: 0,
y: 0,
k: 1
};
zoomstarted(dispatch);
}).tween("zoom:zoom", function() {
var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
return function(t) {
var l = i(t), k = dx / l[2];
this.__chart__ = view = {
x: cx - l[0] * k,
y: cy - l[1] * k,
k: k
};
zoomed(dispatch);
};
}).each("interrupt.zoom", function() {
zoomended(dispatch);
}).each("end.zoom", function() {
zoomended(dispatch);
});
} else {
this.__chart__ = view;
zoomstarted(dispatch);
zoomed(dispatch);
zoomended(dispatch);
}
});
};
zoom.translate = function(_) {
if (!arguments.length) return [ view.x, view.y ];
view = {
x: +_[0],
y: +_[1],
k: view.k
};
rescale();
return zoom;
};
zoom.scale = function(_) {
if (!arguments.length) return view.k;
view = {
x: view.x,
y: view.y,
k: null
};
scaleTo(+_);
rescale();
return zoom;
};
zoom.scaleExtent = function(_) {
if (!arguments.length) return scaleExtent;
scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
return zoom;
};
zoom.center = function(_) {
if (!arguments.length) return center;
center = _ && [ +_[0], +_[1] ];
return zoom;
};
zoom.size = function(_) {
if (!arguments.length) return size;
size = _ && [ +_[0], +_[1] ];
return zoom;
};
zoom.duration = function(_) {
if (!arguments.length) return duration;
duration = +_;
return zoom;
};
zoom.x = function(z) {
if (!arguments.length) return x1;
x1 = z;
x0 = z.copy();
view = {
x: 0,
y: 0,
k: 1
};
return zoom;
};
zoom.y = function(z) {
if (!arguments.length) return y1;
y1 = z;
y0 = z.copy();
view = {
x: 0,
y: 0,
k: 1
};
return zoom;
};
function location(p) {
return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
}
function point(l) {
return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
}
function scaleTo(s) {
view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
}
function translateTo(p, l) {
l = point(l);
view.x += p[0] - l[0];
view.y += p[1] - l[1];
}
function zoomTo(that, p, l, k) {
that.__chart__ = {
x: view.x,
y: view.y,
k: view.k
};
scaleTo(Math.pow(2, k));
translateTo(center0 = p, l);
that = d3.select(that);
if (duration > 0) that = that.transition().duration(duration);
that.call(zoom.event);
}
function rescale() {
if (x1) x1.domain(x0.range().map(function(x) {
return (x - view.x) / view.k;
}).map(x0.invert));
if (y1) y1.domain(y0.range().map(function(y) {
return (y - view.y) / view.k;
}).map(y0.invert));
}
function zoomstarted(dispatch) {
if (!zooming++) dispatch({
type: "zoomstart"
});
}
function zoomed(dispatch) {
rescale();
dispatch({
type: "zoom",
scale: view.k,
translate: [ view.x, view.y ]
});
}
function zoomended(dispatch) {
if (!--zooming) dispatch({
type: "zoomend"
}), center0 = null;
}
function mousedowned() {
var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
d3_selection_interrupt.call(that);
zoomstarted(dispatch);
function moved() {
dragged = 1;
translateTo(d3.mouse(that), location0);
zoomed(dispatch);
}
function ended() {
subject.on(mousemove, null).on(mouseup, null);
dragRestore(dragged);
zoomended(dispatch);
}
}
function touchstarted() {
var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
started();
zoomstarted(dispatch);
subject.on(mousedown, null).on(touchstart, started);
function relocate() {
var touches = d3.touches(that);
scale0 = view.k;
touches.forEach(function(t) {
if (t.identifier in locations0) locations0[t.identifier] = location(t);
});
return touches;
}
function started() {
var target = d3.event.target;
d3.select(target).on(touchmove, moved).on(touchend, ended);
targets.push(target);
var changed = d3.event.changedTouches;
for (var i = 0, n = changed.length; i < n; ++i) {
locations0[changed[i].identifier] = null;
}
var touches = relocate(), now = Date.now();
if (touches.length === 1) {
if (now - touchtime < 500) {
var p = touches[0];
zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
d3_eventPreventDefault();
}
touchtime = now;
} else if (touches.length > 1) {
var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
distance0 = dx * dx + dy * dy;
}
}
function moved() {
var touches = d3.touches(that), p0, l0, p1, l1;
d3_selection_interrupt.call(that);
for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
p1 = touches[i];
if (l1 = locations0[p1.identifier]) {
if (l0) break;
p0 = p1, l0 = l1;
}
}
if (l1) {
var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
scaleTo(scale1 * scale0);
}
touchtime = null;
translateTo(p0, l0);
zoomed(dispatch);
}
function ended() {
if (d3.event.touches.length) {
var changed = d3.event.changedTouches;
for (var i = 0, n = changed.length; i < n; ++i) {
delete locations0[changed[i].identifier];
}
for (var identifier in locations0) {
return void relocate();
}
}
d3.selectAll(targets).on(zoomName, null);
subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
dragRestore();
zoomended(dispatch);
}
}
function mousewheeled() {
var dispatch = event.of(this, arguments);
if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this),
translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
mousewheelTimer = setTimeout(function() {
mousewheelTimer = null;
zoomended(dispatch);
}, 50);
d3_eventPreventDefault();
scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
translateTo(center0, translate0);
zoomed(dispatch);
}
function dblclicked() {
var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
}
return d3.rebind(zoom, event, "on");
};
var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
d3.color = d3_color;
function d3_color() {}
d3_color.prototype.toString = function() {
return this.rgb() + "";
};
d3.hsl = d3_hsl;
function d3_hsl(h, s, l) {
return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
}
var d3_hslPrototype = d3_hsl.prototype = new d3_color();
d3_hslPrototype.brighter = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return new d3_hsl(this.h, this.s, this.l / k);
};
d3_hslPrototype.darker = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return new d3_hsl(this.h, this.s, k * this.l);
};
d3_hslPrototype.rgb = function() {
return d3_hsl_rgb(this.h, this.s, this.l);
};
function d3_hsl_rgb(h, s, l) {
var m1, m2;
h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
l = l < 0 ? 0 : l > 1 ? 1 : l;
m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
m1 = 2 * l - m2;
function v(h) {
if (h > 360) h -= 360; else if (h < 0) h += 360;
if (h < 60) return m1 + (m2 - m1) * h / 60;
if (h < 180) return m2;
if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
return m1;
}
function vv(h) {
return Math.round(v(h) * 255);
}
return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
}
d3.hcl = d3_hcl;
function d3_hcl(h, c, l) {
return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
}
var d3_hclPrototype = d3_hcl.prototype = new d3_color();
d3_hclPrototype.brighter = function(k) {
return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
};
d3_hclPrototype.darker = function(k) {
return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
};
d3_hclPrototype.rgb = function() {
return d3_hcl_lab(this.h, this.c, this.l).rgb();
};
function d3_hcl_lab(h, c, l) {
if (isNaN(h)) h = 0;
if (isNaN(c)) c = 0;
return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
}
d3.lab = d3_lab;
function d3_lab(l, a, b) {
return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
}
var d3_lab_K = 18;
var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
var d3_labPrototype = d3_lab.prototype = new d3_color();
d3_labPrototype.brighter = function(k) {
return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
};
d3_labPrototype.darker = function(k) {
return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
};
d3_labPrototype.rgb = function() {
return d3_lab_rgb(this.l, this.a, this.b);
};
function d3_lab_rgb(l, a, b) {
var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
x = d3_lab_xyz(x) * d3_lab_X;
y = d3_lab_xyz(y) * d3_lab_Y;
z = d3_lab_xyz(z) * d3_lab_Z;
return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
}
function d3_lab_hcl(l, a, b) {
return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
}
function d3_lab_xyz(x) {
return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
}
function d3_xyz_lab(x) {
return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
}
function d3_xyz_rgb(r) {
return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
}
d3.rgb = d3_rgb;
function d3_rgb(r, g, b) {
return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
}
function d3_rgbNumber(value) {
return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
}
function d3_rgbString(value) {
return d3_rgbNumber(value) + "";
}
var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
d3_rgbPrototype.brighter = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
var r = this.r, g = this.g, b = this.b, i = 30;
if (!r && !g && !b) return new d3_rgb(i, i, i);
if (r && r < i) r = i;
if (g && g < i) g = i;
if (b && b < i) b = i;
return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
};
d3_rgbPrototype.darker = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return new d3_rgb(k * this.r, k * this.g, k * this.b);
};
d3_rgbPrototype.hsl = function() {
return d3_rgb_hsl(this.r, this.g, this.b);
};
d3_rgbPrototype.toString = function() {
return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
};
function d3_rgb_hex(v) {
return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
}
function d3_rgb_parse(format, rgb, hsl) {
var r = 0, g = 0, b = 0, m1, m2, color;
m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
if (m1) {
m2 = m1[2].split(",");
switch (m1[1]) {
case "hsl":
{
return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
}
case "rgb":
{
return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
}
}
}
if (color = d3_rgb_names.get(format)) {
return rgb(color.r, color.g, color.b);
}
if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) {
if (format.length === 4) {
r = (color & 3840) >> 4;
r = r >> 4 | r;
g = color & 240;
g = g >> 4 | g;
b = color & 15;
b = b << 4 | b;
} else if (format.length === 7) {
r = (color & 16711680) >> 16;
g = (color & 65280) >> 8;
b = color & 255;
}
}
return rgb(r, g, b);
}
function d3_rgb_hsl(r, g, b) {
var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
if (d) {
s = l < .5 ? d / (max + min) : d / (2 - max - min);
if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
h *= 60;
} else {
h = NaN;
s = l > 0 && l < 1 ? 0 : h;
}
return new d3_hsl(h, s, l);
}
function d3_rgb_lab(r, g, b) {
r = d3_rgb_xyz(r);
g = d3_rgb_xyz(g);
b = d3_rgb_xyz(b);
var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
}
function d3_rgb_xyz(r) {
return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
}
function d3_rgb_parseNumber(c) {
var f = parseFloat(c);
return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
}
var d3_rgb_names = d3.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
});
d3_rgb_names.forEach(function(key, value) {
d3_rgb_names.set(key, d3_rgbNumber(value));
});
function d3_functor(v) {
return typeof v === "function" ? v : function() {
return v;
};
}
d3.functor = d3_functor;
d3.xhr = d3_xhrType(d3_identity);
function d3_xhrType(response) {
return function(url, mimeType, callback) {
if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType,
mimeType = null;
return d3_xhr(url, mimeType, response, callback);
};
}
function d3_xhr(url, mimeType, response, callback) {
var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
"onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
request.readyState > 3 && respond();
};
function respond() {
var status = request.status, result;
if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
try {
result = response.call(xhr, request);
} catch (e) {
dispatch.error.call(xhr, e);
return;
}
dispatch.load.call(xhr, result);
} else {
dispatch.error.call(xhr, request);
}
}
request.onprogress = function(event) {
var o = d3.event;
d3.event = event;
try {
dispatch.progress.call(xhr, request);
} finally {
d3.event = o;
}
};
xhr.header = function(name, value) {
name = (name + "").toLowerCase();
if (arguments.length < 2) return headers[name];
if (value == null) delete headers[name]; else headers[name] = value + "";
return xhr;
};
xhr.mimeType = function(value) {
if (!arguments.length) return mimeType;
mimeType = value == null ? null : value + "";
return xhr;
};
xhr.responseType = function(value) {
if (!arguments.length) return responseType;
responseType = value;
return xhr;
};
xhr.response = function(value) {
response = value;
return xhr;
};
[ "get", "post" ].forEach(function(method) {
xhr[method] = function() {
return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
};
});
xhr.send = function(method, data, callback) {
if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
request.open(method, url, true);
if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
if (responseType != null) request.responseType = responseType;
if (callback != null) xhr.on("error", callback).on("load", function(request) {
callback(null, request);
});
dispatch.beforesend.call(xhr, request);
request.send(data == null ? null : data);
return xhr;
};
xhr.abort = function() {
request.abort();
return xhr;
};
d3.rebind(xhr, dispatch, "on");
return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
}
function d3_xhr_fixCallback(callback) {
return callback.length === 1 ? function(error, request) {
callback(error == null ? request : null);
} : callback;
}
function d3_xhrHasResponse(request) {
var type = request.responseType;
return type && type !== "text" ? request.response : request.responseText;
}
d3.dsv = function(delimiter, mimeType) {
var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
function dsv(url, row, callback) {
if (arguments.length < 3) callback = row, row = null;
var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
xhr.row = function(_) {
return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
};
return xhr;
}
function response(request) {
return dsv.parse(request.responseText);
}
function typedResponse(f) {
return function(request) {
return dsv.parse(request.responseText, f);
};
}
dsv.parse = function(text, f) {
var o;
return dsv.parseRows(text, function(row, i) {
if (o) return o(row, i - 1);
var a = new Function("d", "return {" + row.map(function(name, i) {
return JSON.stringify(name) + ": d[" + i + "]";
}).join(",") + "}");
o = f ? function(row, i) {
return f(a(row), i);
} : a;
});
};
dsv.parseRows = function(text, f) {
var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
function token() {
if (I >= N) return EOF;
if (eol) return eol = false, EOL;
var j = I;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < N) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
++i;
}
}
I = i + 2;
var c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) ++I;
} else if (c === 10) {
eol = true;
}
return text.slice(j + 1, i).replace(/""/g, '"');
}
while (I < N) {
var c = text.charCodeAt(I++), k = 1;
if (c === 10) eol = true; else if (c === 13) {
eol = true;
if (text.charCodeAt(I) === 10) ++I, ++k;
} else if (c !== delimiterCode) continue;
return text.slice(j, I - k);
}
return text.slice(j);
}
while ((t = token()) !== EOF) {
var a = [];
while (t !== EOL && t !== EOF) {
a.push(t);
t = token();
}
if (f && (a = f(a, n++)) == null) continue;
rows.push(a);
}
return rows;
};
dsv.format = function(rows) {
if (Array.isArray(rows[0])) return dsv.formatRows(rows);
var fieldSet = new d3_Set(), fields = [];
rows.forEach(function(row) {
for (var field in row) {
if (!fieldSet.has(field)) {
fields.push(fieldSet.add(field));
}
}
});
return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
return fields.map(function(field) {
return formatValue(row[field]);
}).join(delimiter);
})).join("\n");
};
dsv.formatRows = function(rows) {
return rows.map(formatRow).join("\n");
};
function formatRow(row) {
return row.map(formatValue).join(delimiter);
}
function formatValue(text) {
return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
}
return dsv;
};
d3.csv = d3.dsv(",", "text/csv");
d3.tsv = d3.dsv(" ", "text/tab-separated-values");
var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
setTimeout(callback, 17);
};
d3.timer = function() {
d3_timer.apply(this, arguments);
};
function d3_timer(callback, delay, then) {
var n = arguments.length;
if (n < 2) delay = 0;
if (n < 3) then = Date.now();
var time = then + delay, timer = {
c: callback,
t: time,
n: null
};
if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
d3_timer_queueTail = timer;
if (!d3_timer_interval) {
d3_timer_timeout = clearTimeout(d3_timer_timeout);
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
return timer;
}
function d3_timer_step() {
var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
if (delay > 24) {
if (isFinite(delay)) {
clearTimeout(d3_timer_timeout);
d3_timer_timeout = setTimeout(d3_timer_step, delay);
}
d3_timer_interval = 0;
} else {
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
}
d3.timer.flush = function() {
d3_timer_mark();
d3_timer_sweep();
};
function d3_timer_mark() {
var now = Date.now(), timer = d3_timer_queueHead;
while (timer) {
if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
timer = timer.n;
}
return now;
}
function d3_timer_sweep() {
var t0, t1 = d3_timer_queueHead, time = Infinity;
while (t1) {
if (t1.c) {
if (t1.t < time) time = t1.t;
t1 = (t0 = t1).n;
} else {
t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
}
}
d3_timer_queueTail = t0;
return time;
}
function d3_format_precision(x, p) {
return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
}
d3.round = function(x, n) {
return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
};
var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
d3.formatPrefix = function(value, precision) {
var i = 0;
if (value = +value) {
if (value < 0) value *= -1;
if (precision) value = d3.round(value, d3_format_precision(value, precision));
i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3));
}
return d3_formatPrefixes[8 + i / 3];
};
function d3_formatPrefix(d, i) {
var k = Math.pow(10, abs(8 - i) * 3);
return {
scale: i > 8 ? function(d) {
return d / k;
} : function(d) {
return d * k;
},
symbol: d
};
}
function d3_locale_numberFormat(locale) {
var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) {
var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0;
while (i > 0 && g > 0) {
if (length + g + 1 > width) g = Math.max(1, width - length);
t.push(value.substring(i -= g, i + g));
if ((length += g + 1) > width) break;
g = locale_grouping[j = (j + 1) % locale_grouping.length];
}
return t.reverse().join(locale_thousands);
} : d3_identity;
return function(specifier) {
var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true;
if (precision) precision = +precision.substring(1);
if (zfill || fill === "0" && align === "=") {
zfill = fill = "0";
align = "=";
}
switch (type) {
case "n":
comma = true;
type = "g";
break;
case "%":
scale = 100;
suffix = "%";
type = "f";
break;
case "p":
scale = 100;
suffix = "%";
type = "r";
break;
case "b":
case "o":
case "x":
case "X":
if (symbol === "#") prefix = "0" + type.toLowerCase();
case "c":
exponent = false;
case "d":
integer = true;
precision = 0;
break;
case "s":
scale = -1;
type = "r";
break;
}
if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1];
if (type == "r" && !precision) type = "g";
if (precision != null) {
if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision));
}
type = d3_format_types.get(type) || d3_format_typeDefault;
var zcomma = zfill && comma;
return function(value) {
var fullSuffix = suffix;
if (integer && value % 1) return "";
var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign;
if (scale < 0) {
var unit = d3.formatPrefix(value, precision);
value = unit.scale(value);
fullSuffix = unit.symbol + suffix;
} else {
value *= scale;
}
value = type(value, precision);
var i = value.lastIndexOf("."), before, after;
if (i < 0) {
var j = exponent ? value.lastIndexOf("e") : -1;
if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j);
} else {
before = value.substring(0, i);
after = locale_decimal + value.substring(i + 1);
}
if (!zfill && comma) before = formatGroup(before, Infinity);
var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : "";
if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity);
negative += prefix;
value = before + after;
return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix;
};
};
}
var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
var d3_format_types = d3.map({
b: function(x) {
return x.toString(2);
},
c: function(x) {
return String.fromCharCode(x);
},
o: function(x) {
return x.toString(8);
},
x: function(x) {
return x.toString(16);
},
X: function(x) {
return x.toString(16).toUpperCase();
},
g: function(x, p) {
return x.toPrecision(p);
},
e: function(x, p) {
return x.toExponential(p);
},
f: function(x, p) {
return x.toFixed(p);
},
r: function(x, p) {
return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p))));
}
});
function d3_format_typeDefault(x) {
return x + "";
}
var d3_time = d3.time = {}, d3_date = Date;
function d3_date_utc() {
this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
}
d3_date_utc.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() {
d3_time_prototype.setUTCDate.apply(this._, arguments);
},
setDay: function() {
d3_time_prototype.setUTCDay.apply(this._, arguments);
},
setFullYear: function() {
d3_time_prototype.setUTCFullYear.apply(this._, arguments);
},
setHours: function() {
d3_time_prototype.setUTCHours.apply(this._, arguments);
},
setMilliseconds: function() {
d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
},
setMinutes: function() {
d3_time_prototype.setUTCMinutes.apply(this._, arguments);
},
setMonth: function() {
d3_time_prototype.setUTCMonth.apply(this._, arguments);
},
setSeconds: function() {
d3_time_prototype.setUTCSeconds.apply(this._, arguments);
},
setTime: function() {
d3_time_prototype.setTime.apply(this._, arguments);
}
};
var d3_time_prototype = Date.prototype;
function d3_time_interval(local, step, number) {
function round(date) {
var d0 = local(date), d1 = offset(d0, 1);
return date - d0 < d1 - date ? d0 : d1;
}
function ceil(date) {
step(date = local(new d3_date(date - 1)), 1);
return date;
}
function offset(date, k) {
step(date = new d3_date(+date), k);
return date;
}
function range(t0, t1, dt) {
var time = ceil(t0), times = [];
if (dt > 1) {
while (time < t1) {
if (!(number(time) % dt)) times.push(new Date(+time));
step(time, 1);
}
} else {
while (time < t1) times.push(new Date(+time)), step(time, 1);
}
return times;
}
function range_utc(t0, t1, dt) {
try {
d3_date = d3_date_utc;
var utc = new d3_date_utc();
utc._ = t0;
return range(utc, t1, dt);
} finally {
d3_date = Date;
}
}
local.floor = local;
local.round = round;
local.ceil = ceil;
local.offset = offset;
local.range = range;
var utc = local.utc = d3_time_interval_utc(local);
utc.floor = utc;
utc.round = d3_time_interval_utc(round);
utc.ceil = d3_time_interval_utc(ceil);
utc.offset = d3_time_interval_utc(offset);
utc.range = range_utc;
return local;
}
function d3_time_interval_utc(method) {
return function(date, k) {
try {
d3_date = d3_date_utc;
var utc = new d3_date_utc();
utc._ = date;
return method(utc, k)._;
} finally {
d3_date = Date;
}
};
}
d3_time.year = d3_time_interval(function(date) {
date = d3_time.day(date);
date.setMonth(0, 1);
return date;
}, function(date, offset) {
date.setFullYear(date.getFullYear() + offset);
}, function(date) {
return date.getFullYear();
});
d3_time.years = d3_time.year.range;
d3_time.years.utc = d3_time.year.utc.range;
d3_time.day = d3_time_interval(function(date) {
var day = new d3_date(2e3, 0);
day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
return day;
}, function(date, offset) {
date.setDate(date.getDate() + offset);
}, function(date) {
return date.getDate() - 1;
});
d3_time.days = d3_time.day.range;
d3_time.days.utc = d3_time.day.utc.range;
d3_time.dayOfYear = function(date) {
var year = d3_time.year(date);
return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
};
[ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) {
i = 7 - i;
var interval = d3_time[day] = d3_time_interval(function(date) {
(date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
return date;
}, function(date, offset) {
date.setDate(date.getDate() + Math.floor(offset) * 7);
}, function(date) {
var day = d3_time.year(date).getDay();
return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
});
d3_time[day + "s"] = interval.range;
d3_time[day + "s"].utc = interval.utc.range;
d3_time[day + "OfYear"] = function(date) {
var day = d3_time.year(date).getDay();
return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7);
};
});
d3_time.week = d3_time.sunday;
d3_time.weeks = d3_time.sunday.range;
d3_time.weeks.utc = d3_time.sunday.utc.range;
d3_time.weekOfYear = d3_time.sundayOfYear;
function d3_locale_timeFormat(locale) {
var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths;
function d3_time_format(template) {
var n = template.length;
function format(date) {
var string = [], i = -1, j = 0, c, p, f;
while (++i < n) {
if (template.charCodeAt(i) === 37) {
string.push(template.slice(j, i));
if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i);
if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p);
string.push(c);
j = i + 1;
}
}
string.push(template.slice(j, i));
return string.join("");
}
format.parse = function(string) {
var d = {
y: 1900,
m: 0,
d: 1,
H: 0,
M: 0,
S: 0,
L: 0,
Z: null
}, i = d3_time_parse(d, template, string, 0);
if (i != string.length) return null;
if ("p" in d) d.H = d.H % 12 + d.p * 12;
var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)();
if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) {
if (!("w" in d)) d.w = "W" in d ? 1 : 0;
date.setFullYear(d.y, 0, 1);
date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7);
} else date.setFullYear(d.y, d.m, d.d);
date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L);
return localZ ? date._ : date;
};
format.toString = function() {
return template;
};
return format;
}
function d3_time_parse(date, template, string, j) {
var c, p, t, i = 0, n = template.length, m = string.length;
while (i < n) {
if (j >= m) return -1;
c = template.charCodeAt(i++);
if (c === 37) {
t = template.charAt(i++);
p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t];
if (!p || (j = p(date, string, j)) < 0) return -1;
} else if (c != string.charCodeAt(j++)) {
return -1;
}
}
return j;
}
d3_time_format.utc = function(template) {
var local = d3_time_format(template);
function format(date) {
try {
d3_date = d3_date_utc;
var utc = new d3_date();
utc._ = date;
return local(utc);
} finally {
d3_date = Date;
}
}
format.parse = function(string) {
try {
d3_date = d3_date_utc;
var date = local.parse(string);
return date && date._;
} finally {
d3_date = Date;
}
};
format.toString = local.toString;
return format;
};
d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti;
var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths);
locale_periods.forEach(function(p, i) {
d3_time_periodLookup.set(p.toLowerCase(), i);
});
var d3_time_formats = {
a: function(d) {
return locale_shortDays[d.getDay()];
},
A: function(d) {
return locale_days[d.getDay()];
},
b: function(d) {
return locale_shortMonths[d.getMonth()];
},
B: function(d) {
return locale_months[d.getMonth()];
},
c: d3_time_format(locale_dateTime),
d: function(d, p) {
return d3_time_formatPad(d.getDate(), p, 2);
},
e: function(d, p) {
return d3_time_formatPad(d.getDate(), p, 2);
},
H: function(d, p) {
return d3_time_formatPad(d.getHours(), p, 2);
},
I: function(d, p) {
return d3_time_formatPad(d.getHours() % 12 || 12, p, 2);
},
j: function(d, p) {
return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3);
},
L: function(d, p) {
return d3_time_formatPad(d.getMilliseconds(), p, 3);
},
m: function(d, p) {
return d3_time_formatPad(d.getMonth() + 1, p, 2);
},
M: function(d, p) {
return d3_time_formatPad(d.getMinutes(), p, 2);
},
p: function(d) {
return locale_periods[+(d.getHours() >= 12)];
},
S: function(d, p) {
return d3_time_formatPad(d.getSeconds(), p, 2);
},
U: function(d, p) {
return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2);
},
w: function(d) {
return d.getDay();
},
W: function(d, p) {
return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2);
},
x: d3_time_format(locale_date),
X: d3_time_format(locale_time),
y: function(d, p) {
return d3_time_formatPad(d.getFullYear() % 100, p, 2);
},
Y: function(d, p) {
return d3_time_formatPad(d.getFullYear() % 1e4, p, 4);
},
Z: d3_time_zone,
"%": function() {
return "%";
}
};
var d3_time_parsers = {
a: d3_time_parseWeekdayAbbrev,
A: d3_time_parseWeekday,
b: d3_time_parseMonthAbbrev,
B: d3_time_parseMonth,
c: d3_time_parseLocaleFull,
d: d3_time_parseDay,
e: d3_time_parseDay,
H: d3_time_parseHour24,
I: d3_time_parseHour24,
j: d3_time_parseDayOfYear,
L: d3_time_parseMilliseconds,
m: d3_time_parseMonthNumber,
M: d3_time_parseMinutes,
p: d3_time_parseAmPm,
S: d3_time_parseSeconds,
U: d3_time_parseWeekNumberSunday,
w: d3_time_parseWeekdayNumber,
W: d3_time_parseWeekNumberMonday,
x: d3_time_parseLocaleDate,
X: d3_time_parseLocaleTime,
y: d3_time_parseYear,
Y: d3_time_parseFullYear,
Z: d3_time_parseZone,
"%": d3_time_parseLiteralPercent
};
function d3_time_parseWeekdayAbbrev(date, string, i) {
d3_time_dayAbbrevRe.lastIndex = 0;
var n = d3_time_dayAbbrevRe.exec(string.slice(i));
return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
}
function d3_time_parseWeekday(date, string, i) {
d3_time_dayRe.lastIndex = 0;
var n = d3_time_dayRe.exec(string.slice(i));
return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
}
function d3_time_parseMonthAbbrev(date, string, i) {
d3_time_monthAbbrevRe.lastIndex = 0;
var n = d3_time_monthAbbrevRe.exec(string.slice(i));
return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
}
function d3_time_parseMonth(date, string, i) {
d3_time_monthRe.lastIndex = 0;
var n = d3_time_monthRe.exec(string.slice(i));
return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
}
function d3_time_parseLocaleFull(date, string, i) {
return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
}
function d3_time_parseLocaleDate(date, string, i) {
return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
}
function d3_time_parseLocaleTime(date, string, i) {
return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
}
function d3_time_parseAmPm(date, string, i) {
var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase());
return n == null ? -1 : (date.p = n, i);
}
return d3_time_format;
}
var d3_time_formatPads = {
"-": "",
_: " ",
"0": "0"
}, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/;
function d3_time_formatPad(value, fill, width) {
var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
}
function d3_time_formatRe(names) {
return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
}
function d3_time_formatLookup(names) {
var map = new d3_Map(), i = -1, n = names.length;
while (++i < n) map.set(names[i].toLowerCase(), i);
return map;
}
function d3_time_parseWeekdayNumber(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 1));
return n ? (date.w = +n[0], i + n[0].length) : -1;
}
function d3_time_parseWeekNumberSunday(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i));
return n ? (date.U = +n[0], i + n[0].length) : -1;
}
function d3_time_parseWeekNumberMonday(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i));
return n ? (date.W = +n[0], i + n[0].length) : -1;
}
function d3_time_parseFullYear(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 4));
return n ? (date.y = +n[0], i + n[0].length) : -1;
}
function d3_time_parseYear(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 2));
return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1;
}
function d3_time_parseZone(date, string, i) {
return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string,
i + 5) : -1;
}
function d3_time_expandYear(d) {
return d + (d > 68 ? 1900 : 2e3);
}
function d3_time_parseMonthNumber(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 2));
return n ? (date.m = n[0] - 1, i + n[0].length) : -1;
}
function d3_time_parseDay(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 2));
return n ? (date.d = +n[0], i + n[0].length) : -1;
}
function d3_time_parseDayOfYear(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 3));
return n ? (date.j = +n[0], i + n[0].length) : -1;
}
function d3_time_parseHour24(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 2));
return n ? (date.H = +n[0], i + n[0].length) : -1;
}
function d3_time_parseMinutes(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 2));
return n ? (date.M = +n[0], i + n[0].length) : -1;
}
function d3_time_parseSeconds(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 2));
return n ? (date.S = +n[0], i + n[0].length) : -1;
}
function d3_time_parseMilliseconds(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.slice(i, i + 3));
return n ? (date.L = +n[0], i + n[0].length) : -1;
}
function d3_time_zone(d) {
var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60;
return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2);
}
function d3_time_parseLiteralPercent(date, string, i) {
d3_time_percentRe.lastIndex = 0;
var n = d3_time_percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function d3_time_formatMulti(formats) {
var n = formats.length, i = -1;
while (++i < n) formats[i][0] = this(formats[i][0]);
return function(date) {
var i = 0, f = formats[i];
while (!f[1](date)) f = formats[++i];
return f[0](date);
};
}
d3.locale = function(locale) {
return {
numberFormat: d3_locale_numberFormat(locale),
timeFormat: d3_locale_timeFormat(locale)
};
};
var d3_locale_enUS = d3.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" ]
});
d3.format = d3_locale_enUS.numberFormat;
d3.geo = {};
function d3_adder() {}
d3_adder.prototype = {
s: 0,
t: 0,
add: function(y) {
d3_adderSum(y, this.t, d3_adderTemp);
d3_adderSum(d3_adderTemp.s, this.s, this);
if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t;
},
reset: function() {
this.s = this.t = 0;
},
valueOf: function() {
return this.s;
}
};
var d3_adderTemp = new d3_adder();
function d3_adderSum(a, b, o) {
var x = o.s = a + b, bv = x - a, av = x - bv;
o.t = a - av + (b - bv);
}
d3.geo.stream = function(object, listener) {
if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) {
d3_geo_streamObjectType[object.type](object, listener);
} else {
d3_geo_streamGeometry(object, listener);
}
};
function d3_geo_streamGeometry(geometry, listener) {
if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) {
d3_geo_streamGeometryType[geometry.type](geometry, listener);
}
}
var d3_geo_streamObjectType = {
Feature: function(feature, listener) {
d3_geo_streamGeometry(feature.geometry, listener);
},
FeatureCollection: function(object, listener) {
var features = object.features, i = -1, n = features.length;
while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener);
}
};
var d3_geo_streamGeometryType = {
Sphere: function(object, listener) {
listener.sphere();
},
Point: function(object, listener) {
object = object.coordinates;
listener.point(object[0], object[1], object[2]);
},
MultiPoint: function(object, listener) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]);
},
LineString: function(object, listener) {
d3_geo_streamLine(object.coordinates, listener, 0);
},
MultiLineString: function(object, listener) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0);
},
Polygon: function(object, listener) {
d3_geo_streamPolygon(object.coordinates, listener);
},
MultiPolygon: function(object, listener) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) d3_geo_streamPolygon(coordinates[i], listener);
},
GeometryCollection: function(object, listener) {
var geometries = object.geometries, i = -1, n = geometries.length;
while (++i < n) d3_geo_streamGeometry(geometries[i], listener);
}
};
function d3_geo_streamLine(coordinates, listener, closed) {
var i = -1, n = coordinates.length - closed, coordinate;
listener.lineStart();
while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]);
listener.lineEnd();
}
function d3_geo_streamPolygon(coordinates, listener) {
var i = -1, n = coordinates.length;
listener.polygonStart();
while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1);
listener.polygonEnd();
}
d3.geo.area = function(object) {
d3_geo_areaSum = 0;
d3.geo.stream(object, d3_geo_area);
return d3_geo_areaSum;
};
var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder();
var d3_geo_area = {
sphere: function() {
d3_geo_areaSum += 4 * π;
},
point: d3_noop,
lineStart: d3_noop,
lineEnd: d3_noop,
polygonStart: function() {
d3_geo_areaRingSum.reset();
d3_geo_area.lineStart = d3_geo_areaRingStart;
},
polygonEnd: function() {
var area = 2 * d3_geo_areaRingSum;
d3_geo_areaSum += area < 0 ? 4 * π + area : area;
d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop;
}
};
function d3_geo_areaRingStart() {
var λ00, φ00, λ0, cosφ0, sinφ0;
d3_geo_area.point = function(λ, φ) {
d3_geo_area.point = nextPoint;
λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4),
sinφ0 = Math.sin(φ);
};
function nextPoint(λ, φ) {
λ *= d3_radians;
φ = φ * d3_radians / 2 + π / 4;
var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ);
d3_geo_areaRingSum.add(Math.atan2(v, u));
λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
}
d3_geo_area.lineEnd = function() {
nextPoint(λ00, φ00);
};
}
function d3_geo_cartesian(spherical) {
var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ);
return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ];
}
function d3_geo_cartesianDot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
function d3_geo_cartesianCross(a, b) {
return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];
}
function d3_geo_cartesianAdd(a, b) {
a[0] += b[0];
a[1] += b[1];
a[2] += b[2];
}
function d3_geo_cartesianScale(vector, k) {
return [ vector[0] * k, vector[1] * k, vector[2] * k ];
}
function d3_geo_cartesianNormalize(d) {
var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
d[0] /= l;
d[1] /= l;
d[2] /= l;
}
function d3_geo_spherical(cartesian) {
return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ];
}
function d3_geo_sphericalEqual(a, b) {
return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε;
}
d3.geo.bounds = function() {
var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range;
var bound = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
bound.point = ringPoint;
bound.lineStart = ringStart;
bound.lineEnd = ringEnd;
dλSum = 0;
d3_geo_area.polygonStart();
},
polygonEnd: function() {
d3_geo_area.polygonEnd();
bound.point = point;
bound.lineStart = lineStart;
bound.lineEnd = lineEnd;
if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90;
range[0] = λ0, range[1] = λ1;
}
};
function point(λ, φ) {
ranges.push(range = [ λ0 = λ, λ1 = λ ]);
if (φ < φ0) φ0 = φ;
if (φ > φ1) φ1 = φ;
}
function linePoint(λ, φ) {
var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]);
if (p0) {
var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal);
d3_geo_cartesianNormalize(inflection);
inflection = d3_geo_spherical(inflection);
var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180;
if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
var φi = inflection[1] * d3_degrees;
if (φi > φ1) φ1 = φi;
} else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
var φi = -inflection[1] * d3_degrees;
if (φi < φ0) φ0 = φi;
} else {
if (φ < φ0) φ0 = φ;
if (φ > φ1) φ1 = φ;
}
if (antimeridian) {
if (λ < λ_) {
if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
} else {
if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
}
} else {
if (λ1 >= λ0) {
if (λ < λ0) λ0 = λ;
if (λ > λ1) λ1 = λ;
} else {
if (λ > λ_) {
if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
} else {
if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
}
}
}
} else {
point(λ, φ);
}
p0 = p, λ_ = λ;
}
function lineStart() {
bound.point = linePoint;
}
function lineEnd() {
range[0] = λ0, range[1] = λ1;
bound.point = point;
p0 = null;
}
function ringPoint(λ, φ) {
if (p0) {
var dλ = λ - λ_;
dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ;
} else λ__ = λ, φ__ = φ;
d3_geo_area.point(λ, φ);
linePoint(λ, φ);
}
function ringStart() {
d3_geo_area.lineStart();
}
function ringEnd() {
ringPoint(λ__, φ__);
d3_geo_area.lineEnd();
if (abs(dλSum) > ε) λ0 = -(λ1 = 180);
range[0] = λ0, range[1] = λ1;
p0 = null;
}
function angle(λ0, λ1) {
return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1;
}
function compareRanges(a, b) {
return a[0] - b[0];
}
function withinRange(x, range) {
return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
}
return function(feature) {
φ1 = λ1 = -(λ0 = φ0 = Infinity);
ranges = [];
d3.geo.stream(feature, bound);
var n = ranges.length;
if (n) {
ranges.sort(compareRanges);
for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) {
b = ranges[i];
if (withinRange(b[0], a) || withinRange(b[1], a)) {
if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
} else {
merged.push(a = b);
}
}
var best = -Infinity, dλ;
for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) {
b = merged[i];
if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1];
}
}
ranges = range = null;
return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ];
};
}();
d3.geo.centroid = function(object) {
d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
d3.geo.stream(object, d3_geo_centroid);
var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z;
if (m < ε2) {
x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1;
if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0;
m = x * x + y * y + z * z;
if (m < ε2) return [ NaN, NaN ];
}
return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ];
};
var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2;
var d3_geo_centroid = {
sphere: d3_noop,
point: d3_geo_centroidPoint,
lineStart: d3_geo_centroidLineStart,
lineEnd: d3_geo_centroidLineEnd,
polygonStart: function() {
d3_geo_centroid.lineStart = d3_geo_centroidRingStart;
},
polygonEnd: function() {
d3_geo_centroid.lineStart = d3_geo_centroidLineStart;
}
};
function d3_geo_centroidPoint(λ, φ) {
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians);
d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ));
}
function d3_geo_centroidPointXYZ(x, y, z) {
++d3_geo_centroidW0;
d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0;
d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0;
d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0;
}
function d3_geo_centroidLineStart() {
var x0, y0, z0;
d3_geo_centroid.point = function(λ, φ) {
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians);
x0 = cosφ * Math.cos(λ);
y0 = cosφ * Math.sin(λ);
z0 = Math.sin(φ);
d3_geo_centroid.point = nextPoint;
d3_geo_centroidPointXYZ(x0, y0, z0);
};
function nextPoint(λ, φ) {
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
d3_geo_centroidW1 += w;
d3_geo_centroidX1 += w * (x0 + (x0 = x));
d3_geo_centroidY1 += w * (y0 + (y0 = y));
d3_geo_centroidZ1 += w * (z0 + (z0 = z));
d3_geo_centroidPointXYZ(x0, y0, z0);
}
}
function d3_geo_centroidLineEnd() {
d3_geo_centroid.point = d3_geo_centroidPoint;
}
function d3_geo_centroidRingStart() {
var λ00, φ00, x0, y0, z0;
d3_geo_centroid.point = function(λ, φ) {
λ00 = λ, φ00 = φ;
d3_geo_centroid.point = nextPoint;
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians);
x0 = cosφ * Math.cos(λ);
y0 = cosφ * Math.sin(λ);
z0 = Math.sin(φ);
d3_geo_centroidPointXYZ(x0, y0, z0);
};
d3_geo_centroid.lineEnd = function() {
nextPoint(λ00, φ00);
d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd;
d3_geo_centroid.point = d3_geo_centroidPoint;
};
function nextPoint(λ, φ) {
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u);
d3_geo_centroidX2 += v * cx;
d3_geo_centroidY2 += v * cy;
d3_geo_centroidZ2 += v * cz;
d3_geo_centroidW1 += w;
d3_geo_centroidX1 += w * (x0 + (x0 = x));
d3_geo_centroidY1 += w * (y0 + (y0 = y));
d3_geo_centroidZ1 += w * (z0 + (z0 = z));
d3_geo_centroidPointXYZ(x0, y0, z0);
}
}
function d3_geo_compose(a, b) {
function compose(x, y) {
return x = a(x, y), b(x[0], x[1]);
}
if (a.invert && b.invert) compose.invert = function(x, y) {
return x = b.invert(x, y), x && a.invert(x[0], x[1]);
};
return compose;
}
function d3_true() {
return true;
}
function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) {
var subject = [], clip = [];
segments.forEach(function(segment) {
if ((n = segment.length - 1) <= 0) return;
var n, p0 = segment[0], p1 = segment[n];
if (d3_geo_sphericalEqual(p0, p1)) {
listener.lineStart();
for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]);
listener.lineEnd();
return;
}
var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false);
a.o = b;
subject.push(a);
clip.push(b);
a = new d3_geo_clipPolygonIntersection(p1, segment, null, false);
b = new d3_geo_clipPolygonIntersection(p1, null, a, true);
a.o = b;
subject.push(a);
clip.push(b);
});
clip.sort(compare);
d3_geo_clipPolygonLinkCircular(subject);
d3_geo_clipPolygonLinkCircular(clip);
if (!subject.length) return;
for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) {
clip[i].e = entry = !entry;
}
var start = subject[0], points, point;
while (1) {
var current = start, isSubject = true;
while (current.v) if ((current = current.n) === start) return;
points = current.z;
listener.lineStart();
do {
current.v = current.o.v = true;
if (current.e) {
if (isSubject) {
for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]);
} else {
interpolate(current.x, current.n.x, 1, listener);
}
current = current.n;
} else {
if (isSubject) {
points = current.p.z;
for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]);
} else {
interpolate(current.x, current.p.x, -1, listener);
}
current = current.p;
}
current = current.o;
points = current.z;
isSubject = !isSubject;
} while (!current.v);
listener.lineEnd();
}
}
function d3_geo_clipPolygonLinkCircular(array) {
if (!(n = array.length)) return;
var n, i = 0, a = array[0], b;
while (++i < n) {
a.n = b = array[i];
b.p = a;
a = b;
}
a.n = b = array[0];
b.p = a;
}
function d3_geo_clipPolygonIntersection(point, points, other, entry) {
this.x = point;
this.z = points;
this.o = other;
this.e = entry;
this.v = false;
this.n = this.p = null;
}
function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) {
return function(rotate, listener) {
var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]);
var clip = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
clip.point = pointRing;
clip.lineStart = ringStart;
clip.lineEnd = ringEnd;
segments = [];
polygon = [];
},
polygonEnd: function() {
clip.point = point;
clip.lineStart = lineStart;
clip.lineEnd = lineEnd;
segments = d3.merge(segments);
var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon);
if (segments.length) {
if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener);
} else if (clipStartInside) {
if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
listener.lineStart();
interpolate(null, null, 1, listener);
listener.lineEnd();
}
if (polygonStarted) listener.polygonEnd(), polygonStarted = false;
segments = polygon = null;
},
sphere: function() {
listener.polygonStart();
listener.lineStart();
interpolate(null, null, 1, listener);
listener.lineEnd();
listener.polygonEnd();
}
};
function point(λ, φ) {
var point = rotate(λ, φ);
if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ);
}
function pointLine(λ, φ) {
var point = rotate(λ, φ);
line.point(point[0], point[1]);
}
function lineStart() {
clip.point = pointLine;
line.lineStart();
}
function lineEnd() {
clip.point = point;
line.lineEnd();
}
var segments;
var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring;
function pointRing(λ, φ) {
ring.push([ λ, φ ]);
var point = rotate(λ, φ);
ringListener.point(point[0], point[1]);
}
function ringStart() {
ringListener.lineStart();
ring = [];
}
function ringEnd() {
pointRing(ring[0][0], ring[0][1]);
ringListener.lineEnd();
var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length;
ring.pop();
polygon.push(ring);
ring = null;
if (!n) return;
if (clean & 1) {
segment = ringSegments[0];
var n = segment.length - 1, i = -1, point;
if (n > 0) {
if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
listener.lineStart();
while (++i < n) listener.point((point = segment[i])[0], point[1]);
listener.lineEnd();
}
return;
}
if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));
}
return clip;
};
}
function d3_geo_clipSegmentLength1(segment) {
return segment.length > 1;
}
function d3_geo_clipBufferListener() {
var lines = [], line;
return {
lineStart: function() {
lines.push(line = []);
},
point: function(λ, φ) {
line.push([ λ, φ ]);
},
lineEnd: d3_noop,
buffer: function() {
var buffer = lines;
lines = [];
line = null;
return buffer;
},
rejoin: function() {
if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
}
};
}
function d3_geo_clipSort(a, b) {
return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]);
}
var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]);
function d3_geo_clipAntimeridianLine(listener) {
var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean;
return {
lineStart: function() {
listener.lineStart();
clean = 1;
},
point: function(λ1, φ1) {
var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0);
if (abs(dλ - π) < ε) {
listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ);
listener.point(sλ0, φ0);
listener.lineEnd();
listener.lineStart();
listener.point(sλ1, φ0);
listener.point(λ1, φ0);
clean = 0;
} else if (sλ0 !== sλ1 && dλ >= π) {
if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε;
if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε;
φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1);
listener.point(sλ0, φ0);
listener.lineEnd();
listener.lineStart();
listener.point(sλ1, φ0);
clean = 0;
}
listener.point(λ0 = λ1, φ0 = φ1);
sλ0 = sλ1;
},
lineEnd: function() {
listener.lineEnd();
λ0 = φ0 = NaN;
},
clean: function() {
return 2 - clean;
}
};
}
function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) {
var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1);
return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2;
}
function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) {
var φ;
if (from == null) {
φ = direction * halfπ;
listener.point(-π, φ);
listener.point(0, φ);
listener.point(π, φ);
listener.point(π, 0);
listener.point(π, -φ);
listener.point(0, -φ);
listener.point(-π, -φ);
listener.point(-π, 0);
listener.point(-π, φ);
} else if (abs(from[0] - to[0]) > ε) {
var s = from[0] < to[0] ? π : -π;
φ = direction * s / 2;
listener.point(-s, φ);
listener.point(0, φ);
listener.point(s, φ);
} else {
listener.point(to[0], to[1]);
}
}
function d3_geo_pointInPolygon(point, polygon) {
var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0;
d3_geo_areaRingSum.reset();
for (var i = 0, n = polygon.length; i < n; ++i) {
var ring = polygon[i], m = ring.length;
if (!m) continue;
var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1;
while (true) {
if (j === m) j = 0;
point = ring[j];
var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ;
d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ)));
polarAngle += antimeridian ? dλ + sdλ * τ : dλ;
if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) {
var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point));
d3_geo_cartesianNormalize(arc);
var intersection = d3_geo_cartesianCross(meridianNormal, arc);
d3_geo_cartesianNormalize(intersection);
var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]);
if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) {
winding += antimeridian ^ dλ >= 0 ? 1 : -1;
}
}
if (!j++) break;
λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point;
}
}
return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1;
}
function d3_geo_clipCircle(radius) {
var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians);
return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]);
function visible(λ, φ) {
return Math.cos(λ) * Math.cos(φ) > cr;
}
function clipLine(listener) {
var point0, c0, v0, v00, clean;
return {
lineStart: function() {
v00 = v0 = false;
clean = 1;
},
point: function(λ, φ) {
var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0;
if (!point0 && (v00 = v0 = v)) listener.lineStart();
if (v !== v0) {
point2 = intersect(point0, point1);
if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) {
point1[0] += ε;
point1[1] += ε;
v = visible(point1[0], point1[1]);
}
}
if (v !== v0) {
clean = 0;
if (v) {
listener.lineStart();
point2 = intersect(point1, point0);
listener.point(point2[0], point2[1]);
} else {
point2 = intersect(point0, point1);
listener.point(point2[0], point2[1]);
listener.lineEnd();
}
point0 = point2;
} else if (notHemisphere && point0 && smallRadius ^ v) {
var t;
if (!(c & c0) && (t = intersect(point1, point0, true))) {
clean = 0;
if (smallRadius) {
listener.lineStart();
listener.point(t[0][0], t[0][1]);
listener.point(t[1][0], t[1][1]);
listener.lineEnd();
} else {
listener.point(t[1][0], t[1][1]);
listener.lineEnd();
listener.lineStart();
listener.point(t[0][0], t[0][1]);
}
}
}
if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) {
listener.point(point1[0], point1[1]);
}
point0 = point1, v0 = v, c0 = c;
},
lineEnd: function() {
if (v0) listener.lineEnd();
point0 = null;
},
clean: function() {
return clean | (v00 && v0) << 1;
}
};
}
function intersect(a, b, two) {
var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b);
var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
if (!determinant) return !two && a;
var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2);
d3_geo_cartesianAdd(A, B);
var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1);
if (t2 < 0) return;
var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu);
d3_geo_cartesianAdd(q, A);
q = d3_geo_spherical(q);
if (!two) return q;
var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z;
if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z;
var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε;
if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z;
if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) {
var q1 = d3_geo_cartesianScale(u, (-w + t) / uu);
d3_geo_cartesianAdd(q1, A);
return [ q, d3_geo_spherical(q1) ];
}
}
function code(λ, φ) {
var r = smallRadius ? radius : π - radius, code = 0;
if (λ < -r) code |= 1; else if (λ > r) code |= 2;
if (φ < -r) code |= 4; else if (φ > r) code |= 8;
return code;
}
}
function d3_geom_clipLine(x0, y0, x1, y1) {
return function(line) {
var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
r = x0 - ax;
if (!dx && r > 0) return;
r /= dx;
if (dx < 0) {
if (r < t0) return;
if (r < t1) t1 = r;
} else if (dx > 0) {
if (r > t1) return;
if (r > t0) t0 = r;
}
r = x1 - ax;
if (!dx && r < 0) return;
r /= dx;
if (dx < 0) {
if (r > t1) return;
if (r > t0) t0 = r;
} else if (dx > 0) {
if (r < t0) return;
if (r < t1) t1 = r;
}
r = y0 - ay;
if (!dy && r > 0) return;
r /= dy;
if (dy < 0) {
if (r < t0) return;
if (r < t1) t1 = r;
} else if (dy > 0) {
if (r > t1) return;
if (r > t0) t0 = r;
}
r = y1 - ay;
if (!dy && r < 0) return;
r /= dy;
if (dy < 0) {
if (r > t1) return;
if (r > t0) t0 = r;
} else if (dy > 0) {
if (r < t0) return;
if (r < t1) t1 = r;
}
if (t0 > 0) line.a = {
x: ax + t0 * dx,
y: ay + t0 * dy
};
if (t1 < 1) line.b = {
x: ax + t1 * dx,
y: ay + t1 * dy
};
return line;
};
}
var d3_geo_clipExtentMAX = 1e9;
d3.geo.clipExtent = function() {
var x0, y0, x1, y1, stream, clip, clipExtent = {
stream: function(output) {
if (stream) stream.valid = false;
stream = clip(output);
stream.valid = true;
return stream;
},
extent: function(_) {
if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]);
if (stream) stream.valid = false, stream = null;
return clipExtent;
}
};
return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]);
};
function d3_geo_clipExtent(x0, y0, x1, y1) {
return function(listener) {
var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring;
var clip = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
listener = bufferListener;
segments = [];
polygon = [];
clean = true;
},
polygonEnd: function() {
listener = listener_;
segments = d3.merge(segments);
var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length;
if (inside || visible) {
listener.polygonStart();
if (inside) {
listener.lineStart();
interpolate(null, null, 1, listener);
listener.lineEnd();
}
if (visible) {
d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener);
}
listener.polygonEnd();
}
segments = polygon = ring = null;
}
};
function insidePolygon(p) {
var wn = 0, n = polygon.length, y = p[1];
for (var i = 0; i < n; ++i) {
for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) {
b = v[j];
if (a[1] <= y) {
if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn;
} else {
if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn;
}
a = b;
}
}
return wn !== 0;
}
function interpolate(from, to, direction, listener) {
var a = 0, a1 = 0;
if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) {
do {
listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
} while ((a = (a + direction + 4) % 4) !== a1);
} else {
listener.point(to[0], to[1]);
}
}
function pointVisible(x, y) {
return x0 <= x && x <= x1 && y0 <= y && y <= y1;
}
function point(x, y) {
if (pointVisible(x, y)) listener.point(x, y);
}
var x__, y__, v__, x_, y_, v_, first, clean;
function lineStart() {
clip.point = linePoint;
if (polygon) polygon.push(ring = []);
first = true;
v_ = false;
x_ = y_ = NaN;
}
function lineEnd() {
if (segments) {
linePoint(x__, y__);
if (v__ && v_) bufferListener.rejoin();
segments.push(bufferListener.buffer());
}
clip.point = point;
if (v_) listener.lineEnd();
}
function linePoint(x, y) {
x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x));
y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y));
var v = pointVisible(x, y);
if (polygon) ring.push([ x, y ]);
if (first) {
x__ = x, y__ = y, v__ = v;
first = false;
if (v) {
listener.lineStart();
listener.point(x, y);
}
} else {
if (v && v_) listener.point(x, y); else {
var l = {
a: {
x: x_,
y: y_
},
b: {
x: x,
y: y
}
};
if (clipLine(l)) {
if (!v_) {
listener.lineStart();
listener.point(l.a.x, l.a.y);
}
listener.point(l.b.x, l.b.y);
if (!v) listener.lineEnd();
clean = false;
} else if (v) {
listener.lineStart();
listener.point(x, y);
clean = false;
}
}
}
x_ = x, y_ = y, v_ = v;
}
return clip;
};
function corner(p, direction) {
return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
}
function compare(a, b) {
return comparePoints(a.x, b.x);
}
function comparePoints(a, b) {
var ca = corner(a, 1), cb = corner(b, 1);
return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
}
}
function d3_geo_conic(projectAt) {
var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1);
p.parallels = function(_) {
if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ];
return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180);
};
return p;
}
function d3_geo_conicEqualArea(φ0, φ1) {
var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n;
function forward(λ, φ) {
var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n;
return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ];
}
forward.invert = function(x, y) {
var ρ0_y = ρ0 - y;
return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ];
};
return forward;
}
(d3.geo.conicEqualArea = function() {
return d3_geo_conic(d3_geo_conicEqualArea);
}).raw = d3_geo_conicEqualArea;
d3.geo.albers = function() {
return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070);
};
d3.geo.albersUsa = function() {
var lower48 = d3.geo.albers();
var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]);
var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]);
var point, pointStream = {
point: function(x, y) {
point = [ x, y ];
}
}, lower48Point, alaskaPoint, hawaiiPoint;
function albersUsa(coordinates) {
var x = coordinates[0], y = coordinates[1];
point = null;
(lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
return point;
}
albersUsa.invert = function(coordinates) {
var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates);
};
albersUsa.stream = function(stream) {
var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream);
return {
point: function(x, y) {
lower48Stream.point(x, y);
alaskaStream.point(x, y);
hawaiiStream.point(x, y);
},
sphere: function() {
lower48Stream.sphere();
alaskaStream.sphere();
hawaiiStream.sphere();
},
lineStart: function() {
lower48Stream.lineStart();
alaskaStream.lineStart();
hawaiiStream.lineStart();
},
lineEnd: function() {
lower48Stream.lineEnd();
alaskaStream.lineEnd();
hawaiiStream.lineEnd();
},
polygonStart: function() {
lower48Stream.polygonStart();
alaskaStream.polygonStart();
hawaiiStream.polygonStart();
},
polygonEnd: function() {
lower48Stream.polygonEnd();
alaskaStream.polygonEnd();
hawaiiStream.polygonEnd();
}
};
};
albersUsa.precision = function(_) {
if (!arguments.length) return lower48.precision();
lower48.precision(_);
alaska.precision(_);
hawaii.precision(_);
return albersUsa;
};
albersUsa.scale = function(_) {
if (!arguments.length) return lower48.scale();
lower48.scale(_);
alaska.scale(_ * .35);
hawaii.scale(_);
return albersUsa.translate(lower48.translate());
};
albersUsa.translate = function(_) {
if (!arguments.length) return lower48.translate();
var k = lower48.scale(), x = +_[0], y = +_[1];
lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point;
alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
return albersUsa;
};
return albersUsa.scale(1070);
};
var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = {
point: d3_noop,
lineStart: d3_noop,
lineEnd: d3_noop,
polygonStart: function() {
d3_geo_pathAreaPolygon = 0;
d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart;
},
polygonEnd: function() {
d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop;
d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2);
}
};
function d3_geo_pathAreaRingStart() {
var x00, y00, x0, y0;
d3_geo_pathArea.point = function(x, y) {
d3_geo_pathArea.point = nextPoint;
x00 = x0 = x, y00 = y0 = y;
};
function nextPoint(x, y) {
d3_geo_pathAreaPolygon += y0 * x - x0 * y;
x0 = x, y0 = y;
}
d3_geo_pathArea.lineEnd = function() {
nextPoint(x00, y00);
};
}
var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1;
var d3_geo_pathBounds = {
point: d3_geo_pathBoundsPoint,
lineStart: d3_noop,
lineEnd: d3_noop,
polygonStart: d3_noop,
polygonEnd: d3_noop
};
function d3_geo_pathBoundsPoint(x, y) {
if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x;
if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x;
if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y;
if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y;
}
function d3_geo_pathBuffer() {
var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = [];
var stream = {
point: point,
lineStart: function() {
stream.point = pointLineStart;
},
lineEnd: lineEnd,
polygonStart: function() {
stream.lineEnd = lineEndPolygon;
},
polygonEnd: function() {
stream.lineEnd = lineEnd;
stream.point = point;
},
pointRadius: function(_) {
pointCircle = d3_geo_pathBufferCircle(_);
return stream;
},
result: function() {
if (buffer.length) {
var result = buffer.join("");
buffer = [];
return result;
}
}
};
function point(x, y) {
buffer.push("M", x, ",", y, pointCircle);
}
function pointLineStart(x, y) {
buffer.push("M", x, ",", y);
stream.point = pointLine;
}
function pointLine(x, y) {
buffer.push("L", x, ",", y);
}
function lineEnd() {
stream.point = point;
}
function lineEndPolygon() {
buffer.push("Z");
}
return stream;
}
function d3_geo_pathBufferCircle(radius) {
return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
}
var d3_geo_pathCentroid = {
point: d3_geo_pathCentroidPoint,
lineStart: d3_geo_pathCentroidLineStart,
lineEnd: d3_geo_pathCentroidLineEnd,
polygonStart: function() {
d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart;
},
polygonEnd: function() {
d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart;
d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd;
}
};
function d3_geo_pathCentroidPoint(x, y) {
d3_geo_centroidX0 += x;
d3_geo_centroidY0 += y;
++d3_geo_centroidZ0;
}
function d3_geo_pathCentroidLineStart() {
var x0, y0;
d3_geo_pathCentroid.point = function(x, y) {
d3_geo_pathCentroid.point = nextPoint;
d3_geo_pathCentroidPoint(x0 = x, y0 = y);
};
function nextPoint(x, y) {
var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
d3_geo_centroidX1 += z * (x0 + x) / 2;
d3_geo_centroidY1 += z * (y0 + y) / 2;
d3_geo_centroidZ1 += z;
d3_geo_pathCentroidPoint(x0 = x, y0 = y);
}
}
function d3_geo_pathCentroidLineEnd() {
d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
}
function d3_geo_pathCentroidRingStart() {
var x00, y00, x0, y0;
d3_geo_pathCentroid.point = function(x, y) {
d3_geo_pathCentroid.point = nextPoint;
d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y);
};
function nextPoint(x, y) {
var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
d3_geo_centroidX1 += z * (x0 + x) / 2;
d3_geo_centroidY1 += z * (y0 + y) / 2;
d3_geo_centroidZ1 += z;
z = y0 * x - x0 * y;
d3_geo_centroidX2 += z * (x0 + x);
d3_geo_centroidY2 += z * (y0 + y);
d3_geo_centroidZ2 += z * 3;
d3_geo_pathCentroidPoint(x0 = x, y0 = y);
}
d3_geo_pathCentroid.lineEnd = function() {
nextPoint(x00, y00);
};
}
function d3_geo_pathContext(context) {
var pointRadius = 4.5;
var stream = {
point: point,
lineStart: function() {
stream.point = pointLineStart;
},
lineEnd: lineEnd,
polygonStart: function() {
stream.lineEnd = lineEndPolygon;
},
polygonEnd: function() {
stream.lineEnd = lineEnd;
stream.point = point;
},
pointRadius: function(_) {
pointRadius = _;
return stream;
},
result: d3_noop
};
function point(x, y) {
context.moveTo(x + pointRadius, y);
context.arc(x, y, pointRadius, 0, τ);
}
function pointLineStart(x, y) {
context.moveTo(x, y);
stream.point = pointLine;
}
function pointLine(x, y) {
context.lineTo(x, y);
}
function lineEnd() {
stream.point = point;
}
function lineEndPolygon() {
context.closePath();
}
return stream;
}
function d3_geo_resample(project) {
var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16;
function resample(stream) {
return (maxDepth ? resampleRecursive : resampleNone)(stream);
}
function resampleNone(stream) {
return d3_geo_transformPoint(stream, function(x, y) {
x = project(x, y);
stream.point(x[0], x[1]);
});
}
function resampleRecursive(stream) {
var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0;
var resample = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
stream.polygonStart();
resample.lineStart = ringStart;
},
polygonEnd: function() {
stream.polygonEnd();
resample.lineStart = lineStart;
}
};
function point(x, y) {
x = project(x, y);
stream.point(x[0], x[1]);
}
function lineStart() {
x0 = NaN;
resample.point = linePoint;
stream.lineStart();
}
function linePoint(λ, φ) {
var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ);
resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
stream.point(x0, y0);
}
function lineEnd() {
resample.point = point;
stream.lineEnd();
}
function ringStart() {
lineStart();
resample.point = ringPoint;
resample.lineEnd = ringEnd;
}
function ringPoint(λ, φ) {
linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
resample.point = linePoint;
}
function ringEnd() {
resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream);
resample.lineEnd = lineEnd;
lineEnd();
}
return resample;
}
function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) {
var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
if (d2 > 4 * δ2 && depth--) {
var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream);
stream.point(x2, y2);
resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream);
}
}
}
resample.precision = function(_) {
if (!arguments.length) return Math.sqrt(δ2);
maxDepth = (δ2 = _ * _) > 0 && 16;
return resample;
};
return resample;
}
d3.geo.path = function() {
var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream;
function path(object) {
if (object) {
if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream);
d3.geo.stream(object, cacheStream);
}
return contextStream.result();
}
path.area = function(object) {
d3_geo_pathAreaSum = 0;
d3.geo.stream(object, projectStream(d3_geo_pathArea));
return d3_geo_pathAreaSum;
};
path.centroid = function(object) {
d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
d3.geo.stream(object, projectStream(d3_geo_pathCentroid));
return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ];
};
path.bounds = function(object) {
d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity);
d3.geo.stream(object, projectStream(d3_geo_pathBounds));
return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ];
};
path.projection = function(_) {
if (!arguments.length) return projection;
projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity;
return reset();
};
path.context = function(_) {
if (!arguments.length) return context;
contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_);
if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
return reset();
};
path.pointRadius = function(_) {
if (!arguments.length) return pointRadius;
pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
return path;
};
function reset() {
cacheStream = null;
return path;
}
return path.projection(d3.geo.albersUsa()).context(null);
};
function d3_geo_pathProjectStream(project) {
var resample = d3_geo_resample(function(x, y) {
return project([ x * d3_degrees, y * d3_degrees ]);
});
return function(stream) {
return d3_geo_projectionRadians(resample(stream));
};
}
d3.geo.transform = function(methods) {
return {
stream: function(stream) {
var transform = new d3_geo_transform(stream);
for (var k in methods) transform[k] = methods[k];
return transform;
}
};
};
function d3_geo_transform(stream) {
this.stream = stream;
}
d3_geo_transform.prototype = {
point: function(x, y) {
this.stream.point(x, y);
},
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();
}
};
function d3_geo_transformPoint(stream, point) {
return {
point: point,
sphere: function() {
stream.sphere();
},
lineStart: function() {
stream.lineStart();
},
lineEnd: function() {
stream.lineEnd();
},
polygonStart: function() {
stream.polygonStart();
},
polygonEnd: function() {
stream.polygonEnd();
}
};
}
d3.geo.projection = d3_geo_projection;
d3.geo.projectionMutator = d3_geo_projectionMutator;
function d3_geo_projection(project) {
return d3_geo_projectionMutator(function() {
return project;
})();
}
function d3_geo_projectionMutator(projectAt) {
var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) {
x = project(x, y);
return [ x[0] * k + δx, δy - x[1] * k ];
}), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream;
function projection(point) {
point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
return [ point[0] * k + δx, δy - point[1] * k ];
}
function invert(point) {
point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k);
return point && [ point[0] * d3_degrees, point[1] * d3_degrees ];
}
projection.stream = function(output) {
if (stream) stream.valid = false;
stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output))));
stream.valid = true;
return stream;
};
projection.clipAngle = function(_) {
if (!arguments.length) return clipAngle;
preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians);
return invalidate();
};
projection.clipExtent = function(_) {
if (!arguments.length) return clipExtent;
clipExtent = _;
postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity;
return invalidate();
};
projection.scale = function(_) {
if (!arguments.length) return k;
k = +_;
return reset();
};
projection.translate = function(_) {
if (!arguments.length) return [ x, y ];
x = +_[0];
y = +_[1];
return reset();
};
projection.center = function(_) {
if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ];
λ = _[0] % 360 * d3_radians;
φ = _[1] % 360 * d3_radians;
return reset();
};
projection.rotate = function(_) {
if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ];
δλ = _[0] % 360 * d3_radians;
δφ = _[1] % 360 * d3_radians;
δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0;
return reset();
};
d3.rebind(projection, projectResample, "precision");
function reset() {
projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project);
var center = project(λ, φ);
δx = x - center[0] * k;
δy = y + center[1] * k;
return invalidate();
}
function invalidate() {
if (stream) stream.valid = false, stream = null;
return projection;
}
return function() {
project = projectAt.apply(this, arguments);
projection.invert = project.invert && invert;
return reset();
};
}
function d3_geo_projectionRadians(stream) {
return d3_geo_transformPoint(stream, function(x, y) {
stream.point(x * d3_radians, y * d3_radians);
});
}
function d3_geo_equirectangular(λ, φ) {
return [ λ, φ ];
}
(d3.geo.equirectangular = function() {
return d3_geo_projection(d3_geo_equirectangular);
}).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular;
d3.geo.rotation = function(rotate) {
rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0);
function forward(coordinates) {
coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
}
forward.invert = function(coordinates) {
coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
};
return forward;
};
function d3_geo_identityRotation(λ, φ) {
return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
}
d3_geo_identityRotation.invert = d3_geo_equirectangular;
function d3_geo_rotation(δλ, δφ, δγ) {
return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation;
}
function d3_geo_forwardRotationλ(δλ) {
return function(λ, φ) {
return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
};
}
function d3_geo_rotationλ(δλ) {
var rotation = d3_geo_forwardRotationλ(δλ);
rotation.invert = d3_geo_forwardRotationλ(-δλ);
return rotation;
}
function d3_geo_rotationφγ(δφ, δγ) {
var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ);
function rotation(λ, φ) {
var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ;
return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ];
}
rotation.invert = function(λ, φ) {
var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ;
return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ];
};
return rotation;
}
d3.geo.circle = function() {
var origin = [ 0, 0 ], angle, precision = 6, interpolate;
function circle() {
var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = [];
interpolate(null, null, 1, {
point: function(x, y) {
ring.push(x = rotate(x, y));
x[0] *= d3_degrees, x[1] *= d3_degrees;
}
});
return {
type: "Polygon",
coordinates: [ ring ]
};
}
circle.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
return circle;
};
circle.angle = function(x) {
if (!arguments.length) return angle;
interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians);
return circle;
};
circle.precision = function(_) {
if (!arguments.length) return precision;
interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians);
return circle;
};
return circle.angle(90);
};
function d3_geo_circleInterpolate(radius, precision) {
var cr = Math.cos(radius), sr = Math.sin(radius);
return function(from, to, direction, listener) {
var step = direction * precision;
if (from != null) {
from = d3_geo_circleAngle(cr, from);
to = d3_geo_circleAngle(cr, to);
if (direction > 0 ? from < to : from > to) from += direction * τ;
} else {
from = radius + direction * τ;
to = radius - .5 * step;
}
for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) {
listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]);
}
};
}
function d3_geo_circleAngle(cr, point) {
var a = d3_geo_cartesian(point);
a[0] -= cr;
d3_geo_cartesianNormalize(a);
var angle = d3_acos(-a[1]);
return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI);
}
d3.geo.distance = function(a, b) {
var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t;
return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ);
};
d3.geo.graticule = function() {
var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
function graticule() {
return {
type: "MultiLineString",
coordinates: lines()
};
}
function lines() {
return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
return abs(x % DX) > ε;
}).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
return abs(y % DY) > ε;
}).map(y));
}
graticule.lines = function() {
return lines().map(function(coordinates) {
return {
type: "LineString",
coordinates: coordinates
};
});
};
graticule.outline = function() {
return {
type: "Polygon",
coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ]
};
};
graticule.extent = function(_) {
if (!arguments.length) return graticule.minorExtent();
return graticule.majorExtent(_).minorExtent(_);
};
graticule.majorExtent = function(_) {
if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ];
X0 = +_[0][0], X1 = +_[1][0];
Y0 = +_[0][1], Y1 = +_[1][1];
if (X0 > X1) _ = X0, X0 = X1, X1 = _;
if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
return graticule.precision(precision);
};
graticule.minorExtent = function(_) {
if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
x0 = +_[0][0], x1 = +_[1][0];
y0 = +_[0][1], y1 = +_[1][1];
if (x0 > x1) _ = x0, x0 = x1, x1 = _;
if (y0 > y1) _ = y0, y0 = y1, y1 = _;
return graticule.precision(precision);
};
graticule.step = function(_) {
if (!arguments.length) return graticule.minorStep();
return graticule.majorStep(_).minorStep(_);
};
graticule.majorStep = function(_) {
if (!arguments.length) return [ DX, DY ];
DX = +_[0], DY = +_[1];
return graticule;
};
graticule.minorStep = function(_) {
if (!arguments.length) return [ dx, dy ];
dx = +_[0], dy = +_[1];
return graticule;
};
graticule.precision = function(_) {
if (!arguments.length) return precision;
precision = +_;
x = d3_geo_graticuleX(y0, y1, 90);
y = d3_geo_graticuleY(x0, x1, precision);
X = d3_geo_graticuleX(Y0, Y1, 90);
Y = d3_geo_graticuleY(X0, X1, precision);
return graticule;
};
return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]);
};
function d3_geo_graticuleX(y0, y1, dy) {
var y = d3.range(y0, y1 - ε, dy).concat(y1);
return function(x) {
return y.map(function(y) {
return [ x, y ];
});
};
}
function d3_geo_graticuleY(x0, x1, dx) {
var x = d3.range(x0, x1 - ε, dx).concat(x1);
return function(y) {
return x.map(function(x) {
return [ x, y ];
});
};
}
function d3_source(d) {
return d.source;
}
function d3_target(d) {
return d.target;
}
d3.geo.greatArc = function() {
var source = d3_source, source_, target = d3_target, target_;
function greatArc() {
return {
type: "LineString",
coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ]
};
}
greatArc.distance = function() {
return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments));
};
greatArc.source = function(_) {
if (!arguments.length) return source;
source = _, source_ = typeof _ === "function" ? null : _;
return greatArc;
};
greatArc.target = function(_) {
if (!arguments.length) return target;
target = _, target_ = typeof _ === "function" ? null : _;
return greatArc;
};
greatArc.precision = function() {
return arguments.length ? greatArc : 0;
};
return greatArc;
};
d3.geo.interpolate = function(source, target) {
return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians);
};
function d3_geo_interpolate(x0, y0, x1, y1) {
var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d);
var interpolate = d ? function(t) {
var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ];
} : function() {
return [ x0 * d3_degrees, y0 * d3_degrees ];
};
interpolate.distance = d;
return interpolate;
}
d3.geo.length = function(object) {
d3_geo_lengthSum = 0;
d3.geo.stream(object, d3_geo_length);
return d3_geo_lengthSum;
};
var d3_geo_lengthSum;
var d3_geo_length = {
sphere: d3_noop,
point: d3_noop,
lineStart: d3_geo_lengthLineStart,
lineEnd: d3_noop,
polygonStart: d3_noop,
polygonEnd: d3_noop
};
function d3_geo_lengthLineStart() {
var λ0, sinφ0, cosφ0;
d3_geo_length.point = function(λ, φ) {
λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ);
d3_geo_length.point = nextPoint;
};
d3_geo_length.lineEnd = function() {
d3_geo_length.point = d3_geo_length.lineEnd = d3_noop;
};
function nextPoint(λ, φ) {
var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t);
d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ);
λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ;
}
}
function d3_geo_azimuthal(scale, angle) {
function azimuthal(λ, φ) {
var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ);
return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ];
}
azimuthal.invert = function(x, y) {
var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c);
return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ];
};
return azimuthal;
}
var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) {
return Math.sqrt(2 / (1 + cosλcosφ));
}, function(ρ) {
return 2 * Math.asin(ρ / 2);
});
(d3.geo.azimuthalEqualArea = function() {
return d3_geo_projection(d3_geo_azimuthalEqualArea);
}).raw = d3_geo_azimuthalEqualArea;
var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) {
var c = Math.acos(cosλcosφ);
return c && c / Math.sin(c);
}, d3_identity);
(d3.geo.azimuthalEquidistant = function() {
return d3_geo_projection(d3_geo_azimuthalEquidistant);
}).raw = d3_geo_azimuthalEquidistant;
function d3_geo_conicConformal(φ0, φ1) {
var cosφ0 = Math.cos(φ0), t = function(φ) {
return Math.tan(π / 4 + φ / 2);
}, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n;
if (!n) return d3_geo_mercator;
function forward(λ, φ) {
if (F > 0) {
if (φ < -halfπ + ε) φ = -halfπ + ε;
} else {
if (φ > halfπ - ε) φ = halfπ - ε;
}
var ρ = F / Math.pow(t(φ), n);
return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ];
}
forward.invert = function(x, y) {
var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y);
return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ];
};
return forward;
}
(d3.geo.conicConformal = function() {
return d3_geo_conic(d3_geo_conicConformal);
}).raw = d3_geo_conicConformal;
function d3_geo_conicEquidistant(φ0, φ1) {
var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0;
if (abs(n) < ε) return d3_geo_equirectangular;
function forward(λ, φ) {
var ρ = G - φ;
return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ];
}
forward.invert = function(x, y) {
var ρ0_y = G - y;
return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ];
};
return forward;
}
(d3.geo.conicEquidistant = function() {
return d3_geo_conic(d3_geo_conicEquidistant);
}).raw = d3_geo_conicEquidistant;
var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) {
return 1 / cosλcosφ;
}, Math.atan);
(d3.geo.gnomonic = function() {
return d3_geo_projection(d3_geo_gnomonic);
}).raw = d3_geo_gnomonic;
function d3_geo_mercator(λ, φ) {
return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ];
}
d3_geo_mercator.invert = function(x, y) {
return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ];
};
function d3_geo_mercatorProjection(project) {
var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto;
m.scale = function() {
var v = scale.apply(m, arguments);
return v === m ? clipAuto ? m.clipExtent(null) : m : v;
};
m.translate = function() {
var v = translate.apply(m, arguments);
return v === m ? clipAuto ? m.clipExtent(null) : m : v;
};
m.clipExtent = function(_) {
var v = clipExtent.apply(m, arguments);
if (v === m) {
if (clipAuto = _ == null) {
var k = π * scale(), t = translate();
clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]);
}
} else if (clipAuto) {
v = null;
}
return v;
};
return m.clipExtent(null);
}
(d3.geo.mercator = function() {
return d3_geo_mercatorProjection(d3_geo_mercator);
}).raw = d3_geo_mercator;
var d3_geo_orthographic = d3_geo_azimuthal(function() {
return 1;
}, Math.asin);
(d3.geo.orthographic = function() {
return d3_geo_projection(d3_geo_orthographic);
}).raw = d3_geo_orthographic;
var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) {
return 1 / (1 + cosλcosφ);
}, function(ρ) {
return 2 * Math.atan(ρ);
});
(d3.geo.stereographic = function() {
return d3_geo_projection(d3_geo_stereographic);
}).raw = d3_geo_stereographic;
function d3_geo_transverseMercator(λ, φ) {
return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ];
}
d3_geo_transverseMercator.invert = function(x, y) {
return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ];
};
(d3.geo.transverseMercator = function() {
var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate;
projection.center = function(_) {
return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]);
};
projection.rotate = function(_) {
return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(),
[ _[0], _[1], _[2] - 90 ]);
};
return rotate([ 0, 0, 90 ]);
}).raw = d3_geo_transverseMercator;
d3.geom = {};
function d3_geom_pointX(d) {
return d[0];
}
function d3_geom_pointY(d) {
return d[1];
}
d3.geom.hull = function(vertices) {
var x = d3_geom_pointX, y = d3_geom_pointY;
if (arguments.length) return hull(vertices);
function hull(data) {
if (data.length < 3) return [];
var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
for (i = 0; i < n; i++) {
points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]);
}
points.sort(d3_geom_hullOrder);
for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]);
var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
return polygon;
}
hull.x = function(_) {
return arguments.length ? (x = _, hull) : x;
};
hull.y = function(_) {
return arguments.length ? (y = _, hull) : y;
};
return hull;
};
function d3_geom_hullUpper(points) {
var n = points.length, hull = [ 0, 1 ], hs = 2;
for (var i = 2; i < n; i++) {
while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
hull[hs++] = i;
}
return hull.slice(0, hs);
}
function d3_geom_hullOrder(a, b) {
return a[0] - b[0] || a[1] - b[1];
}
d3.geom.polygon = function(coordinates) {
d3_subclass(coordinates, d3_geom_polygonPrototype);
return coordinates;
};
var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
d3_geom_polygonPrototype.area = function() {
var i = -1, n = this.length, a, b = this[n - 1], area = 0;
while (++i < n) {
a = b;
b = this[i];
area += a[1] * b[0] - a[0] * b[1];
}
return area * .5;
};
d3_geom_polygonPrototype.centroid = function(k) {
var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
if (!arguments.length) k = -1 / (6 * this.area());
while (++i < n) {
a = b;
b = this[i];
c = a[0] * b[1] - b[0] * a[1];
x += (a[0] + b[0]) * c;
y += (a[1] + b[1]) * c;
}
return [ x * k, y * k ];
};
d3_geom_polygonPrototype.clip = function(subject) {
var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
while (++i < n) {
input = subject.slice();
subject.length = 0;
b = this[i];
c = input[(m = input.length - closed) - 1];
j = -1;
while (++j < m) {
d = input[j];
if (d3_geom_polygonInside(d, a, b)) {
if (!d3_geom_polygonInside(c, a, b)) {
subject.push(d3_geom_polygonIntersect(c, d, a, b));
}
subject.push(d);
} else if (d3_geom_polygonInside(c, a, b)) {
subject.push(d3_geom_polygonIntersect(c, d, a, b));
}
c = d;
}
if (closed) subject.push(subject[0]);
a = b;
}
return subject;
};
function d3_geom_polygonInside(p, a, b) {
return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
}
function d3_geom_polygonIntersect(c, d, a, b) {
var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
return [ x1 + ua * x21, y1 + ua * y21 ];
}
function d3_geom_polygonClosed(coordinates) {
var a = coordinates[0], b = coordinates[coordinates.length - 1];
return !(a[0] - b[0] || a[1] - b[1]);
}
var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
function d3_geom_voronoiBeach() {
d3_geom_voronoiRedBlackNode(this);
this.edge = this.site = this.circle = null;
}
function d3_geom_voronoiCreateBeach(site) {
var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
beach.site = site;
return beach;
}
function d3_geom_voronoiDetachBeach(beach) {
d3_geom_voronoiDetachCircle(beach);
d3_geom_voronoiBeaches.remove(beach);
d3_geom_voronoiBeachPool.push(beach);
d3_geom_voronoiRedBlackNode(beach);
}
function d3_geom_voronoiRemoveBeach(beach) {
var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
x: x,
y: y
}, previous = beach.P, next = beach.N, disappearing = [ beach ];
d3_geom_voronoiDetachBeach(beach);
var lArc = previous;
while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) {
previous = lArc.P;
disappearing.unshift(lArc);
d3_geom_voronoiDetachBeach(lArc);
lArc = previous;
}
disappearing.unshift(lArc);
d3_geom_voronoiDetachCircle(lArc);
var rArc = next;
while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) {
next = rArc.N;
disappearing.push(rArc);
d3_geom_voronoiDetachBeach(rArc);
rArc = next;
}
disappearing.push(rArc);
d3_geom_voronoiDetachCircle(rArc);
var nArcs = disappearing.length, iArc;
for (iArc = 1; iArc < nArcs; ++iArc) {
rArc = disappearing[iArc];
lArc = disappearing[iArc - 1];
d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
}
lArc = disappearing[0];
rArc = disappearing[nArcs - 1];
rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
}
function d3_geom_voronoiAddBeach(site) {
var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
while (node) {
dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
if (dxl > ε) node = node.L; else {
dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
if (dxr > ε) {
if (!node.R) {
lArc = node;
break;
}
node = node.R;
} else {
if (dxl > -ε) {
lArc = node.P;
rArc = node;
} else if (dxr > -ε) {
lArc = node;
rArc = node.N;
} else {
lArc = rArc = node;
}
break;
}
}
}
var newArc = d3_geom_voronoiCreateBeach(site);
d3_geom_voronoiBeaches.insert(lArc, newArc);
if (!lArc && !rArc) return;
if (lArc === rArc) {
d3_geom_voronoiDetachCircle(lArc);
rArc = d3_geom_voronoiCreateBeach(lArc.site);
d3_geom_voronoiBeaches.insert(newArc, rArc);
newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
return;
}
if (!rArc) {
newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
return;
}
d3_geom_voronoiDetachCircle(lArc);
d3_geom_voronoiDetachCircle(rArc);
var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
x: (cy * hb - by * hc) / d + ax,
y: (bx * hc - cx * hb) / d + ay
};
d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
}
function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
if (!pby2) return rfocx;
var lArc = arc.P;
if (!lArc) return -Infinity;
site = lArc.site;
var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
if (!plby2) return lfocx;
var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
return (rfocx + lfocx) / 2;
}
function d3_geom_voronoiRightBreakPoint(arc, directrix) {
var rArc = arc.N;
if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
var site = arc.site;
return site.y === directrix ? site.x : Infinity;
}
function d3_geom_voronoiCell(site) {
this.site = site;
this.edges = [];
}
d3_geom_voronoiCell.prototype.prepare = function() {
var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
while (iHalfEdge--) {
edge = halfEdges[iHalfEdge].edge;
if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
}
halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
return halfEdges.length;
};
function d3_geom_voronoiCloseCells(extent) {
var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
while (iCell--) {
cell = cells[iCell];
if (!cell || !cell.prepare()) continue;
halfEdges = cell.edges;
nHalfEdges = halfEdges.length;
iHalfEdge = 0;
while (iHalfEdge < nHalfEdges) {
end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) {
halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? {
x: x0,
y: abs(x2 - x0) < ε ? y2 : y1
} : abs(y3 - y1) < ε && x1 - x3 > ε ? {
x: abs(y2 - y1) < ε ? x2 : x1,
y: y1
} : abs(x3 - x1) < ε && y3 - y0 > ε ? {
x: x1,
y: abs(x2 - x1) < ε ? y2 : y0
} : abs(y3 - y0) < ε && x3 - x0 > ε ? {
x: abs(y2 - y0) < ε ? x2 : x0,
y: y0
} : null), cell.site, null));
++nHalfEdges;
}
}
}
}
function d3_geom_voronoiHalfEdgeOrder(a, b) {
return b.angle - a.angle;
}
function d3_geom_voronoiCircle() {
d3_geom_voronoiRedBlackNode(this);
this.x = this.y = this.arc = this.site = this.cy = null;
}
function d3_geom_voronoiAttachCircle(arc) {
var lArc = arc.P, rArc = arc.N;
if (!lArc || !rArc) return;
var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
if (lSite === rSite) return;
var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
var d = 2 * (ax * cy - ay * cx);
if (d >= -ε2) return;
var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
circle.arc = arc;
circle.site = cSite;
circle.x = x + bx;
circle.y = cy + Math.sqrt(x * x + y * y);
circle.cy = cy;
arc.circle = circle;
var before = null, node = d3_geom_voronoiCircles._;
while (node) {
if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
if (node.L) node = node.L; else {
before = node.P;
break;
}
} else {
if (node.R) node = node.R; else {
before = node;
break;
}
}
}
d3_geom_voronoiCircles.insert(before, circle);
if (!before) d3_geom_voronoiFirstCircle = circle;
}
function d3_geom_voronoiDetachCircle(arc) {
var circle = arc.circle;
if (circle) {
if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
d3_geom_voronoiCircles.remove(circle);
d3_geom_voronoiCirclePool.push(circle);
d3_geom_voronoiRedBlackNode(circle);
arc.circle = null;
}
}
function d3_geom_voronoiClipEdges(extent) {
var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
while (i--) {
e = edges[i];
if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) {
e.a = e.b = null;
edges.splice(i, 1);
}
}
}
function d3_geom_voronoiConnectEdge(edge, extent) {
var vb = edge.b;
if (vb) return true;
var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
if (ry === ly) {
if (fx < x0 || fx >= x1) return;
if (lx > rx) {
if (!va) va = {
x: fx,
y: y0
}; else if (va.y >= y1) return;
vb = {
x: fx,
y: y1
};
} else {
if (!va) va = {
x: fx,
y: y1
}; else if (va.y < y0) return;
vb = {
x: fx,
y: y0
};
}
} else {
fm = (lx - rx) / (ry - ly);
fb = fy - fm * fx;
if (fm < -1 || fm > 1) {
if (lx > rx) {
if (!va) va = {
x: (y0 - fb) / fm,
y: y0
}; else if (va.y >= y1) return;
vb = {
x: (y1 - fb) / fm,
y: y1
};
} else {
if (!va) va = {
x: (y1 - fb) / fm,
y: y1
}; else if (va.y < y0) return;
vb = {
x: (y0 - fb) / fm,
y: y0
};
}
} else {
if (ly < ry) {
if (!va) va = {
x: x0,
y: fm * x0 + fb
}; else if (va.x >= x1) return;
vb = {
x: x1,
y: fm * x1 + fb
};
} else {
if (!va) va = {
x: x1,
y: fm * x1 + fb
}; else if (va.x < x0) return;
vb = {
x: x0,
y: fm * x0 + fb
};
}
}
}
edge.a = va;
edge.b = vb;
return true;
}
function d3_geom_voronoiEdge(lSite, rSite) {
this.l = lSite;
this.r = rSite;
this.a = this.b = null;
}
function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
var edge = new d3_geom_voronoiEdge(lSite, rSite);
d3_geom_voronoiEdges.push(edge);
if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
return edge;
}
function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
var edge = new d3_geom_voronoiEdge(lSite, null);
edge.a = va;
edge.b = vb;
d3_geom_voronoiEdges.push(edge);
return edge;
}
function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
if (!edge.a && !edge.b) {
edge.a = vertex;
edge.l = lSite;
edge.r = rSite;
} else if (edge.l === rSite) {
edge.b = vertex;
} else {
edge.a = vertex;
}
}
function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
var va = edge.a, vb = edge.b;
this.edge = edge;
this.site = lSite;
this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
}
d3_geom_voronoiHalfEdge.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;
}
};
function d3_geom_voronoiRedBlackTree() {
this._ = null;
}
function d3_geom_voronoiRedBlackNode(node) {
node.U = node.C = node.L = node.R = node.P = node.N = null;
}
d3_geom_voronoiRedBlackTree.prototype = {
insert: function(after, node) {
var parent, grandpa, uncle;
if (after) {
node.P = after;
node.N = after.N;
if (after.N) after.N.P = node;
after.N = node;
if (after.R) {
after = after.R;
while (after.L) after = after.L;
after.L = node;
} else {
after.R = node;
}
parent = after;
} else if (this._) {
after = d3_geom_voronoiRedBlackFirst(this._);
node.P = null;
node.N = after;
after.P = after.L = node;
parent = after;
} else {
node.P = node.N = null;
this._ = node;
parent = null;
}
node.L = node.R = null;
node.U = parent;
node.C = true;
after = node;
while (parent && parent.C) {
grandpa = parent.U;
if (parent === grandpa.L) {
uncle = grandpa.R;
if (uncle && uncle.C) {
parent.C = uncle.C = false;
grandpa.C = true;
after = grandpa;
} else {
if (after === parent.R) {
d3_geom_voronoiRedBlackRotateLeft(this, parent);
after = parent;
parent = after.U;
}
parent.C = false;
grandpa.C = true;
d3_geom_voronoiRedBlackRotateRight(this, grandpa);
}
} else {
uncle = grandpa.L;
if (uncle && uncle.C) {
parent.C = uncle.C = false;
grandpa.C = true;
after = grandpa;
} else {
if (after === parent.L) {
d3_geom_voronoiRedBlackRotateRight(this, parent);
after = parent;
parent = after.U;
}
parent.C = false;
grandpa.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
}
}
parent = after.U;
}
this._.C = false;
},
remove: function(node) {
if (node.N) node.N.P = node.P;
if (node.P) node.P.N = node.N;
node.N = node.P = null;
var parent = node.U, sibling, left = node.L, right = node.R, next, red;
if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
if (parent) {
if (parent.L === node) parent.L = next; else parent.R = next;
} else {
this._ = next;
}
if (left && right) {
red = next.C;
next.C = node.C;
next.L = left;
left.U = next;
if (next !== right) {
parent = next.U;
next.U = node.U;
node = next.R;
parent.L = node;
next.R = right;
right.U = next;
} else {
next.U = parent;
parent = next;
node = next.R;
}
} else {
red = node.C;
node = next;
}
if (node) node.U = parent;
if (red) return;
if (node && node.C) {
node.C = false;
return;
}
do {
if (node === this._) break;
if (node === parent.L) {
sibling = parent.R;
if (sibling.C) {
sibling.C = false;
parent.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, parent);
sibling = parent.R;
}
if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
if (!sibling.R || !sibling.R.C) {
sibling.L.C = false;
sibling.C = true;
d3_geom_voronoiRedBlackRotateRight(this, sibling);
sibling = parent.R;
}
sibling.C = parent.C;
parent.C = sibling.R.C = false;
d3_geom_voronoiRedBlackRotateLeft(this, parent);
node = this._;
break;
}
} else {
sibling = parent.L;
if (sibling.C) {
sibling.C = false;
parent.C = true;
d3_geom_voronoiRedBlackRotateRight(this, parent);
sibling = parent.L;
}
if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
if (!sibling.L || !sibling.L.C) {
sibling.R.C = false;
sibling.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, sibling);
sibling = parent.L;
}
sibling.C = parent.C;
parent.C = sibling.L.C = false;
d3_geom_voronoiRedBlackRotateRight(this, parent);
node = this._;
break;
}
}
sibling.C = true;
node = parent;
parent = parent.U;
} while (!node.C);
if (node) node.C = false;
}
};
function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
var p = node, q = node.R, parent = p.U;
if (parent) {
if (parent.L === p) parent.L = q; else parent.R = q;
} else {
tree._ = q;
}
q.U = parent;
p.U = q;
p.R = q.L;
if (p.R) p.R.U = p;
q.L = p;
}
function d3_geom_voronoiRedBlackRotateRight(tree, node) {
var p = node, q = node.L, parent = p.U;
if (parent) {
if (parent.L === p) parent.L = q; else parent.R = q;
} else {
tree._ = q;
}
q.U = parent;
p.U = q;
p.L = q.R;
if (p.L) p.L.U = p;
q.R = p;
}
function d3_geom_voronoiRedBlackFirst(node) {
while (node.L) node = node.L;
return node;
}
function d3_geom_voronoi(sites, bbox) {
var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
d3_geom_voronoiEdges = [];
d3_geom_voronoiCells = new Array(sites.length);
d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
while (true) {
circle = d3_geom_voronoiFirstCircle;
if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
if (site.x !== x0 || site.y !== y0) {
d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
d3_geom_voronoiAddBeach(site);
x0 = site.x, y0 = site.y;
}
site = sites.pop();
} else if (circle) {
d3_geom_voronoiRemoveBeach(circle.arc);
} else {
break;
}
}
if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
var diagram = {
cells: d3_geom_voronoiCells,
edges: d3_geom_voronoiEdges
};
d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
return diagram;
}
function d3_geom_voronoiVertexOrder(a, b) {
return b.y - a.y || b.x - a.x;
}
d3.geom.voronoi = function(points) {
var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
if (points) return voronoi(points);
function voronoi(data) {
var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
var s = e.start();
return [ s.x, s.y ];
}) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
polygon.point = data[i];
});
return polygons;
}
function sites(data) {
return data.map(function(d, i) {
return {
x: Math.round(fx(d, i) / ε) * ε,
y: Math.round(fy(d, i) / ε) * ε,
i: i
};
});
}
voronoi.links = function(data) {
return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
return edge.l && edge.r;
}).map(function(edge) {
return {
source: data[edge.l.i],
target: data[edge.r.i]
};
});
};
voronoi.triangles = function(data) {
var triangles = [];
d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
while (++j < m) {
e0 = e1;
s0 = s1;
e1 = edges[j].edge;
s1 = e1.l === site ? e1.r : e1.l;
if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
triangles.push([ data[i], data[s0.i], data[s1.i] ]);
}
}
});
return triangles;
};
voronoi.x = function(_) {
return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
};
voronoi.y = function(_) {
return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
};
voronoi.clipExtent = function(_) {
if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
return voronoi;
};
voronoi.size = function(_) {
if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
};
return voronoi;
};
var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
function d3_geom_voronoiTriangleArea(a, b, c) {
return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
}
d3.geom.delaunay = function(vertices) {
return d3.geom.voronoi().triangles(vertices);
};
d3.geom.quadtree = function(points, x1, y1, x2, y2) {
var x = d3_geom_pointX, y = d3_geom_pointY, compat;
if (compat = arguments.length) {
x = d3_geom_quadtreeCompatX;
y = d3_geom_quadtreeCompatY;
if (compat === 3) {
y2 = y1;
x2 = x1;
y1 = x1 = 0;
}
return quadtree(points);
}
function quadtree(data) {
var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
if (x1 != null) {
x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
} else {
x2_ = y2_ = -(x1_ = y1_ = Infinity);
xs = [], ys = [];
n = data.length;
if (compat) for (i = 0; i < n; ++i) {
d = data[i];
if (d.x < x1_) x1_ = d.x;
if (d.y < y1_) y1_ = d.y;
if (d.x > x2_) x2_ = d.x;
if (d.y > y2_) y2_ = d.y;
xs.push(d.x);
ys.push(d.y);
} else for (i = 0; i < n; ++i) {
var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
if (x_ < x1_) x1_ = x_;
if (y_ < y1_) y1_ = y_;
if (x_ > x2_) x2_ = x_;
if (y_ > y2_) y2_ = y_;
xs.push(x_);
ys.push(y_);
}
}
var dx = x2_ - x1_, dy = y2_ - y1_;
if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
function insert(n, d, x, y, x1, y1, x2, y2) {
if (isNaN(x) || isNaN(y)) return;
if (n.leaf) {
var nx = n.x, ny = n.y;
if (nx != null) {
if (abs(nx - x) + abs(ny - y) < .01) {
insertChild(n, d, x, y, x1, y1, x2, y2);
} else {
var nPoint = n.point;
n.x = n.y = n.point = null;
insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
insertChild(n, d, x, y, x1, y1, x2, y2);
}
} else {
n.x = x, n.y = y, n.point = d;
}
} else {
insertChild(n, d, x, y, x1, y1, x2, y2);
}
}
function insertChild(n, d, x, y, x1, y1, x2, y2) {
var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right;
n.leaf = false;
n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
if (right) x1 = xm; else x2 = xm;
if (below) y1 = ym; else y2 = ym;
insert(n, d, x, y, x1, y1, x2, y2);
}
var root = d3_geom_quadtreeNode();
root.add = function(d) {
insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
};
root.visit = function(f) {
d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
};
root.find = function(point) {
return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
};
i = -1;
if (x1 == null) {
while (++i < n) {
insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
}
--i;
} else data.forEach(root.add);
xs = ys = data = d = null;
return root;
}
quadtree.x = function(_) {
return arguments.length ? (x = _, quadtree) : x;
};
quadtree.y = function(_) {
return arguments.length ? (y = _, quadtree) : y;
};
quadtree.extent = function(_) {
if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0],
y2 = +_[1][1];
return quadtree;
};
quadtree.size = function(_) {
if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
return quadtree;
};
return quadtree;
};
function d3_geom_quadtreeCompatX(d) {
return d.x;
}
function d3_geom_quadtreeCompatY(d) {
return d.y;
}
function d3_geom_quadtreeNode() {
return {
leaf: true,
nodes: [],
point: null,
x: null,
y: null
};
}
function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
if (!f(node, x1, y1, x2, y2)) {
var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
}
}
function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
var minDistance2 = Infinity, closestPoint;
(function find(node, x1, y1, x2, y2) {
if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
if (point = node.point) {
var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
if (distance2 < minDistance2) {
var distance = Math.sqrt(minDistance2 = distance2);
x0 = x - distance, y0 = y - distance;
x3 = x + distance, y3 = y + distance;
closestPoint = point;
}
}
var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym;
for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
if (node = children[i & 3]) switch (i & 3) {
case 0:
find(node, x1, y1, xm, ym);
break;
case 1:
find(node, xm, y1, x2, ym);
break;
case 2:
find(node, x1, ym, xm, y2);
break;
case 3:
find(node, xm, ym, x2, y2);
break;
}
}
})(root, x0, y0, x3, y3);
return closestPoint;
}
d3.interpolateRgb = d3_interpolateRgb;
function d3_interpolateRgb(a, b) {
a = d3.rgb(a);
b = d3.rgb(b);
var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
return function(t) {
return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
};
}
d3.interpolateObject = d3_interpolateObject;
function d3_interpolateObject(a, b) {
var i = {}, c = {}, k;
for (k in a) {
if (k in b) {
i[k] = d3_interpolate(a[k], b[k]);
} else {
c[k] = a[k];
}
}
for (k in b) {
if (!(k in a)) {
c[k] = b[k];
}
}
return function(t) {
for (k in i) c[k] = i[k](t);
return c;
};
}
d3.interpolateNumber = d3_interpolateNumber;
function d3_interpolateNumber(a, b) {
a = +a, b = +b;
return function(t) {
return a * (1 - t) + b * t;
};
}
d3.interpolateString = d3_interpolateString;
function d3_interpolateString(a, b) {
var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
a = a + "", b = b + "";
while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
if ((bs = bm.index) > bi) {
bs = b.slice(bi, bs);
if (s[i]) s[i] += bs; else s[++i] = bs;
}
if ((am = am[0]) === (bm = bm[0])) {
if (s[i]) s[i] += bm; else s[++i] = bm;
} else {
s[++i] = null;
q.push({
i: i,
x: d3_interpolateNumber(am, bm)
});
}
bi = d3_interpolate_numberB.lastIndex;
}
if (bi < b.length) {
bs = b.slice(bi);
if (s[i]) s[i] += bs; else s[++i] = bs;
}
return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
return b(t) + "";
}) : function() {
return b;
} : (b = q.length, function(t) {
for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
return s.join("");
});
}
var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
d3.interpolate = d3_interpolate;
function d3_interpolate(a, b) {
var i = d3.interpolators.length, f;
while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
return f;
}
d3.interpolators = [ function(a, b) {
var t = typeof b;
return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
} ];
d3.interpolateArray = d3_interpolateArray;
function d3_interpolateArray(a, b) {
var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
for (;i < na; ++i) c[i] = a[i];
for (;i < nb; ++i) c[i] = b[i];
return function(t) {
for (i = 0; i < n0; ++i) c[i] = x[i](t);
return c;
};
}
var d3_ease_default = function() {
return d3_identity;
};
var d3_ease = d3.map({
linear: d3_ease_default,
poly: d3_ease_poly,
quad: function() {
return d3_ease_quad;
},
cubic: function() {
return d3_ease_cubic;
},
sin: function() {
return d3_ease_sin;
},
exp: function() {
return d3_ease_exp;
},
circle: function() {
return d3_ease_circle;
},
elastic: d3_ease_elastic,
back: d3_ease_back,
bounce: function() {
return d3_ease_bounce;
}
});
var d3_ease_mode = d3.map({
"in": d3_identity,
out: d3_ease_reverse,
"in-out": d3_ease_reflect,
"out-in": function(f) {
return d3_ease_reflect(d3_ease_reverse(f));
}
});
d3.ease = function(name) {
var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in";
t = d3_ease.get(t) || d3_ease_default;
m = d3_ease_mode.get(m) || d3_identity;
return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
};
function d3_ease_clamp(f) {
return function(t) {
return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
};
}
function d3_ease_reverse(f) {
return function(t) {
return 1 - f(1 - t);
};
}
function d3_ease_reflect(f) {
return function(t) {
return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
};
}
function d3_ease_quad(t) {
return t * t;
}
function d3_ease_cubic(t) {
return t * t * t;
}
function d3_ease_cubicInOut(t) {
if (t <= 0) return 0;
if (t >= 1) return 1;
var t2 = t * t, t3 = t2 * t;
return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
}
function d3_ease_poly(e) {
return function(t) {
return Math.pow(t, e);
};
}
function d3_ease_sin(t) {
return 1 - Math.cos(t * halfπ);
}
function d3_ease_exp(t) {
return Math.pow(2, 10 * (t - 1));
}
function d3_ease_circle(t) {
return 1 - Math.sqrt(1 - t * t);
}
function d3_ease_elastic(a, p) {
var s;
if (arguments.length < 2) p = .45;
if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4;
return function(t) {
return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p);
};
}
function d3_ease_back(s) {
if (!s) s = 1.70158;
return function(t) {
return t * t * ((s + 1) * t - s);
};
}
function d3_ease_bounce(t) {
return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
}
d3.interpolateHcl = d3_interpolateHcl;
function d3_interpolateHcl(a, b) {
a = d3.hcl(a);
b = d3.hcl(b);
var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
return function(t) {
return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
};
}
d3.interpolateHsl = d3_interpolateHsl;
function d3_interpolateHsl(a, b) {
a = d3.hsl(a);
b = d3.hsl(b);
var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
return function(t) {
return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
};
}
d3.interpolateLab = d3_interpolateLab;
function d3_interpolateLab(a, b) {
a = d3.lab(a);
b = d3.lab(b);
var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
return function(t) {
return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
};
}
d3.interpolateRound = d3_interpolateRound;
function d3_interpolateRound(a, b) {
b -= a;
return function(t) {
return Math.round(a + b * t);
};
}
d3.transform = function(string) {
var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
return (d3.transform = function(string) {
if (string != null) {
g.setAttribute("transform", string);
var t = g.transform.baseVal.consolidate();
}
return new d3_transform(t ? t.matrix : d3_transformIdentity);
})(string);
};
function d3_transform(m) {
var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
if (r0[0] * r1[1] < r1[0] * r0[1]) {
r0[0] *= -1;
r0[1] *= -1;
kx *= -1;
kz *= -1;
}
this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
this.translate = [ m.e, m.f ];
this.scale = [ kx, ky ];
this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
}
d3_transform.prototype.toString = function() {
return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
};
function d3_transformDot(a, b) {
return a[0] * b[0] + a[1] * b[1];
}
function d3_transformNormalize(a) {
var k = Math.sqrt(d3_transformDot(a, a));
if (k) {
a[0] /= k;
a[1] /= k;
}
return k;
}
function d3_transformCombine(a, b, k) {
a[0] += k * b[0];
a[1] += k * b[1];
return a;
}
var d3_transformIdentity = {
a: 1,
b: 0,
c: 0,
d: 1,
e: 0,
f: 0
};
d3.interpolateTransform = d3_interpolateTransform;
function d3_interpolateTransformPop(s) {
return s.length ? s.pop() + "," : "";
}
function d3_interpolateTranslate(ta, tb, s, q) {
if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
var i = s.push("translate(", null, ",", null, ")");
q.push({
i: i - 4,
x: d3_interpolateNumber(ta[0], tb[0])
}, {
i: i - 2,
x: d3_interpolateNumber(ta[1], tb[1])
});
} else if (tb[0] || tb[1]) {
s.push("translate(" + tb + ")");
}
}
function d3_interpolateRotate(ra, rb, s, q) {
if (ra !== rb) {
if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
q.push({
i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
x: d3_interpolateNumber(ra, rb)
});
} else if (rb) {
s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
}
}
function d3_interpolateSkew(wa, wb, s, q) {
if (wa !== wb) {
q.push({
i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
x: d3_interpolateNumber(wa, wb)
});
} else if (wb) {
s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
}
}
function d3_interpolateScale(ka, kb, s, q) {
if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
q.push({
i: i - 4,
x: d3_interpolateNumber(ka[0], kb[0])
}, {
i: i - 2,
x: d3_interpolateNumber(ka[1], kb[1])
});
} else if (kb[0] !== 1 || kb[1] !== 1) {
s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
}
}
function d3_interpolateTransform(a, b) {
var s = [], q = [];
a = d3.transform(a), b = d3.transform(b);
d3_interpolateTranslate(a.translate, b.translate, s, q);
d3_interpolateRotate(a.rotate, b.rotate, s, q);
d3_interpolateSkew(a.skew, b.skew, s, q);
d3_interpolateScale(a.scale, b.scale, s, q);
a = b = null;
return function(t) {
var i = -1, n = q.length, o;
while (++i < n) s[(o = q[i]).i] = o.x(t);
return s.join("");
};
}
function d3_uninterpolateNumber(a, b) {
b = (b -= a = +a) || 1 / b;
return function(x) {
return (x - a) / b;
};
}
function d3_uninterpolateClamp(a, b) {
b = (b -= a = +a) || 1 / b;
return function(x) {
return Math.max(0, Math.min(1, (x - a) / b));
};
}
d3.layout = {};
d3.layout.bundle = function() {
return function(links) {
var paths = [], i = -1, n = links.length;
while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
return paths;
};
};
function d3_layout_bundlePath(link) {
var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
while (start !== lca) {
start = start.parent;
points.push(start);
}
var k = points.length;
while (end !== lca) {
points.splice(k, 0, end);
end = end.parent;
}
return points;
}
function d3_layout_bundleAncestors(node) {
var ancestors = [], parent = node.parent;
while (parent != null) {
ancestors.push(node);
node = parent;
parent = parent.parent;
}
ancestors.push(node);
return ancestors;
}
function d3_layout_bundleLeastCommonAncestor(a, b) {
if (a === b) return a;
var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
while (aNode === bNode) {
sharedNode = aNode;
aNode = aNodes.pop();
bNode = bNodes.pop();
}
return sharedNode;
}
d3.layout.chord = function() {
var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
function relayout() {
var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
chords = [];
groups = [];
k = 0, i = -1;
while (++i < n) {
x = 0, j = -1;
while (++j < n) {
x += matrix[i][j];
}
groupSums.push(x);
subgroupIndex.push(d3.range(n));
k += x;
}
if (sortGroups) {
groupIndex.sort(function(a, b) {
return sortGroups(groupSums[a], groupSums[b]);
});
}
if (sortSubgroups) {
subgroupIndex.forEach(function(d, i) {
d.sort(function(a, b) {
return sortSubgroups(matrix[i][a], matrix[i][b]);
});
});
}
k = (τ - padding * n) / k;
x = 0, i = -1;
while (++i < n) {
x0 = x, j = -1;
while (++j < n) {
var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
subgroups[di + "-" + dj] = {
index: di,
subindex: dj,
startAngle: a0,
endAngle: a1,
value: v
};
}
groups[di] = {
index: di,
startAngle: x0,
endAngle: x,
value: groupSums[di]
};
x += padding;
}
i = -1;
while (++i < n) {
j = i - 1;
while (++j < n) {
var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
if (source.value || target.value) {
chords.push(source.value < target.value ? {
source: target,
target: source
} : {
source: source,
target: target
});
}
}
}
if (sortChords) resort();
}
function resort() {
chords.sort(function(a, b) {
return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
});
}
chord.matrix = function(x) {
if (!arguments.length) return matrix;
n = (matrix = x) && matrix.length;
chords = groups = null;
return chord;
};
chord.padding = function(x) {
if (!arguments.length) return padding;
padding = x;
chords = groups = null;
return chord;
};
chord.sortGroups = function(x) {
if (!arguments.length) return sortGroups;
sortGroups = x;
chords = groups = null;
return chord;
};
chord.sortSubgroups = function(x) {
if (!arguments.length) return sortSubgroups;
sortSubgroups = x;
chords = null;
return chord;
};
chord.sortChords = function(x) {
if (!arguments.length) return sortChords;
sortChords = x;
if (chords) resort();
return chord;
};
chord.chords = function() {
if (!chords) relayout();
return chords;
};
chord.groups = function() {
if (!groups) relayout();
return groups;
};
return chord;
};
d3.layout.force = function() {
var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges;
function repulse(node) {
return function(quad, x1, _, x2) {
if (quad.point !== node) {
var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
if (dw * dw / theta2 < dn) {
if (dn < chargeDistance2) {
var k = quad.charge / dn;
node.px -= dx * k;
node.py -= dy * k;
}
return true;
}
if (quad.point && dn && dn < chargeDistance2) {
var k = quad.pointCharge / dn;
node.px -= dx * k;
node.py -= dy * k;
}
}
return !quad.charge;
};
}
force.tick = function() {
if ((alpha *= .99) < .005) {
timer = null;
event.end({
type: "end",
alpha: alpha = 0
});
return true;
}
var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
for (i = 0; i < m; ++i) {
o = links[i];
s = o.source;
t = o.target;
x = t.x - s.x;
y = t.y - s.y;
if (l = x * x + y * y) {
l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
x *= l;
y *= l;
t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5);
t.y -= y * k;
s.x += x * (k = 1 - k);
s.y += y * k;
}
}
if (k = alpha * gravity) {
x = size[0] / 2;
y = size[1] / 2;
i = -1;
if (k) while (++i < n) {
o = nodes[i];
o.x += (x - o.x) * k;
o.y += (y - o.y) * k;
}
}
if (charge) {
d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
i = -1;
while (++i < n) {
if (!(o = nodes[i]).fixed) {
q.visit(repulse(o));
}
}
}
i = -1;
while (++i < n) {
o = nodes[i];
if (o.fixed) {
o.x = o.px;
o.y = o.py;
} else {
o.x -= (o.px - (o.px = o.x)) * friction;
o.y -= (o.py - (o.py = o.y)) * friction;
}
}
event.tick({
type: "tick",
alpha: alpha
});
};
force.nodes = function(x) {
if (!arguments.length) return nodes;
nodes = x;
return force;
};
force.links = function(x) {
if (!arguments.length) return links;
links = x;
return force;
};
force.size = function(x) {
if (!arguments.length) return size;
size = x;
return force;
};
force.linkDistance = function(x) {
if (!arguments.length) return linkDistance;
linkDistance = typeof x === "function" ? x : +x;
return force;
};
force.distance = force.linkDistance;
force.linkStrength = function(x) {
if (!arguments.length) return linkStrength;
linkStrength = typeof x === "function" ? x : +x;
return force;
};
force.friction = function(x) {
if (!arguments.length) return friction;
friction = +x;
return force;
};
force.charge = function(x) {
if (!arguments.length) return charge;
charge = typeof x === "function" ? x : +x;
return force;
};
force.chargeDistance = function(x) {
if (!arguments.length) return Math.sqrt(chargeDistance2);
chargeDistance2 = x * x;
return force;
};
force.gravity = function(x) {
if (!arguments.length) return gravity;
gravity = +x;
return force;
};
force.theta = function(x) {
if (!arguments.length) return Math.sqrt(theta2);
theta2 = x * x;
return force;
};
force.alpha = function(x) {
if (!arguments.length) return alpha;
x = +x;
if (alpha) {
if (x > 0) {
alpha = x;
} else {
timer.c = null, timer.t = NaN, timer = null;
event.end({
type: "end",
alpha: alpha = 0
});
}
} else if (x > 0) {
event.start({
type: "start",
alpha: alpha = x
});
timer = d3_timer(force.tick);
}
return force;
};
force.start = function() {
var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
for (i = 0; i < n; ++i) {
(o = nodes[i]).index = i;
o.weight = 0;
}
for (i = 0; i < m; ++i) {
o = links[i];
if (typeof o.source == "number") o.source = nodes[o.source];
if (typeof o.target == "number") o.target = nodes[o.target];
++o.source.weight;
++o.target.weight;
}
for (i = 0; i < n; ++i) {
o = nodes[i];
if (isNaN(o.x)) o.x = position("x", w);
if (isNaN(o.y)) o.y = position("y", h);
if (isNaN(o.px)) o.px = o.x;
if (isNaN(o.py)) o.py = o.y;
}
distances = [];
if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
strengths = [];
if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
charges = [];
if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
function position(dimension, size) {
if (!neighbors) {
neighbors = new Array(n);
for (j = 0; j < n; ++j) {
neighbors[j] = [];
}
for (j = 0; j < m; ++j) {
var o = links[j];
neighbors[o.source.index].push(o.target);
neighbors[o.target.index].push(o.source);
}
}
var candidates = neighbors[i], j = -1, l = candidates.length, x;
while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
return Math.random() * size;
}
return force.resume();
};
force.resume = function() {
return force.alpha(.1);
};
force.stop = function() {
return force.alpha(0);
};
force.drag = function() {
if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
if (!arguments.length) return drag;
this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
};
function dragmove(d) {
d.px = d3.event.x, d.py = d3.event.y;
force.resume();
}
return d3.rebind(force, event, "on");
};
function d3_layout_forceDragstart(d) {
d.fixed |= 2;
}
function d3_layout_forceDragend(d) {
d.fixed &= ~6;
}
function d3_layout_forceMouseover(d) {
d.fixed |= 4;
d.px = d.x, d.py = d.y;
}
function d3_layout_forceMouseout(d) {
d.fixed &= ~4;
}
function d3_layout_forceAccumulate(quad, alpha, charges) {
var cx = 0, cy = 0;
quad.charge = 0;
if (!quad.leaf) {
var nodes = quad.nodes, n = nodes.length, i = -1, c;
while (++i < n) {
c = nodes[i];
if (c == null) continue;
d3_layout_forceAccumulate(c, alpha, charges);
quad.charge += c.charge;
cx += c.charge * c.cx;
cy += c.charge * c.cy;
}
}
if (quad.point) {
if (!quad.leaf) {
quad.point.x += Math.random() - .5;
quad.point.y += Math.random() - .5;
}
var k = alpha * charges[quad.point.index];
quad.charge += quad.pointCharge = k;
cx += k * quad.point.x;
cy += k * quad.point.y;
}
quad.cx = cx / quad.charge;
quad.cy = cy / quad.charge;
}
var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
d3.layout.hierarchy = function() {
var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
function hierarchy(root) {
var stack = [ root ], nodes = [], node;
root.depth = 0;
while ((node = stack.pop()) != null) {
nodes.push(node);
if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
var n, childs, child;
while (--n >= 0) {
stack.push(child = childs[n]);
child.parent = node;
child.depth = node.depth + 1;
}
if (value) node.value = 0;
node.children = childs;
} else {
if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
delete node.children;
}
}
d3_layout_hierarchyVisitAfter(root, function(node) {
var childs, parent;
if (sort && (childs = node.children)) childs.sort(sort);
if (value && (parent = node.parent)) parent.value += node.value;
});
return nodes;
}
hierarchy.sort = function(x) {
if (!arguments.length) return sort;
sort = x;
return hierarchy;
};
hierarchy.children = function(x) {
if (!arguments.length) return children;
children = x;
return hierarchy;
};
hierarchy.value = function(x) {
if (!arguments.length) return value;
value = x;
return hierarchy;
};
hierarchy.revalue = function(root) {
if (value) {
d3_layout_hierarchyVisitBefore(root, function(node) {
if (node.children) node.value = 0;
});
d3_layout_hierarchyVisitAfter(root, function(node) {
var parent;
if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
if (parent = node.parent) parent.value += node.value;
});
}
return root;
};
return hierarchy;
};
function d3_layout_hierarchyRebind(object, hierarchy) {
d3.rebind(object, hierarchy, "sort", "children", "value");
object.nodes = object;
object.links = d3_layout_hierarchyLinks;
return object;
}
function d3_layout_hierarchyVisitBefore(node, callback) {
var nodes = [ node ];
while ((node = nodes.pop()) != null) {
callback(node);
if ((children = node.children) && (n = children.length)) {
var n, children;
while (--n >= 0) nodes.push(children[n]);
}
}
}
function d3_layout_hierarchyVisitAfter(node, callback) {
var nodes = [ node ], nodes2 = [];
while ((node = nodes.pop()) != null) {
nodes2.push(node);
if ((children = node.children) && (n = children.length)) {
var i = -1, n, children;
while (++i < n) nodes.push(children[i]);
}
}
while ((node = nodes2.pop()) != null) {
callback(node);
}
}
function d3_layout_hierarchyChildren(d) {
return d.children;
}
function d3_layout_hierarchyValue(d) {
return d.value;
}
function d3_layout_hierarchySort(a, b) {
return b.value - a.value;
}
function d3_layout_hierarchyLinks(nodes) {
return d3.merge(nodes.map(function(parent) {
return (parent.children || []).map(function(child) {
return {
source: parent,
target: child
};
});
}));
}
d3.layout.partition = function() {
var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
function position(node, x, dx, dy) {
var children = node.children;
node.x = x;
node.y = node.depth * dy;
node.dx = dx;
node.dy = dy;
if (children && (n = children.length)) {
var i = -1, n, c, d;
dx = node.value ? dx / node.value : 0;
while (++i < n) {
position(c = children[i], x, d = c.value * dx, dy);
x += d;
}
}
}
function depth(node) {
var children = node.children, d = 0;
if (children && (n = children.length)) {
var i = -1, n;
while (++i < n) d = Math.max(d, depth(children[i]));
}
return 1 + d;
}
function partition(d, i) {
var nodes = hierarchy.call(this, d, i);
position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
return nodes;
}
partition.size = function(x) {
if (!arguments.length) return size;
size = x;
return partition;
};
return d3_layout_hierarchyRebind(partition, hierarchy);
};
d3.layout.pie = function() {
var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0;
function pie(data) {
var n = data.length, values = data.map(function(d, i) {
return +value.call(pie, d, i);
}), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
return values[j] - values[i];
} : function(i, j) {
return sort(data[i], data[j]);
});
index.forEach(function(i) {
arcs[i] = {
data: data[i],
value: v = values[i],
startAngle: a,
endAngle: a += v * k + pa,
padAngle: p
};
});
return arcs;
}
pie.value = function(_) {
if (!arguments.length) return value;
value = _;
return pie;
};
pie.sort = function(_) {
if (!arguments.length) return sort;
sort = _;
return pie;
};
pie.startAngle = function(_) {
if (!arguments.length) return startAngle;
startAngle = _;
return pie;
};
pie.endAngle = function(_) {
if (!arguments.length) return endAngle;
endAngle = _;
return pie;
};
pie.padAngle = function(_) {
if (!arguments.length) return padAngle;
padAngle = _;
return pie;
};
return pie;
};
var d3_layout_pieSortByValue = {};
d3.layout.stack = function() {
var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
function stack(data, index) {
if (!(n = data.length)) return data;
var series = data.map(function(d, i) {
return values.call(stack, d, i);
});
var points = series.map(function(d) {
return d.map(function(v, i) {
return [ x.call(stack, v, i), y.call(stack, v, i) ];
});
});
var orders = order.call(stack, points, index);
series = d3.permute(series, orders);
points = d3.permute(points, orders);
var offsets = offset.call(stack, points, index);
var m = series[0].length, n, i, j, o;
for (j = 0; j < m; ++j) {
out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
for (i = 1; i < n; ++i) {
out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
}
}
return data;
}
stack.values = function(x) {
if (!arguments.length) return values;
values = x;
return stack;
};
stack.order = function(x) {
if (!arguments.length) return order;
order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
return stack;
};
stack.offset = function(x) {
if (!arguments.length) return offset;
offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
return stack;
};
stack.x = function(z) {
if (!arguments.length) return x;
x = z;
return stack;
};
stack.y = function(z) {
if (!arguments.length) return y;
y = z;
return stack;
};
stack.out = function(z) {
if (!arguments.length) return out;
out = z;
return stack;
};
return stack;
};
function d3_layout_stackX(d) {
return d.x;
}
function d3_layout_stackY(d) {
return d.y;
}
function d3_layout_stackOut(d, y0, y) {
d.y0 = y0;
d.y = y;
}
var d3_layout_stackOrders = d3.map({
"inside-out": function(data) {
var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
return max[a] - max[b];
}), top = 0, bottom = 0, tops = [], bottoms = [];
for (i = 0; i < n; ++i) {
j = index[i];
if (top < bottom) {
top += sums[j];
tops.push(j);
} else {
bottom += sums[j];
bottoms.push(j);
}
}
return bottoms.reverse().concat(tops);
},
reverse: function(data) {
return d3.range(data.length).reverse();
},
"default": d3_layout_stackOrderDefault
});
var d3_layout_stackOffsets = d3.map({
silhouette: function(data) {
var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
for (j = 0; j < m; ++j) {
for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
if (o > max) max = o;
sums.push(o);
}
for (j = 0; j < m; ++j) {
y0[j] = (max - sums[j]) / 2;
}
return y0;
},
wiggle: function(data) {
var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
y0[0] = o = o0 = 0;
for (j = 1; j < m; ++j) {
for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
}
s2 += s3 * data[i][j][1];
}
y0[j] = o -= s1 ? s2 / s1 * dx : 0;
if (o < o0) o0 = o;
}
for (j = 0; j < m; ++j) y0[j] -= o0;
return y0;
},
expand: function(data) {
var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
for (j = 0; j < m; ++j) {
for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
}
for (j = 0; j < m; ++j) y0[j] = 0;
return y0;
},
zero: d3_layout_stackOffsetZero
});
function d3_layout_stackOrderDefault(data) {
return d3.range(data.length);
}
function d3_layout_stackOffsetZero(data) {
var j = -1, m = data[0].length, y0 = [];
while (++j < m) y0[j] = 0;
return y0;
}
function d3_layout_stackMaxIndex(array) {
var i = 1, j = 0, v = array[0][1], k, n = array.length;
for (;i < n; ++i) {
if ((k = array[i][1]) > v) {
j = i;
v = k;
}
}
return j;
}
function d3_layout_stackReduceSum(d) {
return d.reduce(d3_layout_stackSum, 0);
}
function d3_layout_stackSum(p, d) {
return p + d[1];
}
d3.layout.histogram = function() {
var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
function histogram(data, i) {
var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
while (++i < m) {
bin = bins[i] = [];
bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
bin.y = 0;
}
if (m > 0) {
i = -1;
while (++i < n) {
x = values[i];
if (x >= range[0] && x <= range[1]) {
bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
bin.y += k;
bin.push(data[i]);
}
}
}
return bins;
}
histogram.value = function(x) {
if (!arguments.length) return valuer;
valuer = x;
return histogram;
};
histogram.range = function(x) {
if (!arguments.length) return ranger;
ranger = d3_functor(x);
return histogram;
};
histogram.bins = function(x) {
if (!arguments.length) return binner;
binner = typeof x === "number" ? function(range) {
return d3_layout_histogramBinFixed(range, x);
} : d3_functor(x);
return histogram;
};
histogram.frequency = function(x) {
if (!arguments.length) return frequency;
frequency = !!x;
return histogram;
};
return histogram;
};
function d3_layout_histogramBinSturges(range, values) {
return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
}
function d3_layout_histogramBinFixed(range, n) {
var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
while (++x <= n) f[x] = m * x + b;
return f;
}
function d3_layout_histogramRange(values) {
return [ d3.min(values), d3.max(values) ];
}
d3.layout.pack = function() {
var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
function pack(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
return radius;
};
root.x = root.y = 0;
d3_layout_hierarchyVisitAfter(root, function(d) {
d.r = +r(d.value);
});
d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
if (padding) {
var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
d3_layout_hierarchyVisitAfter(root, function(d) {
d.r += dr;
});
d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
d3_layout_hierarchyVisitAfter(root, function(d) {
d.r -= dr;
});
}
d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
return nodes;
}
pack.size = function(_) {
if (!arguments.length) return size;
size = _;
return pack;
};
pack.radius = function(_) {
if (!arguments.length) return radius;
radius = _ == null || typeof _ === "function" ? _ : +_;
return pack;
};
pack.padding = function(_) {
if (!arguments.length) return padding;
padding = +_;
return pack;
};
return d3_layout_hierarchyRebind(pack, hierarchy);
};
function d3_layout_packSort(a, b) {
return a.value - b.value;
}
function d3_layout_packInsert(a, b) {
var c = a._pack_next;
a._pack_next = b;
b._pack_prev = a;
b._pack_next = c;
c._pack_prev = b;
}
function d3_layout_packSplice(a, b) {
a._pack_next = b;
b._pack_prev = a;
}
function d3_layout_packIntersects(a, b) {
var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
return .999 * dr * dr > dx * dx + dy * dy;
}
function d3_layout_packSiblings(node) {
if (!(nodes = node.children) || !(n = nodes.length)) return;
var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
function bound(node) {
xMin = Math.min(node.x - node.r, xMin);
xMax = Math.max(node.x + node.r, xMax);
yMin = Math.min(node.y - node.r, yMin);
yMax = Math.max(node.y + node.r, yMax);
}
nodes.forEach(d3_layout_packLink);
a = nodes[0];
a.x = -a.r;
a.y = 0;
bound(a);
if (n > 1) {
b = nodes[1];
b.x = b.r;
b.y = 0;
bound(b);
if (n > 2) {
c = nodes[2];
d3_layout_packPlace(a, b, c);
bound(c);
d3_layout_packInsert(a, c);
a._pack_prev = c;
d3_layout_packInsert(c, b);
b = a._pack_next;
for (i = 3; i < n; i++) {
d3_layout_packPlace(a, b, c = nodes[i]);
var isect = 0, s1 = 1, s2 = 1;
for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
if (d3_layout_packIntersects(j, c)) {
isect = 1;
break;
}
}
if (isect == 1) {
for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
if (d3_layout_packIntersects(k, c)) {
break;
}
}
}
if (isect) {
if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
i--;
} else {
d3_layout_packInsert(a, c);
b = c;
bound(c);
}
}
}
}
var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
for (i = 0; i < n; i++) {
c = nodes[i];
c.x -= cx;
c.y -= cy;
cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
}
node.r = cr;
nodes.forEach(d3_layout_packUnlink);
}
function d3_layout_packLink(node) {
node._pack_next = node._pack_prev = node;
}
function d3_layout_packUnlink(node) {
delete node._pack_next;
delete node._pack_prev;
}
function d3_layout_packTransform(node, x, y, k) {
var children = node.children;
node.x = x += k * node.x;
node.y = y += k * node.y;
node.r *= k;
if (children) {
var i = -1, n = children.length;
while (++i < n) d3_layout_packTransform(children[i], x, y, k);
}
}
function d3_layout_packPlace(a, b, c) {
var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
if (db && (dx || dy)) {
var da = b.r + c.r, dc = dx * dx + dy * dy;
da *= da;
db *= db;
var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
c.x = a.x + x * dx + y * dy;
c.y = a.y + x * dy - y * dx;
} else {
c.x = a.x + db;
c.y = a.y;
}
}
d3.layout.tree = function() {
var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null;
function tree(d, i) {
var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
d3_layout_hierarchyVisitBefore(root1, secondWalk);
if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else {
var left = root0, right = root0, bottom = root0;
d3_layout_hierarchyVisitBefore(root0, function(node) {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
if (node.depth > bottom.depth) bottom = node;
});
var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
d3_layout_hierarchyVisitBefore(root0, function(node) {
node.x = (node.x + tx) * kx;
node.y = node.depth * ky;
});
}
return nodes;
}
function wrapTree(root0) {
var root1 = {
A: null,
children: [ root0 ]
}, queue = [ root1 ], node1;
while ((node1 = queue.pop()) != null) {
for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
queue.push((children[i] = child = {
_: children[i],
parent: node1,
children: (child = children[i].children) && child.slice() || [],
A: null,
a: null,
z: 0,
m: 0,
c: 0,
s: 0,
t: null,
i: i
}).a = child);
}
}
return root1.children[0];
}
function firstWalk(v) {
var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
if (children.length) {
d3_layout_treeShift(v);
var midpoint = (children[0].z + children[children.length - 1].z) / 2;
if (w) {
v.z = w.z + separation(v._, w._);
v.m = v.z - midpoint;
} else {
v.z = midpoint;
}
} else if (w) {
v.z = w.z + separation(v._, w._);
}
v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
}
function secondWalk(v) {
v._.x = v.z + v.parent.m;
v.m += v.parent.m;
}
function apportion(v, w, ancestor) {
if (w) {
var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
vom = d3_layout_treeLeft(vom);
vop = d3_layout_treeRight(vop);
vop.a = v;
shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
if (shift > 0) {
d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
sip += shift;
sop += shift;
}
sim += vim.m;
sip += vip.m;
som += vom.m;
sop += vop.m;
}
if (vim && !d3_layout_treeRight(vop)) {
vop.t = vim;
vop.m += sim - sop;
}
if (vip && !d3_layout_treeLeft(vom)) {
vom.t = vip;
vom.m += sip - som;
ancestor = v;
}
}
return ancestor;
}
function sizeNode(node) {
node.x *= size[0];
node.y = node.depth * size[1];
}
tree.separation = function(x) {
if (!arguments.length) return separation;
separation = x;
return tree;
};
tree.size = function(x) {
if (!arguments.length) return nodeSize ? null : size;
nodeSize = (size = x) == null ? sizeNode : null;
return tree;
};
tree.nodeSize = function(x) {
if (!arguments.length) return nodeSize ? size : null;
nodeSize = (size = x) == null ? null : sizeNode;
return tree;
};
return d3_layout_hierarchyRebind(tree, hierarchy);
};
function d3_layout_treeSeparation(a, b) {
return a.parent == b.parent ? 1 : 2;
}
function d3_layout_treeLeft(v) {
var children = v.children;
return children.length ? children[0] : v.t;
}
function d3_layout_treeRight(v) {
var children = v.children, n;
return (n = children.length) ? children[n - 1] : v.t;
}
function d3_layout_treeMove(wm, wp, shift) {
var change = shift / (wp.i - wm.i);
wp.c -= change;
wp.s += shift;
wm.c += change;
wp.z += shift;
wp.m += shift;
}
function d3_layout_treeShift(v) {
var shift = 0, change = 0, children = v.children, i = children.length, w;
while (--i >= 0) {
w = children[i];
w.z += shift;
w.m += shift;
shift += w.s + (change += w.c);
}
}
function d3_layout_treeAncestor(vim, v, ancestor) {
return vim.a.parent === v.parent ? vim.a : ancestor;
}
d3.layout.cluster = function() {
var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
function cluster(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
d3_layout_hierarchyVisitAfter(root, function(node) {
var children = node.children;
if (children && children.length) {
node.x = d3_layout_clusterX(children);
node.y = d3_layout_clusterY(children);
} else {
node.x = previousNode ? x += separation(node, previousNode) : 0;
node.y = 0;
previousNode = node;
}
});
var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
node.x = (node.x - root.x) * size[0];
node.y = (root.y - node.y) * size[1];
} : function(node) {
node.x = (node.x - x0) / (x1 - x0) * size[0];
node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
});
return nodes;
}
cluster.separation = function(x) {
if (!arguments.length) return separation;
separation = x;
return cluster;
};
cluster.size = function(x) {
if (!arguments.length) return nodeSize ? null : size;
nodeSize = (size = x) == null;
return cluster;
};
cluster.nodeSize = function(x) {
if (!arguments.length) return nodeSize ? size : null;
nodeSize = (size = x) != null;
return cluster;
};
return d3_layout_hierarchyRebind(cluster, hierarchy);
};
function d3_layout_clusterY(children) {
return 1 + d3.max(children, function(child) {
return child.y;
});
}
function d3_layout_clusterX(children) {
return children.reduce(function(x, child) {
return x + child.x;
}, 0) / children.length;
}
function d3_layout_clusterLeft(node) {
var children = node.children;
return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
}
function d3_layout_clusterRight(node) {
var children = node.children, n;
return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
}
d3.layout.treemap = function() {
var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
function scale(children, k) {
var i = -1, n = children.length, child, area;
while (++i < n) {
area = (child = children[i]).value * (k < 0 ? 0 : k);
child.area = isNaN(area) || area <= 0 ? 0 : area;
}
}
function squarify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while ((n = remaining.length) > 0) {
row.push(child = remaining[n - 1]);
row.area += child.area;
if (mode !== "squarify" || (score = worst(row, u)) <= best) {
remaining.pop();
best = score;
} else {
row.area -= row.pop().area;
position(row, u, rect, false);
u = Math.min(rect.dx, rect.dy);
row.length = row.area = 0;
best = Infinity;
}
}
if (row.length) {
position(row, u, rect, true);
row.length = row.area = 0;
}
children.forEach(squarify);
}
}
function stickify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node), remaining = children.slice(), child, row = [];
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while (child = remaining.pop()) {
row.push(child);
row.area += child.area;
if (child.z != null) {
position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
row.length = row.area = 0;
}
}
children.forEach(stickify);
}
}
function worst(row, u) {
var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
while (++i < n) {
if (!(r = row[i].area)) continue;
if (r < rmin) rmin = r;
if (r > rmax) rmax = r;
}
s *= s;
u *= u;
return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
}
function position(row, u, rect, flush) {
var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
if (u == rect.dx) {
if (flush || v > rect.dy) v = rect.dy;
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dy = v;
x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
}
o.z = true;
o.dx += rect.x + rect.dx - x;
rect.y += v;
rect.dy -= v;
} else {
if (flush || v > rect.dx) v = rect.dx;
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dx = v;
y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
}
o.z = false;
o.dy += rect.y + rect.dy - y;
rect.x += v;
rect.dx -= v;
}
}
function treemap(d) {
var nodes = stickies || hierarchy(d), root = nodes[0];
root.x = root.y = 0;
if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0;
if (stickies) hierarchy.revalue(root);
scale([ root ], root.dx * root.dy / root.value);
(stickies ? stickify : squarify)(root);
if (sticky) stickies = nodes;
return nodes;
}
treemap.size = function(x) {
if (!arguments.length) return size;
size = x;
return treemap;
};
treemap.padding = function(x) {
if (!arguments.length) return padding;
function padFunction(node) {
var p = x.call(treemap, node, node.depth);
return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
}
function padConstant(node) {
return d3_layout_treemapPad(node, x);
}
var type;
pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ],
padConstant) : padConstant;
return treemap;
};
treemap.round = function(x) {
if (!arguments.length) return round != Number;
round = x ? Math.round : Number;
return treemap;
};
treemap.sticky = function(x) {
if (!arguments.length) return sticky;
sticky = x;
stickies = null;
return treemap;
};
treemap.ratio = function(x) {
if (!arguments.length) return ratio;
ratio = x;
return treemap;
};
treemap.mode = function(x) {
if (!arguments.length) return mode;
mode = x + "";
return treemap;
};
return d3_layout_hierarchyRebind(treemap, hierarchy);
};
function d3_layout_treemapPadNull(node) {
return {
x: node.x,
y: node.y,
dx: node.dx,
dy: node.dy
};
}
function d3_layout_treemapPad(node, padding) {
var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
if (dx < 0) {
x += dx / 2;
dx = 0;
}
if (dy < 0) {
y += dy / 2;
dy = 0;
}
return {
x: x,
y: y,
dx: dx,
dy: dy
};
}
d3.random = {
normal: function(µ, σ) {
var n = arguments.length;
if (n < 2) σ = 1;
if (n < 1) µ = 0;
return function() {
var x, y, r;
do {
x = Math.random() * 2 - 1;
y = Math.random() * 2 - 1;
r = x * x + y * y;
} while (!r || r > 1);
return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r);
};
},
logNormal: function() {
var random = d3.random.normal.apply(d3, arguments);
return function() {
return Math.exp(random());
};
},
bates: function(m) {
var random = d3.random.irwinHall(m);
return function() {
return random() / m;
};
},
irwinHall: function(m) {
return function() {
for (var s = 0, j = 0; j < m; j++) s += Math.random();
return s;
};
}
};
d3.scale = {};
function d3_scaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
}
function d3_scaleRange(scale) {
return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
}
function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
return function(x) {
return i(u(x));
};
}
function d3_scale_nice(domain, nice) {
var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
if (x1 < x0) {
dx = i0, i0 = i1, i1 = dx;
dx = x0, x0 = x1, x1 = dx;
}
domain[i0] = nice.floor(x0);
domain[i1] = nice.ceil(x1);
return domain;
}
function d3_scale_niceStep(step) {
return step ? {
floor: function(x) {
return Math.floor(x / step) * step;
},
ceil: function(x) {
return Math.ceil(x / step) * step;
}
} : d3_scale_niceIdentity;
}
var d3_scale_niceIdentity = {
floor: d3_identity,
ceil: d3_identity
};
function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
if (domain[k] < domain[0]) {
domain = domain.slice().reverse();
range = range.slice().reverse();
}
while (++j <= k) {
u.push(uninterpolate(domain[j - 1], domain[j]));
i.push(interpolate(range[j - 1], range[j]));
}
return function(x) {
var j = d3.bisect(domain, x, 1, k) - 1;
return i[j](u[j](x));
};
}
d3.scale.linear = function() {
return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
};
function d3_scale_linear(domain, range, interpolate, clamp) {
var output, input;
function rescale() {
var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
output = linear(domain, range, uninterpolate, interpolate);
input = linear(range, domain, uninterpolate, d3_interpolate);
return scale;
}
function scale(x) {
return output(x);
}
scale.invert = function(y) {
return input(y);
};
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.map(Number);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.rangeRound = function(x) {
return scale.range(x).interpolate(d3_interpolateRound);
};
scale.clamp = function(x) {
if (!arguments.length) return clamp;
clamp = x;
return rescale();
};
scale.interpolate = function(x) {
if (!arguments.length) return interpolate;
interpolate = x;
return rescale();
};
scale.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
scale.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
scale.nice = function(m) {
d3_scale_linearNice(domain, m);
return rescale();
};
scale.copy = function() {
return d3_scale_linear(domain, range, interpolate, clamp);
};
return rescale();
}
function d3_scale_linearRebind(scale, linear) {
return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
}
function d3_scale_linearNice(domain, m) {
d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
return domain;
}
function d3_scale_linearTickRange(domain, m) {
if (m == null) m = 10;
var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
extent[0] = Math.ceil(extent[0] / step) * step;
extent[1] = Math.floor(extent[1] / step) * step + step * .5;
extent[2] = step;
return extent;
}
function d3_scale_linearTicks(domain, m) {
return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
}
function d3_scale_linearTickFormat(domain, m, format) {
var range = d3_scale_linearTickRange(domain, m);
if (format) {
var match = d3_format_re.exec(format);
match.shift();
if (match[8] === "s") {
var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1])));
if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2]));
match[8] = "f";
format = d3.format(match.join(""));
return function(d) {
return format(prefix.scale(d)) + prefix.symbol;
};
}
if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range);
format = match.join("");
} else {
format = ",." + d3_scale_linearPrecision(range[2]) + "f";
}
return d3.format(format);
}
var d3_scale_linearFormatSignificant = {
s: 1,
g: 1,
p: 1,
r: 1,
e: 1
};
function d3_scale_linearPrecision(value) {
return -Math.floor(Math.log(value) / Math.LN10 + .01);
}
function d3_scale_linearFormatPrecision(type, range) {
var p = d3_scale_linearPrecision(range[2]);
return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
}
d3.scale.log = function() {
return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
};
function d3_scale_log(linear, base, positive, domain) {
function log(x) {
return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
}
function pow(x) {
return positive ? Math.pow(base, x) : -Math.pow(base, -x);
}
function scale(x) {
return linear(log(x));
}
scale.invert = function(x) {
return pow(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return domain;
positive = x[0] >= 0;
linear.domain((domain = x.map(Number)).map(log));
return scale;
};
scale.base = function(_) {
if (!arguments.length) return base;
base = +_;
linear.domain(domain.map(log));
return scale;
};
scale.nice = function() {
var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
linear.domain(niced);
domain = niced.map(pow);
return scale;
};
scale.ticks = function() {
var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
if (isFinite(j - i)) {
if (positive) {
for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
ticks.push(pow(i));
} else {
ticks.push(pow(i));
for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
}
for (i = 0; ticks[i] < u; i++) {}
for (j = ticks.length; ticks[j - 1] > v; j--) {}
ticks = ticks.slice(i, j);
}
return ticks;
};
scale.tickFormat = function(n, format) {
if (!arguments.length) return d3_scale_logFormat;
if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format);
var k = Math.max(1, base * n / scale.ticks().length);
return function(d) {
var i = d / pow(Math.round(log(d)));
if (i * base < base - .5) i *= base;
return i <= k ? format(d) : "";
};
};
scale.copy = function() {
return d3_scale_log(linear.copy(), base, positive, domain);
};
return d3_scale_linearRebind(scale, linear);
}
var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = {
floor: function(x) {
return -Math.ceil(-x);
},
ceil: function(x) {
return -Math.floor(-x);
}
};
d3.scale.pow = function() {
return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
};
function d3_scale_pow(linear, exponent, domain) {
var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
function scale(x) {
return linear(powp(x));
}
scale.invert = function(x) {
return powb(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return domain;
linear.domain((domain = x.map(Number)).map(powp));
return scale;
};
scale.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
scale.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
scale.nice = function(m) {
return scale.domain(d3_scale_linearNice(domain, m));
};
scale.exponent = function(x) {
if (!arguments.length) return exponent;
powp = d3_scale_powPow(exponent = x);
powb = d3_scale_powPow(1 / exponent);
linear.domain(domain.map(powp));
return scale;
};
scale.copy = function() {
return d3_scale_pow(linear.copy(), exponent, domain);
};
return d3_scale_linearRebind(scale, linear);
}
function d3_scale_powPow(e) {
return function(x) {
return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
};
}
d3.scale.sqrt = function() {
return d3.scale.pow().exponent(.5);
};
d3.scale.ordinal = function() {
return d3_scale_ordinal([], {
t: "range",
a: [ [] ]
});
};
function d3_scale_ordinal(domain, ranger) {
var index, range, rangeBand;
function scale(x) {
return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
}
function steps(start, step) {
return d3.range(domain.length).map(function(i) {
return start + step * i;
});
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = [];
index = new d3_Map();
var i = -1, n = x.length, xi;
while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
return scale[ranger.t].apply(scale, ranger.a);
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
rangeBand = 0;
ranger = {
t: "range",
a: arguments
};
return scale;
};
scale.rangePoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2,
0) : (stop - start) / (domain.length - 1 + padding);
range = steps(start + step * padding / 2, step);
rangeBand = 0;
ranger = {
t: "rangePoints",
a: arguments
};
return scale;
};
scale.rangeRoundPoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2),
0) : (stop - start) / (domain.length - 1 + padding) | 0;
range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
rangeBand = 0;
ranger = {
t: "rangeRoundPoints",
a: arguments
};
return scale;
};
scale.rangeBands = function(x, padding, outerPadding) {
if (arguments.length < 2) padding = 0;
if (arguments.length < 3) outerPadding = padding;
var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
range = steps(start + step * outerPadding, step);
if (reverse) range.reverse();
rangeBand = step * (1 - padding);
ranger = {
t: "rangeBands",
a: arguments
};
return scale;
};
scale.rangeRoundBands = function(x, padding, outerPadding) {
if (arguments.length < 2) padding = 0;
if (arguments.length < 3) outerPadding = padding;
var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
if (reverse) range.reverse();
rangeBand = Math.round(step * (1 - padding));
ranger = {
t: "rangeRoundBands",
a: arguments
};
return scale;
};
scale.rangeBand = function() {
return rangeBand;
};
scale.rangeExtent = function() {
return d3_scaleExtent(ranger.a[0]);
};
scale.copy = function() {
return d3_scale_ordinal(domain, ranger);
};
return scale.domain(domain);
}
d3.scale.category10 = function() {
return d3.scale.ordinal().range(d3_category10);
};
d3.scale.category20 = function() {
return d3.scale.ordinal().range(d3_category20);
};
d3.scale.category20b = function() {
return d3.scale.ordinal().range(d3_category20b);
};
d3.scale.category20c = function() {
return d3.scale.ordinal().range(d3_category20c);
};
var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
d3.scale.quantile = function() {
return d3_scale_quantile([], []);
};
function d3_scale_quantile(domain, range) {
var thresholds;
function rescale() {
var k = 0, q = range.length;
thresholds = [];
while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
return scale;
}
function scale(x) {
if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.quantiles = function() {
return thresholds;
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
};
scale.copy = function() {
return d3_scale_quantile(domain, range);
};
return rescale();
}
d3.scale.quantize = function() {
return d3_scale_quantize(0, 1, [ 0, 1 ]);
};
function d3_scale_quantize(x0, x1, range) {
var kx, i;
function scale(x) {
return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
}
function rescale() {
kx = range.length / (x1 - x0);
i = range.length - 1;
return scale;
}
scale.domain = function(x) {
if (!arguments.length) return [ x0, x1 ];
x0 = +x[0];
x1 = +x[x.length - 1];
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
y = y < 0 ? NaN : y / kx + x0;
return [ y, y + 1 / kx ];
};
scale.copy = function() {
return d3_scale_quantize(x0, x1, range);
};
return rescale();
}
d3.scale.threshold = function() {
return d3_scale_threshold([ .5 ], [ 0, 1 ]);
};
function d3_scale_threshold(domain, range) {
function scale(x) {
if (x <= x) return range[d3.bisect(domain, x)];
}
scale.domain = function(_) {
if (!arguments.length) return domain;
domain = _;
return scale;
};
scale.range = function(_) {
if (!arguments.length) return range;
range = _;
return scale;
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
return [ domain[y - 1], domain[y] ];
};
scale.copy = function() {
return d3_scale_threshold(domain, range);
};
return scale;
}
d3.scale.identity = function() {
return d3_scale_identity([ 0, 1 ]);
};
function d3_scale_identity(domain) {
function identity(x) {
return +x;
}
identity.invert = identity;
identity.domain = identity.range = function(x) {
if (!arguments.length) return domain;
domain = x.map(identity);
return identity;
};
identity.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
identity.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
identity.copy = function() {
return d3_scale_identity(domain);
};
return identity;
}
d3.svg = {};
function d3_zero() {
return 0;
}
d3.svg.arc = function() {
var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
function arc() {
var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
if (!cw) p1 *= -1;
if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
}
if (r1) {
x0 = r1 * Math.cos(a0 + p1);
y0 = r1 * Math.sin(a0 + p1);
x1 = r1 * Math.cos(a1 - p1);
y1 = r1 * Math.sin(a1 - p1);
var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1;
if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
var h1 = (a0 + a1) / 2;
x0 = r1 * Math.cos(h1);
y0 = r1 * Math.sin(h1);
x1 = y1 = null;
}
} else {
x0 = y0 = 0;
}
if (r0) {
x2 = r0 * Math.cos(a1 - p0);
y2 = r0 * Math.sin(a1 - p0);
x3 = r0 * Math.cos(a0 + p0);
y3 = r0 * Math.sin(a0 + p0);
var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1;
if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
var h0 = (a0 + a1) / 2;
x2 = r0 * Math.cos(h0);
y2 = r0 * Math.sin(h0);
x3 = y3 = null;
}
} else {
x2 = y2 = 0;
}
if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) {
cr = r0 < r1 ^ cw ? 0 : 1;
var rc1 = rc, rc0 = rc;
if (da < π) {
var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
}
if (x1 != null) {
var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw);
if (rc === rc1) {
path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
} else {
path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
}
} else {
path.push("M", x0, ",", y0);
}
if (x3 != null) {
var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw);
if (rc === rc0) {
path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
} else {
path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
}
} else {
path.push("L", x2, ",", y2);
}
} else {
path.push("M", x0, ",", y0);
if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
path.push("L", x2, ",", y2);
if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
}
path.push("Z");
return path.join("");
}
function circleSegment(r1, cw) {
return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
}
arc.innerRadius = function(v) {
if (!arguments.length) return innerRadius;
innerRadius = d3_functor(v);
return arc;
};
arc.outerRadius = function(v) {
if (!arguments.length) return outerRadius;
outerRadius = d3_functor(v);
return arc;
};
arc.cornerRadius = function(v) {
if (!arguments.length) return cornerRadius;
cornerRadius = d3_functor(v);
return arc;
};
arc.padRadius = function(v) {
if (!arguments.length) return padRadius;
padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
return arc;
};
arc.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return arc;
};
arc.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return arc;
};
arc.padAngle = function(v) {
if (!arguments.length) return padAngle;
padAngle = d3_functor(v);
return arc;
};
arc.centroid = function() {
var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ;
return [ Math.cos(a) * r, Math.sin(a) * r ];
};
return arc;
};
var d3_svg_arcAuto = "auto";
function d3_svg_arcInnerRadius(d) {
return d.innerRadius;
}
function d3_svg_arcOuterRadius(d) {
return d.outerRadius;
}
function d3_svg_arcStartAngle(d) {
return d.startAngle;
}
function d3_svg_arcEndAngle(d) {
return d.endAngle;
}
function d3_svg_arcPadAngle(d) {
return d && d.padAngle;
}
function d3_svg_arcSweep(x0, y0, x1, y1) {
return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
}
function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ];
}
function d3_svg_line(projection) {
var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
function line(data) {
var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
function segment() {
segments.push("M", interpolate(projection(points), tension));
}
while (++i < n) {
if (defined.call(this, d = data[i], i)) {
points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
} else if (points.length) {
segment();
points = [];
}
}
if (points.length) segment();
return segments.length ? segments.join("") : null;
}
line.x = function(_) {
if (!arguments.length) return x;
x = _;
return line;
};
line.y = function(_) {
if (!arguments.length) return y;
y = _;
return line;
};
line.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return line;
};
line.interpolate = function(_) {
if (!arguments.length) return interpolateKey;
if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
return line;
};
line.tension = function(_) {
if (!arguments.length) return tension;
tension = _;
return line;
};
return line;
}
d3.svg.line = function() {
return d3_svg_line(d3_identity);
};
var d3_svg_lineInterpolators = d3.map({
linear: d3_svg_lineLinear,
"linear-closed": d3_svg_lineLinearClosed,
step: d3_svg_lineStep,
"step-before": d3_svg_lineStepBefore,
"step-after": d3_svg_lineStepAfter,
basis: d3_svg_lineBasis,
"basis-open": d3_svg_lineBasisOpen,
"basis-closed": d3_svg_lineBasisClosed,
bundle: d3_svg_lineBundle,
cardinal: d3_svg_lineCardinal,
"cardinal-open": d3_svg_lineCardinalOpen,
"cardinal-closed": d3_svg_lineCardinalClosed,
monotone: d3_svg_lineMonotone
});
d3_svg_lineInterpolators.forEach(function(key, value) {
value.key = key;
value.closed = /-closed$/.test(key);
});
function d3_svg_lineLinear(points) {
return points.length > 1 ? points.join("L") : points + "Z";
}
function d3_svg_lineLinearClosed(points) {
return points.join("L") + "Z";
}
function d3_svg_lineStep(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
if (n > 1) path.push("H", p[0]);
return path.join("");
}
function d3_svg_lineStepBefore(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
return path.join("");
}
function d3_svg_lineStepAfter(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
return path.join("");
}
function d3_svg_lineCardinalOpen(points, tension) {
return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
}
function d3_svg_lineCardinalClosed(points, tension) {
return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]),
points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
}
function d3_svg_lineCardinal(points, tension) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
}
function d3_svg_lineHermite(points, tangents) {
if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
return d3_svg_lineLinear(points);
}
var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
if (quad) {
path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
}
}
if (quad) {
var lp = points[pi];
path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
}
return path;
}
function d3_svg_lineCardinalTangents(points, tension) {
var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
while (++i < n) {
p0 = p1;
p1 = p2;
p2 = points[i];
tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
}
return tangents;
}
function d3_svg_lineBasis(points) {
if (points.length < 3) return d3_svg_lineLinear(points);
var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
points.push(points[n - 1]);
while (++i <= n) {
pi = points[i];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
points.pop();
path.push("L", pi);
return path.join("");
}
function d3_svg_lineBasisOpen(points) {
if (points.length < 4) return d3_svg_lineLinear(points);
var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
while (++i < 3) {
pi = points[i];
px.push(pi[0]);
py.push(pi[1]);
}
path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
--i;
while (++i < n) {
pi = points[i];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBasisClosed(points) {
var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
while (++i < 4) {
pi = points[i % n];
px.push(pi[0]);
py.push(pi[1]);
}
path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
--i;
while (++i < m) {
pi = points[i % n];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBundle(points, tension) {
var n = points.length - 1;
if (n) {
var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
while (++i <= n) {
p = points[i];
t = i / n;
p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
}
}
return d3_svg_lineBasis(points);
}
function d3_svg_lineDot4(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
function d3_svg_lineBasisBezier(path, x, y) {
path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
}
function d3_svg_lineSlope(p0, p1) {
return (p1[1] - p0[1]) / (p1[0] - p0[0]);
}
function d3_svg_lineFiniteDifferences(points) {
var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
while (++i < j) {
m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
}
m[i] = d;
return m;
}
function d3_svg_lineMonotoneTangents(points) {
var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
while (++i < j) {
d = d3_svg_lineSlope(points[i], points[i + 1]);
if (abs(d) < ε) {
m[i] = m[i + 1] = 0;
} else {
a = m[i] / d;
b = m[i + 1] / d;
s = a * a + b * b;
if (s > 9) {
s = d * 3 / Math.sqrt(s);
m[i] = s * a;
m[i + 1] = s * b;
}
}
}
i = -1;
while (++i <= j) {
s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
tangents.push([ s || 0, m[i] * s || 0 ]);
}
return tangents;
}
function d3_svg_lineMonotone(points) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
}
d3.svg.line.radial = function() {
var line = d3_svg_line(d3_svg_lineRadial);
line.radius = line.x, delete line.x;
line.angle = line.y, delete line.y;
return line;
};
function d3_svg_lineRadial(points) {
var point, i = -1, n = points.length, r, a;
while (++i < n) {
point = points[i];
r = point[0];
a = point[1] - halfπ;
point[0] = r * Math.cos(a);
point[1] = r * Math.sin(a);
}
return points;
}
function d3_svg_area(projection) {
var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
function area(data) {
var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
return x;
} : d3_functor(x1), fy1 = y0 === y1 ? function() {
return y;
} : d3_functor(y1), x, y;
function segment() {
segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
}
while (++i < n) {
if (defined.call(this, d = data[i], i)) {
points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
} else if (points0.length) {
segment();
points0 = [];
points1 = [];
}
}
if (points0.length) segment();
return segments.length ? segments.join("") : null;
}
area.x = function(_) {
if (!arguments.length) return x1;
x0 = x1 = _;
return area;
};
area.x0 = function(_) {
if (!arguments.length) return x0;
x0 = _;
return area;
};
area.x1 = function(_) {
if (!arguments.length) return x1;
x1 = _;
return area;
};
area.y = function(_) {
if (!arguments.length) return y1;
y0 = y1 = _;
return area;
};
area.y0 = function(_) {
if (!arguments.length) return y0;
y0 = _;
return area;
};
area.y1 = function(_) {
if (!arguments.length) return y1;
y1 = _;
return area;
};
area.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return area;
};
area.interpolate = function(_) {
if (!arguments.length) return interpolateKey;
if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
interpolateReverse = interpolate.reverse || interpolate;
L = interpolate.closed ? "M" : "L";
return area;
};
area.tension = function(_) {
if (!arguments.length) return tension;
tension = _;
return area;
};
return area;
}
d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
d3.svg.area = function() {
return d3_svg_area(d3_identity);
};
d3.svg.area.radial = function() {
var area = d3_svg_area(d3_svg_lineRadial);
area.radius = area.x, delete area.x;
area.innerRadius = area.x0, delete area.x0;
area.outerRadius = area.x1, delete area.x1;
area.angle = area.y, delete area.y;
area.startAngle = area.y0, delete area.y0;
area.endAngle = area.y1, delete area.y1;
return area;
};
d3.svg.chord = function() {
var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
function chord(d, i) {
var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
}
function subgroup(self, f, d, i) {
var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ;
return {
r: r,
a0: a0,
a1: a1,
p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
};
}
function equals(a, b) {
return a.a0 == b.a0 && a.a1 == b.a1;
}
function arc(r, p, a) {
return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p;
}
function curve(r0, p0, r1, p1) {
return "Q 0,0 " + p1;
}
chord.radius = function(v) {
if (!arguments.length) return radius;
radius = d3_functor(v);
return chord;
};
chord.source = function(v) {
if (!arguments.length) return source;
source = d3_functor(v);
return chord;
};
chord.target = function(v) {
if (!arguments.length) return target;
target = d3_functor(v);
return chord;
};
chord.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return chord;
};
chord.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return chord;
};
return chord;
};
function d3_svg_chordRadius(d) {
return d.radius;
}
d3.svg.diagonal = function() {
var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
function diagonal(d, i) {
var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
x: p0.x,
y: m
}, {
x: p3.x,
y: m
}, p3 ];
p = p.map(projection);
return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
}
diagonal.source = function(x) {
if (!arguments.length) return source;
source = d3_functor(x);
return diagonal;
};
diagonal.target = function(x) {
if (!arguments.length) return target;
target = d3_functor(x);
return diagonal;
};
diagonal.projection = function(x) {
if (!arguments.length) return projection;
projection = x;
return diagonal;
};
return diagonal;
};
function d3_svg_diagonalProjection(d) {
return [ d.x, d.y ];
}
d3.svg.diagonal.radial = function() {
var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
diagonal.projection = function(x) {
return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
};
return diagonal;
};
function d3_svg_diagonalRadialProjection(projection) {
return function() {
var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ;
return [ r * Math.cos(a), r * Math.sin(a) ];
};
}
d3.svg.symbol = function() {
var type = d3_svg_symbolType, size = d3_svg_symbolSize;
function symbol(d, i) {
return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
}
symbol.type = function(x) {
if (!arguments.length) return type;
type = d3_functor(x);
return symbol;
};
symbol.size = function(x) {
if (!arguments.length) return size;
size = d3_functor(x);
return symbol;
};
return symbol;
};
function d3_svg_symbolSize() {
return 64;
}
function d3_svg_symbolType() {
return "circle";
}
function d3_svg_symbolCircle(size) {
var r = Math.sqrt(size / π);
return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
}
var d3_svg_symbols = d3.map({
circle: d3_svg_symbolCircle,
cross: function(size) {
var r = Math.sqrt(size / 5) / 2;
return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
},
diamond: function(size) {
var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
},
square: function(size) {
var r = Math.sqrt(size) / 2;
return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
},
"triangle-down": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
},
"triangle-up": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
}
});
d3.svg.symbolTypes = d3_svg_symbols.keys();
var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
d3_selectionPrototype.transition = function(name) {
var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
time: Date.now(),
ease: d3_ease_cubicInOut,
delay: 0,
duration: 250
};
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
subgroup.push(node);
}
}
return d3_transition(subgroups, ns, id);
};
d3_selectionPrototype.interrupt = function(name) {
return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name)));
};
var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
function d3_selection_interruptNS(ns) {
return function() {
var lock, activeId, active;
if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
active.timer.c = null;
active.timer.t = NaN;
if (--lock.count) delete lock[activeId]; else delete this[ns];
lock.active += .5;
active.event && active.event.interrupt.call(this, this.__data__, active.index);
}
};
}
function d3_transition(groups, ns, id) {
d3_subclass(groups, d3_transitionPrototype);
groups.namespace = ns;
groups.id = id;
return groups;
}
var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
d3_transitionPrototype.call = d3_selectionPrototype.call;
d3_transitionPrototype.empty = d3_selectionPrototype.empty;
d3_transitionPrototype.node = d3_selectionPrototype.node;
d3_transitionPrototype.size = d3_selectionPrototype.size;
d3.transition = function(selection, name) {
return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection);
};
d3.transition.prototype = d3_transitionPrototype;
d3_transitionPrototype.select = function(selector) {
var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
if ("__data__" in node) subnode.__data__ = node.__data__;
d3_transitionNode(subnode, i, ns, id, node[ns][id]);
subgroup.push(subnode);
} else {
subgroup.push(null);
}
}
}
return d3_transition(subgroups, ns, id);
};
d3_transitionPrototype.selectAll = function(selector) {
var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
transition = node[ns][id];
subnodes = selector.call(node, node.__data__, i, j);
subgroups.push(subgroup = []);
for (var k = -1, o = subnodes.length; ++k < o; ) {
if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
subgroup.push(subnode);
}
}
}
}
return d3_transition(subgroups, ns, id);
};
d3_transitionPrototype.filter = function(filter) {
var subgroups = [], subgroup, group, node;
if (typeof filter !== "function") filter = d3_selection_filter(filter);
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
subgroup.push(node);
}
}
}
return d3_transition(subgroups, this.namespace, this.id);
};
d3_transitionPrototype.tween = function(name, tween) {
var id = this.id, ns = this.namespace;
if (arguments.length < 2) return this.node()[ns][id].tween.get(name);
return d3_selection_each(this, tween == null ? function(node) {
node[ns][id].tween.remove(name);
} : function(node) {
node[ns][id].tween.set(name, tween);
});
};
function d3_transition_tween(groups, name, value, tween) {
var id = groups.id, ns = groups.namespace;
return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
} : (value = tween(value), function(node) {
node[ns][id].tween.set(name, value);
}));
}
d3_transitionPrototype.attr = function(nameNS, value) {
if (arguments.length < 2) {
for (value in nameNS) this.attr(value, nameNS[value]);
return this;
}
var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
function attrNull() {
this.removeAttribute(name);
}
function attrNullNS() {
this.removeAttributeNS(name.space, name.local);
}
function attrTween(b) {
return b == null ? attrNull : (b += "", function() {
var a = this.getAttribute(name), i;
return a !== b && (i = interpolate(a, b), function(t) {
this.setAttribute(name, i(t));
});
});
}
function attrTweenNS(b) {
return b == null ? attrNullNS : (b += "", function() {
var a = this.getAttributeNS(name.space, name.local), i;
return a !== b && (i = interpolate(a, b), function(t) {
this.setAttributeNS(name.space, name.local, i(t));
});
});
}
return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
};
d3_transitionPrototype.attrTween = function(nameNS, tween) {
var name = d3.ns.qualify(nameNS);
function attrTween(d, i) {
var f = tween.call(this, d, i, this.getAttribute(name));
return f && function(t) {
this.setAttribute(name, f(t));
};
}
function attrTweenNS(d, i) {
var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
return f && function(t) {
this.setAttributeNS(name.space, name.local, f(t));
};
}
return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
};
d3_transitionPrototype.style = function(name, value, priority) {
var n = arguments.length;
if (n < 3) {
if (typeof name !== "string") {
if (n < 2) value = "";
for (priority in name) this.style(priority, name[priority], value);
return this;
}
priority = "";
}
function styleNull() {
this.style.removeProperty(name);
}
function styleString(b) {
return b == null ? styleNull : (b += "", function() {
var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i;
return a !== b && (i = d3_interpolate(a, b), function(t) {
this.style.setProperty(name, i(t), priority);
});
});
}
return d3_transition_tween(this, "style." + name, value, styleString);
};
d3_transitionPrototype.styleTween = function(name, tween, priority) {
if (arguments.length < 3) priority = "";
function styleTween(d, i) {
var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name));
return f && function(t) {
this.style.setProperty(name, f(t), priority);
};
}
return this.tween("style." + name, styleTween);
};
d3_transitionPrototype.text = function(value) {
return d3_transition_tween(this, "text", value, d3_transition_text);
};
function d3_transition_text(b) {
if (b == null) b = "";
return function() {
this.textContent = b;
};
}
d3_transitionPrototype.remove = function() {
var ns = this.namespace;
return this.each("end.transition", function() {
var p;
if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
});
};
d3_transitionPrototype.ease = function(value) {
var id = this.id, ns = this.namespace;
if (arguments.length < 1) return this.node()[ns][id].ease;
if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
return d3_selection_each(this, function(node) {
node[ns][id].ease = value;
});
};
d3_transitionPrototype.delay = function(value) {
var id = this.id, ns = this.namespace;
if (arguments.length < 1) return this.node()[ns][id].delay;
return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
node[ns][id].delay = +value.call(node, node.__data__, i, j);
} : (value = +value, function(node) {
node[ns][id].delay = value;
}));
};
d3_transitionPrototype.duration = function(value) {
var id = this.id, ns = this.namespace;
if (arguments.length < 1) return this.node()[ns][id].duration;
return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
} : (value = Math.max(1, value), function(node) {
node[ns][id].duration = value;
}));
};
d3_transitionPrototype.each = function(type, listener) {
var id = this.id, ns = this.namespace;
if (arguments.length < 2) {
var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
try {
d3_transitionInheritId = id;
d3_selection_each(this, function(node, i, j) {
d3_transitionInherit = node[ns][id];
type.call(node, node.__data__, i, j);
});
} finally {
d3_transitionInherit = inherit;
d3_transitionInheritId = inheritId;
}
} else {
d3_selection_each(this, function(node) {
var transition = node[ns][id];
(transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
});
}
return this;
};
d3_transitionPrototype.transition = function() {
var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
if (node = group[i]) {
transition = node[ns][id0];
d3_transitionNode(node, i, ns, id1, {
time: transition.time,
ease: transition.ease,
delay: transition.delay + transition.duration,
duration: transition.duration
});
}
subgroup.push(node);
}
}
return d3_transition(subgroups, ns, id1);
};
function d3_transitionNamespace(name) {
return name == null ? "__transition__" : "__transition_" + name + "__";
}
function d3_transitionNode(node, i, ns, id, inherit) {
var lock = node[ns] || (node[ns] = {
active: 0,
count: 0
}), transition = lock[id], time, timer, duration, ease, tweens;
function schedule(elapsed) {
var delay = transition.delay;
timer.t = delay + time;
if (delay <= elapsed) return start(elapsed - delay);
timer.c = start;
}
function start(elapsed) {
var activeId = lock.active, active = lock[activeId];
if (active) {
active.timer.c = null;
active.timer.t = NaN;
--lock.count;
delete lock[activeId];
active.event && active.event.interrupt.call(node, node.__data__, active.index);
}
for (var cancelId in lock) {
if (+cancelId < id) {
var cancel = lock[cancelId];
cancel.timer.c = null;
cancel.timer.t = NaN;
--lock.count;
delete lock[cancelId];
}
}
timer.c = tick;
d3_timer(function() {
if (timer.c && tick(elapsed || 1)) {
timer.c = null;
timer.t = NaN;
}
return 1;
}, 0, time);
lock.active = id;
transition.event && transition.event.start.call(node, node.__data__, i);
tweens = [];
transition.tween.forEach(function(key, value) {
if (value = value.call(node, node.__data__, i)) {
tweens.push(value);
}
});
ease = transition.ease;
duration = transition.duration;
}
function tick(elapsed) {
var t = elapsed / duration, e = ease(t), n = tweens.length;
while (n > 0) {
tweens[--n].call(node, e);
}
if (t >= 1) {
transition.event && transition.event.end.call(node, node.__data__, i);
if (--lock.count) delete lock[id]; else delete node[ns];
return 1;
}
}
if (!transition) {
time = inherit.time;
timer = d3_timer(schedule, 0, time);
transition = lock[id] = {
tween: new d3_Map(),
time: time,
timer: timer,
delay: inherit.delay,
duration: inherit.duration,
ease: inherit.ease,
index: i
};
inherit = null;
++lock.count;
}
}
d3.svg.axis = function() {
var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
function axis(g) {
g.each(function() {
var g = d3.select(this);
var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"),
d3.transition(path));
tickEnter.append("line");
tickEnter.append("text");
var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
if (orient === "bottom" || orient === "top") {
tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
} else {
tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
}
lineEnter.attr(y2, sign * innerTickSize);
textEnter.attr(y1, sign * tickSpacing);
lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
if (scale1.rangeBand) {
var x = scale1, dx = x.rangeBand() / 2;
scale0 = scale1 = function(d) {
return x(d) + dx;
};
} else if (scale0.rangeBand) {
scale0 = scale1;
} else {
tickExit.call(tickTransform, scale1, scale0);
}
tickEnter.call(tickTransform, scale0, scale1);
tickUpdate.call(tickTransform, scale1, scale1);
});
}
axis.scale = function(x) {
if (!arguments.length) return scale;
scale = x;
return axis;
};
axis.orient = function(x) {
if (!arguments.length) return orient;
orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
return axis;
};
axis.ticks = function() {
if (!arguments.length) return tickArguments_;
tickArguments_ = d3_array(arguments);
return axis;
};
axis.tickValues = function(x) {
if (!arguments.length) return tickValues;
tickValues = x;
return axis;
};
axis.tickFormat = function(x) {
if (!arguments.length) return tickFormat_;
tickFormat_ = x;
return axis;
};
axis.tickSize = function(x) {
var n = arguments.length;
if (!n) return innerTickSize;
innerTickSize = +x;
outerTickSize = +arguments[n - 1];
return axis;
};
axis.innerTickSize = function(x) {
if (!arguments.length) return innerTickSize;
innerTickSize = +x;
return axis;
};
axis.outerTickSize = function(x) {
if (!arguments.length) return outerTickSize;
outerTickSize = +x;
return axis;
};
axis.tickPadding = function(x) {
if (!arguments.length) return tickPadding;
tickPadding = +x;
return axis;
};
axis.tickSubdivide = function() {
return arguments.length && axis;
};
return axis;
};
var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
top: 1,
right: 1,
bottom: 1,
left: 1
};
function d3_svg_axisX(selection, x0, x1) {
selection.attr("transform", function(d) {
var v0 = x0(d);
return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
});
}
function d3_svg_axisY(selection, y0, y1) {
selection.attr("transform", function(d) {
var v0 = y0(d);
return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
});
}
d3.svg.brush = function() {
var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
function brush(g) {
g.each(function() {
var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
var background = g.selectAll(".background").data([ 0 ]);
background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
var resize = g.selectAll(".resize").data(resizes, d3_identity);
resize.exit().remove();
resize.enter().append("g").attr("class", function(d) {
return "resize " + d;
}).style("cursor", function(d) {
return d3_svg_brushCursor[d];
}).append("rect").attr("x", function(d) {
return /[ew]$/.test(d) ? -3 : null;
}).attr("y", function(d) {
return /^[ns]/.test(d) ? -3 : null;
}).attr("width", 6).attr("height", 6).style("visibility", "hidden");
resize.style("display", brush.empty() ? "none" : null);
var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
if (x) {
range = d3_scaleRange(x);
backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
redrawX(gUpdate);
}
if (y) {
range = d3_scaleRange(y);
backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
redrawY(gUpdate);
}
redraw(gUpdate);
});
}
brush.event = function(g) {
g.each(function() {
var event_ = event.of(this, arguments), extent1 = {
x: xExtent,
y: yExtent,
i: xExtentDomain,
j: yExtentDomain
}, extent0 = this.__chart__ || extent1;
this.__chart__ = extent1;
if (d3_transitionInheritId) {
d3.select(this).transition().each("start.brush", function() {
xExtentDomain = extent0.i;
yExtentDomain = extent0.j;
xExtent = extent0.x;
yExtent = extent0.y;
event_({
type: "brushstart"
});
}).tween("brush:brush", function() {
var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
xExtentDomain = yExtentDomain = null;
return function(t) {
xExtent = extent1.x = xi(t);
yExtent = extent1.y = yi(t);
event_({
type: "brush",
mode: "resize"
});
};
}).each("end.brush", function() {
xExtentDomain = extent1.i;
yExtentDomain = extent1.j;
event_({
type: "brush",
mode: "resize"
});
event_({
type: "brushend"
});
});
} else {
event_({
type: "brushstart"
});
event_({
type: "brush",
mode: "resize"
});
event_({
type: "brushend"
});
}
});
};
function redraw(g) {
g.selectAll(".resize").attr("transform", function(d) {
return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
});
}
function redrawX(g) {
g.select(".extent").attr("x", xExtent[0]);
g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
}
function redrawY(g) {
g.select(".extent").attr("y", yExtent[0]);
g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
}
function brushstart() {
var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
if (d3.event.changedTouches) {
w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
} else {
w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
}
g.interrupt().selectAll("*").interrupt();
if (dragging) {
origin[0] = xExtent[0] - origin[0];
origin[1] = yExtent[0] - origin[1];
} else if (resizing) {
var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
origin[0] = xExtent[ex];
origin[1] = yExtent[ey];
} else if (d3.event.altKey) center = origin.slice();
g.style("pointer-events", "none").selectAll(".resize").style("display", null);
d3.select("body").style("cursor", eventTarget.style("cursor"));
event_({
type: "brushstart"
});
brushmove();
function keydown() {
if (d3.event.keyCode == 32) {
if (!dragging) {
center = null;
origin[0] -= xExtent[1];
origin[1] -= yExtent[1];
dragging = 2;
}
d3_eventPreventDefault();
}
}
function keyup() {
if (d3.event.keyCode == 32 && dragging == 2) {
origin[0] += xExtent[1];
origin[1] += yExtent[1];
dragging = 0;
d3_eventPreventDefault();
}
}
function brushmove() {
var point = d3.mouse(target), moved = false;
if (offset) {
point[0] += offset[0];
point[1] += offset[1];
}
if (!dragging) {
if (d3.event.altKey) {
if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
origin[0] = xExtent[+(point[0] < center[0])];
origin[1] = yExtent[+(point[1] < center[1])];
} else center = null;
}
if (resizingX && move1(point, x, 0)) {
redrawX(g);
moved = true;
}
if (resizingY && move1(point, y, 1)) {
redrawY(g);
moved = true;
}
if (moved) {
redraw(g);
event_({
type: "brush",
mode: dragging ? "move" : "resize"
});
}
}
function move1(point, scale, i) {
var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
if (dragging) {
r0 -= position;
r1 -= size + position;
}
min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
if (dragging) {
max = (min += position) + size;
} else {
if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
if (position < min) {
max = min;
min = position;
} else {
max = position;
}
}
if (extent[0] != min || extent[1] != max) {
if (i) yExtentDomain = null; else xExtentDomain = null;
extent[0] = min;
extent[1] = max;
return true;
}
}
function brushend() {
brushmove();
g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
d3.select("body").style("cursor", null);
w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
dragRestore();
event_({
type: "brushend"
});
}
}
brush.x = function(z) {
if (!arguments.length) return x;
x = z;
resizes = d3_svg_brushResizes[!x << 1 | !y];
return brush;
};
brush.y = function(z) {
if (!arguments.length) return y;
y = z;
resizes = d3_svg_brushResizes[!x << 1 | !y];
return brush;
};
brush.clamp = function(z) {
if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
return brush;
};
brush.extent = function(z) {
var x0, x1, y0, y1, t;
if (!arguments.length) {
if (x) {
if (xExtentDomain) {
x0 = xExtentDomain[0], x1 = xExtentDomain[1];
} else {
x0 = xExtent[0], x1 = xExtent[1];
if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
}
}
if (y) {
if (yExtentDomain) {
y0 = yExtentDomain[0], y1 = yExtentDomain[1];
} else {
y0 = yExtent[0], y1 = yExtent[1];
if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
}
}
return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
}
if (x) {
x0 = z[0], x1 = z[1];
if (y) x0 = x0[0], x1 = x1[0];
xExtentDomain = [ x0, x1 ];
if (x.invert) x0 = x(x0), x1 = x(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
}
if (y) {
y0 = z[0], y1 = z[1];
if (x) y0 = y0[1], y1 = y1[1];
yExtentDomain = [ y0, y1 ];
if (y.invert) y0 = y(y0), y1 = y(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
}
return brush;
};
brush.clear = function() {
if (!brush.empty()) {
xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
xExtentDomain = yExtentDomain = null;
}
return brush;
};
brush.empty = function() {
return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
};
return d3.rebind(brush, event, "on");
};
var d3_svg_brushCursor = {
n: "ns-resize",
e: "ew-resize",
s: "ns-resize",
w: "ew-resize",
nw: "nwse-resize",
ne: "nesw-resize",
se: "nwse-resize",
sw: "nesw-resize"
};
var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat;
var d3_time_formatUtc = d3_time_format.utc;
var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ");
d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso;
function d3_time_formatIsoNative(date) {
return date.toISOString();
}
d3_time_formatIsoNative.parse = function(string) {
var date = new Date(string);
return isNaN(date) ? null : date;
};
d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
d3_time.second = d3_time_interval(function(date) {
return new d3_date(Math.floor(date / 1e3) * 1e3);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 1e3);
}, function(date) {
return date.getSeconds();
});
d3_time.seconds = d3_time.second.range;
d3_time.seconds.utc = d3_time.second.utc.range;
d3_time.minute = d3_time_interval(function(date) {
return new d3_date(Math.floor(date / 6e4) * 6e4);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 6e4);
}, function(date) {
return date.getMinutes();
});
d3_time.minutes = d3_time.minute.range;
d3_time.minutes.utc = d3_time.minute.utc.range;
d3_time.hour = d3_time_interval(function(date) {
var timezone = date.getTimezoneOffset() / 60;
return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 36e5);
}, function(date) {
return date.getHours();
});
d3_time.hours = d3_time.hour.range;
d3_time.hours.utc = d3_time.hour.utc.range;
d3_time.month = d3_time_interval(function(date) {
date = d3_time.day(date);
date.setDate(1);
return date;
}, function(date, offset) {
date.setMonth(date.getMonth() + offset);
}, function(date) {
return date.getMonth();
});
d3_time.months = d3_time.month.range;
d3_time.months.utc = d3_time.month.utc.range;
function d3_time_scale(linear, methods, format) {
function scale(x) {
return linear(x);
}
scale.invert = function(x) {
return d3_time_scaleDate(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
linear.domain(x);
return scale;
};
function tickMethod(extent, count) {
var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target);
return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) {
return d / 31536e6;
}), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i];
}
scale.nice = function(interval, skip) {
var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval);
if (method) interval = method[0], skip = method[1];
function skipped(date) {
return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length;
}
return scale.domain(d3_scale_nice(domain, skip > 1 ? {
floor: function(date) {
while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1);
return date;
},
ceil: function(date) {
while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1);
return date;
}
} : interval));
};
scale.ticks = function(interval, skip) {
var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ {
range: interval
}, skip ];
if (method) interval = method[0], skip = method[1];
return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip);
};
scale.tickFormat = function() {
return format;
};
scale.copy = function() {
return d3_time_scale(linear.copy(), methods, format);
};
return d3_scale_linearRebind(scale, linear);
}
function d3_time_scaleDate(t) {
return new Date(t);
}
var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ];
var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) {
return d.getMilliseconds();
} ], [ ":%S", function(d) {
return d.getSeconds();
} ], [ "%I:%M", function(d) {
return d.getMinutes();
} ], [ "%I %p", function(d) {
return d.getHours();
} ], [ "%a %d", function(d) {
return d.getDay() && d.getDate() != 1;
} ], [ "%b %d", function(d) {
return d.getDate() != 1;
} ], [ "%B", function(d) {
return d.getMonth();
} ], [ "%Y", d3_true ] ]);
var d3_time_scaleMilliseconds = {
range: function(start, stop, step) {
return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate);
},
floor: d3_identity,
ceil: d3_identity
};
d3_time_scaleLocalMethods.year = d3_time.year;
d3_time.scale = function() {
return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
};
var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) {
return [ m[0].utc, m[1] ];
});
var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) {
return d.getUTCMilliseconds();
} ], [ ":%S", function(d) {
return d.getUTCSeconds();
} ], [ "%I:%M", function(d) {
return d.getUTCMinutes();
} ], [ "%I %p", function(d) {
return d.getUTCHours();
} ], [ "%a %d", function(d) {
return d.getUTCDay() && d.getUTCDate() != 1;
} ], [ "%b %d", function(d) {
return d.getUTCDate() != 1;
} ], [ "%B", function(d) {
return d.getUTCMonth();
} ], [ "%Y", d3_true ] ]);
d3_time_scaleUtcMethods.year = d3_time.year.utc;
d3_time.scale.utc = function() {
return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat);
};
d3.text = d3_xhrType(function(request) {
return request.responseText;
});
d3.json = function(url, callback) {
return d3_xhr(url, "application/json", d3_json, callback);
};
function d3_json(request) {
return JSON.parse(request.responseText);
}
d3.html = function(url, callback) {
return d3_xhr(url, "text/html", d3_html, callback);
};
function d3_html(request) {
var range = d3_document.createRange();
range.selectNode(d3_document.body);
return range.createContextualFragment(request.responseText);
}
d3.xml = d3_xhrType(function(request) {
return request.responseXML;
});
if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
}();
},{}],33:[function(require,module,exports){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
},{"./debug":34}],34:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":35}],35:[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
* @return {String|Number}
* @api public
*/
module.exports = function(val, options){
options = options || {};
if ('string' == typeof val) return parse(val);
return options.long
? long(val)
: short(val);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = '' + 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;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
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';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function long(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';
}
},{}],36:[function(require,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var undefined;
var isArray = function isArray(arr) {
if (typeof Array.isArray === 'function') {
return Array.isArray(arr);
}
return toStr.call(arr) === '[object Array]';
};
var isPlainObject = function isPlainObject(obj) {
'use strict';
if (!obj || toStr.call(obj) !== '[object Object]') {
return false;
}
var has_own_constructor = hasOwn.call(obj, 'constructor');
var has_is_property_of_method = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key);
};
module.exports = function extend() {
'use strict';
var options, name, src, copy, copyIsArray, clone,
target = arguments[0],
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
} else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) {
target = {};
}
for (; i < length; ++i) {
options = arguments[i];
// Only deal with non-null/undefined values
if (options != 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 && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};
},{}],37:[function(require,module,exports){
var inserted = {};
module.exports = function (css, options) {
if (inserted[css]) return;
inserted[css] = true;
var elem = document.createElement('style');
elem.setAttribute('type', 'text/css');
if ('textContent' in elem) {
elem.textContent = css;
} else {
elem.styleSheet.cssText = css;
}
var head = document.getElementsByTagName('head')[0];
if (options && options.prepend) {
head.insertBefore(elem, head.childNodes[0]);
} else {
head.appendChild(elem);
}
};
},{}],38:[function(require,module,exports){
var json = typeof JSON !== 'undefined' ? JSON : require('jsonify');
module.exports = function (obj, opts) {
if (!opts) opts = {};
if (typeof opts === 'function') opts = { cmp: opts };
var space = opts.space || '';
if (typeof space === 'number') space = Array(space+1).join(' ');
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
var replacer = opts.replacer || function(key, value) { return value; };
var cmp = opts.cmp && (function (f) {
return function (node) {
return function (a, b) {
var aobj = { key: a, value: node[a] };
var bobj = { key: b, value: node[b] };
return f(aobj, bobj);
};
};
})(opts.cmp);
var seen = [];
return (function stringify (parent, key, node, level) {
var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
var colonSeparator = space ? ': ' : ':';
if (node && node.toJSON && typeof node.toJSON === 'function') {
node = node.toJSON();
}
node = replacer.call(parent, key, node);
if (node === undefined) {
return;
}
if (typeof node !== 'object' || node === null) {
return json.stringify(node);
}
if (isArray(node)) {
var out = [];
for (var i = 0; i < node.length; i++) {
var item = stringify(node, i, node[i], level+1) || json.stringify(null);
out.push(indent + space + item);
}
return '[' + out.join(',') + indent + ']';
}
else {
if (seen.indexOf(node) !== -1) {
if (cycles) return json.stringify('__cycle__');
throw new TypeError('Converting circular structure to JSON');
}
else seen.push(node);
var keys = objectKeys(node).sort(cmp && cmp(node));
var out = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = stringify(node, key, node[key], level+1);
if(!value) continue;
var keyValue = json.stringify(key)
+ colonSeparator
+ value;
;
out.push(indent + space + keyValue);
}
seen.splice(seen.indexOf(node), 1);
return '{' + out.join(',') + indent + '}';
}
})({ '': obj }, '', obj, 0);
};
var isArray = Array.isArray || function (x) {
return {}.toString.call(x) === '[object Array]';
};
var objectKeys = Object.keys || function (obj) {
var has = Object.prototype.hasOwnProperty || function () { return true };
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) keys.push(key);
}
return keys;
};
},{"jsonify":39}],39:[function(require,module,exports){
exports.parse = require('./lib/parse');
exports.stringify = require('./lib/stringify');
},{"./lib/parse":40,"./lib/stringify":41}],40:[function(require,module,exports){
var at, // The index of the current character
ch, // The current character
escapee = {
'"': '"',
'\\': '\\',
'/': '/',
b: '\b',
f: '\f',
n: '\n',
r: '\r',
t: '\t'
},
text,
error = function (m) {
// Call error when something is wrong.
throw {
name: 'SyntaxError',
message: m,
at: at,
text: text
};
},
next = function (c) {
// If a c parameter is provided, verify that it matches the current character.
if (c && c !== ch) {
error("Expected '" + c + "' instead of '" + ch + "'");
}
// Get the next character. When there are no more characters,
// return the empty string.
ch = text.charAt(at);
at += 1;
return ch;
},
number = function () {
// Parse a number value.
var number,
string = '';
if (ch === '-') {
string = '-';
next('-');
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
if (ch === '.') {
string += '.';
while (next() && ch >= '0' && ch <= '9') {
string += ch;
}
}
if (ch === 'e' || ch === 'E') {
string += ch;
next();
if (ch === '-' || ch === '+') {
string += ch;
next();
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
}
number = +string;
if (!isFinite(number)) {
error("Bad number");
} else {
return number;
}
},
string = function () {
// Parse a string value.
var hex,
i,
string = '',
uffff;
// When parsing for string values, we must look for " and \ characters.
if (ch === '"') {
while (next()) {
if (ch === '"') {
next();
return string;
} else if (ch === '\\') {
next();
if (ch === 'u') {
uffff = 0;
for (i = 0; i < 4; i += 1) {
hex = parseInt(next(), 16);
if (!isFinite(hex)) {
break;
}
uffff = uffff * 16 + hex;
}
string += String.fromCharCode(uffff);
} else if (typeof escapee[ch] === 'string') {
string += escapee[ch];
} else {
break;
}
} else {
string += ch;
}
}
}
error("Bad string");
},
white = function () {
// Skip whitespace.
while (ch && ch <= ' ') {
next();
}
},
word = function () {
// true, false, or null.
switch (ch) {
case 't':
next('t');
next('r');
next('u');
next('e');
return true;
case 'f':
next('f');
next('a');
next('l');
next('s');
next('e');
return false;
case 'n':
next('n');
next('u');
next('l');
next('l');
return null;
}
error("Unexpected '" + ch + "'");
},
value, // Place holder for the value function.
array = function () {
// Parse an array value.
var array = [];
if (ch === '[') {
next('[');
white();
if (ch === ']') {
next(']');
return array; // empty array
}
while (ch) {
array.push(value());
white();
if (ch === ']') {
next(']');
return array;
}
next(',');
white();
}
}
error("Bad array");
},
object = function () {
// Parse an object value.
var key,
object = {};
if (ch === '{') {
next('{');
white();
if (ch === '}') {
next('}');
return object; // empty object
}
while (ch) {
key = string();
white();
next(':');
if (Object.hasOwnProperty.call(object, key)) {
error('Duplicate key "' + key + '"');
}
object[key] = value();
white();
if (ch === '}') {
next('}');
return object;
}
next(',');
white();
}
}
error("Bad object");
};
value = function () {
// Parse a JSON value. It could be an object, an array, a string, a number,
// or a word.
white();
switch (ch) {
case '{':
return object();
case '[':
return array();
case '"':
return string();
case '-':
return number();
default:
return ch >= '0' && ch <= '9' ? number() : word();
}
};
// Return the json_parse function. It will have access to all of the above
// functions and variables.
module.exports = function (source, reviver) {
var result;
text = source;
at = 0;
ch = ' ';
result = value();
white();
if (ch) {
error("Syntax error");
}
// If there is a reviver function, we recursively walk the new structure,
// passing each name/value pair to the reviver function for possible
// transformation, starting with a temporary root object that holds the result
// in an empty key. If there is not a reviver function, we simply return the
// result.
return typeof reviver === 'function' ? (function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}({'': result}, '')) : result;
};
},{}],41:[function(require,module,exports){
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
case 'object':
if (!value) return 'null';
gap += indent;
partial = [];
// Array.isArray
if (Object.prototype.toString.apply(value) === '[object Array]') {
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and
// wrap them in brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be
// stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
module.exports = function (value, replacer, space) {
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
}
// If the space parameter is a string, it will be used as the indent string.
else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function'
&& (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
},{}],42:[function(require,module,exports){
(function (process,global){
/*!
localForage -- Offline Storage, Improved
Version 1.4.0
https://mozilla.github.io/localForage
(c) 2013-2015 Mozilla, Apache License 2.0
*/
(function() {
var define, requireModule, require, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = require = 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'); } }
var localForage = (function (globalObject) {
'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
};
var driverSupport = (function (self) {
var result = {};
// 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
result[DriverType.INDEXEDDB] = !!(function () {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB;
// 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;
}
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.WEBSQL] = !!(function () {
try {
return self.openDatabase;
} 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;
})(globalObject);
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;
})();
return new LocalForage();
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localForage;
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;
var asyncStorage = (function (globalObject) {
'use strict';
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || globalObject.indexedDB || globalObject.webkitIndexedDB || globalObject.mozIndexedDB || globalObject.OIndexedDB || globalObject.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);
});
};
};
txn.onerror = txn.onabort = reject;
})['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;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
promise.then(callback, callback);
return promise;
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new Promise(function (resolve) {
deferredOperation.resolve = resolve;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
}
}
// 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,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: []
};
// 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(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
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 !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady()['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(initPromises).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 = 0; k < forages.length; k++) {
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) {
_deferReadiness(dbInfo);
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);
_advanceReadiness(dbInfo);
};
});
}
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;
if (value instanceof Blob) {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
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;
}
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);
};
var req = store.put(value, key);
})['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
};
return asyncStorage;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = asyncStorage;
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;
var localStorageWrapper = (function (globalObject) {
'use strict';
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 (!globalObject.localStorage || !('setItem' in globalObject.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = globalObject.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
};
return localStorageWrapper;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localStorageWrapper;
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var localforageSerializer = (function (globalObject) {
'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;
// 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
};
return localforageSerializer;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localforageSerializer;
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;
var webSQLStorage = (function (globalObject) {
'use strict';
var openDatabase = globalObject.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 reject(e);
}
// 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
};
return webSQLStorage;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = webSQLStorage;
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
}).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"FWaASH":10}],43:[function(require,module,exports){
(function (global){
/**
* @license
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern -d -o ./index.js`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the semantic version number. */
var VERSION = '3.0.1';
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
CURRY_BOUND_FLAG = 4,
CURRY_FLAG = 8,
CURRY_RIGHT_FLAG = 16,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64,
REARG_FLAG = 128,
ARY_FLAG = 256;
/** Used as default options for `_.trunc`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to detect when a function becomes hot. */
var HOT_COUNT = 150,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_FILTER_FLAG = 0,
LAZY_MAP_FLAG = 1,
LAZY_WHILE_FLAG = 2;
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** `Object#toString` result references. */
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]';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match HTML entities and HTML characters. */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
reUnescapedHtml = /[&<>"'`]/g,
reHasEscapedHtml = RegExp(reEscapedHtml.source),
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/** Used to match template delimiters. */
var reEscape = /<%-([\s\S]+?)%>/g,
reEvaluate = /<%([\s\S]+?)%>/g,
reInterpolate = /<%=([\s\S]+?)%>/g;
/**
* Used to match ES template delimiters.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components)
* for more details.
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect named functions. */
var reFuncName = /^\s*function[ \n\r\t]+\w/;
/** Used to detect hexadecimal string values. */
var reHexPrefix = /^0[xX]/;
/** Used to detect host constructors (Safari > 5). */
var reHostCtor = /^\[object .+?Constructor\]$/;
/** Used to match latin-1 supplementary letters (excluding mathematical operators). */
var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/**
* Used to match `RegExp` special characters.
* See this [article on `RegExp` characters](http://www.regular-expressions.info/characters.html#special)
* for more details.
*/
var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g,
reHasRegExpChars = RegExp(reRegExpChars.source);
/** Used to detect functions containing a `this` reference. */
var reThis = /\bthis\b/;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
/** Used to match words to create compound words. */
var reWords = (function() {
var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
return RegExp(upper + '{2,}(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
}());
/** Used to detect and test for whitespace. */
var whitespace = (
// Basic whitespace characters.
' \t\x0b\f\xa0\ufeff' +
// Line terminators.
'\n\r\u2028\u2029' +
// Unicode category "Zs" space separators.
'\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
);
/** Used to assign default `context` object properties. */
var contextProps = [
'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'document',
'isFinite', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
'window', 'WinRTError'
];
/** Used to make template sourceURLs easier to identify. */
var templateCounter = -1;
/** Used to identify `toStringTag` values of typed arrays. */
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;
/** Used to identify `toStringTag` values supported by `_.clone`. */
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;
/** Used as an internal `_.debounce` options object by `_.throttle`. */
var debounceOptions = {
'leading': false,
'maxWait': 0,
'trailing': false
};
/** Used to map latin-1 supplementary letters to basic latin letters. */
var deburredLetters = {
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss'
};
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
'`': '&#96;'
};
/** Used to map HTML entities to characters. */
var htmlUnescapes = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
'&#96;': '`'
};
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/**
* Used as a reference to the global object.
*
* The `this` value is used if it is the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = (objectTypes[typeof window] && window !== (this && this.window)) ? window : this;
/** Detect free variable `exports`. */
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root`. */
var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) {
root = freeGlobal;
}
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `compareAscending` which compares values and
* sorts them in ascending order without guaranteeing a stable sort.
*
* @private
* @param {*} value The value to compare to `other`.
* @param {*} other The value to compare to `value`.
* @returns {number} Returns the sort order indicator for `value`.
*/
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;
}
/**
* The base implementation of `_.indexOf` without support for binary searches.
*
* @private
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
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;
}
/**
* The base implementation of `_.sortBy` and `_.sortByAll` which uses `comparer`
* to define the sort order of `array` and replaces criteria objects with their
* corresponding values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/**
* Converts `value` to a string if it is not one. An empty string is returned
* for `null` or `undefined` values.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
if (typeof value == 'string') {
return value;
}
return value == null ? '' : (value + '');
}
/**
* Used by `_.max` and `_.min` as the default callback for string values.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the code unit of the first character of the string.
*/
function charAtCallback(string) {
return string.charCodeAt(0);
}
/**
* Used by `_.trim` and `_.trimLeft` to get the index of the first character
* of `string` that is not found in `chars`.
*
* @private
* @param {string} string The string to inspect.
* @param {string} chars The characters to find.
* @returns {number} Returns the index of the first character not found in `chars`.
*/
function charsLeftIndex(string, chars) {
var index = -1,
length = string.length;
while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
return index;
}
/**
* Used by `_.trim` and `_.trimRight` to get the index of the last character
* of `string` that is not found in `chars`.
*
* @private
* @param {string} string The string to inspect.
* @param {string} chars The characters to find.
* @returns {number} Returns the index of the last character not found in `chars`.
*/
function charsRightIndex(string, chars) {
var index = string.length;
while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
return index;
}
/**
* Used by `_.sortBy` to compare transformed elements of a collection and stable
* sort them in ascending order.
*
* @private
* @param {Object} object The object to compare to `other`.
* @param {Object} other The object to compare to `object`.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareAscending(object, other) {
return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
}
/**
* Used by `_.sortByAll` to compare multiple properties of each element
* in a collection and stable sort them in ascending order.
*
* @private
* @param {Object} object The object to compare to `other`.
* @param {Object} other The object to compare to `object`.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultipleAscending(object, other) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length;
while (++index < length) {
var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
if (result) {
return result;
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://code.google.com/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
/**
* Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
function deburrLetter(letter) {
return deburredLetters[letter];
}
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeHtmlChar(chr) {
return htmlEscapes[chr];
}
/**
* Used by `_.template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/**
* Gets the index at which the first occurrence of `NaN` is found in `array`.
* If `fromRight` is provided elements of `array` are iterated from right to left.
*
* @private
* @param {Array} array The array to search.
* @param {number} [fromIndex] The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched `NaN`, else `-1`.
*/
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;
}
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return (value && typeof value == 'object') || false;
}
/**
* Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
* character code is whitespace.
*
* @private
* @param {number} charCode The character code to inspect.
* @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
*/
function isSpace(charCode) {
return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
(charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
}
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = -1,
result = [];
while (++index < length) {
if (array[index] === placeholder) {
array[index] = PLACEHOLDER;
result[++resIndex] = index;
}
}
return result;
}
/**
* An implementation of `_.uniq` optimized for sorted arrays without support
* for callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The function invoked per iteration.
* @returns {Array} Returns the new duplicate-value-free array.
*/
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;
}
/**
* Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the first non-whitespace character.
*/
function trimmedLeftIndex(string) {
var index = -1,
length = string.length;
while (++index < length && isSpace(string.charCodeAt(index))) {}
return index;
}
/**
* Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedRightIndex(string) {
var index = string.length;
while (index-- && isSpace(string.charCodeAt(index))) {}
return index;
}
/**
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
function unescapeHtmlChar(chr) {
return htmlUnescapes[chr];
}
/*--------------------------------------------------------------------------*/
/**
* Create a new pristine `lodash` function using the given `context` object.
*
* @static
* @memberOf _
* @category Utility
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
*
* _.mixin({ 'add': function(a, b) { return a + b; } });
*
* var lodash = _.runInContext();
* lodash.mixin({ 'sub': function(a, b) { return a - b; } });
*
* _.isFunction(_.add);
* // => true
* _.isFunction(_.sub);
* // => false
*
* lodash.isFunction(lodash.add);
* // => false
* lodash.isFunction(lodash.sub);
* // => true
*
* // using `context` to mock `Date#getTime` use in `_.now`
* var mock = _.runInContext({
* 'Date': function() {
* return { 'getTime': getTimeMock };
* }
* });
*
* // or creating a suped-up `defer` in Node.js
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
*/
function runInContext(context) {
// Avoid issues with some ES3 environments that attempt to use values, named
// after built-in constructors like `Object`, for the creation of literals.
// ES5 clears this up by stating that literals must use built-in constructors.
// See https://es5.github.io/#x11.1.5 for more details.
context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
/** Native constructor references. */
var Array = context.Array,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Number = context.Number,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/** Used for native method references. */
var arrayProto = Array.prototype,
objectProto = Object.prototype;
/** Used to detect DOM support. */
var document = (document = context.window) && document.document;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to the length of n-tuples for `_.unzip`. */
var getLength = baseProperty('length');
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = context._;
/** Used to detect if a method is native. */
var reNative = RegExp('^' +
escapeRegExp(objToString)
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Native method references. */
var ArrayBuffer = isNative(ArrayBuffer = context.ArrayBuffer) && ArrayBuffer,
bufferSlice = isNative(bufferSlice = ArrayBuffer && new ArrayBuffer(0).slice) && bufferSlice,
ceil = Math.ceil,
clearTimeout = context.clearTimeout,
floor = Math.floor,
getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
push = arrayProto.push,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
Set = isNative(Set = context.Set) && Set,
setTimeout = context.setTimeout,
splice = arrayProto.splice,
Uint8Array = isNative(Uint8Array = context.Uint8Array) && Uint8Array,
unshift = arrayProto.unshift,
WeakMap = isNative(WeakMap = context.WeakMap) && WeakMap;
/** Used to clone array buffers. */
var Float64Array = (function() {
// Safari 5 errors when using an array buffer to initialize a typed array
// where the array buffer's `byteLength` is not a multiple of the typed
// array's `BYTES_PER_ELEMENT`.
try {
var func = isNative(func = context.Float64Array) && func,
result = new func(new ArrayBuffer(10), 0, 1) && func;
} catch(e) {}
return result;
}());
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
nativeIsFinite = context.isFinite,
nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
nativeMax = Math.max,
nativeMin = Math.min,
nativeNow = isNative(nativeNow = Date.now) && nativeNow,
nativeNumIsFinite = isNative(nativeNumIsFinite = Number.isFinite) && nativeNumIsFinite,
nativeParseInt = context.parseInt,
nativeRandom = Math.random;
/** Used as references for `-Infinity` and `Infinity`. */
var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
/** Used as the size, in bytes, of each `Float64Array` element. */
var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0;
/**
* Used as the maximum length of an array-like value.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength)
* for more details.
*/
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps `value` to enable intuitive chaining.
* Methods that operate on and return arrays, collections, and functions can
* be chained together. Methods that return a boolean or single value will
* automatically end the chain returning the unwrapped value. Explicit chaining
* may be enabled using `_.chain`. The execution of chained methods is lazy,
* that is, execution is deferred until `_#value` is implicitly or explicitly
* called.
*
* Lazy evaluation allows several methods to support shortcut fusion. Shortcut
* fusion is an optimization that merges iteratees to avoid creating intermediate
* arrays and reduce the number of iteratee executions.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers also have the following `Array` methods:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
* and `unshift`
*
* The wrapper functions that support shortcut fusion are:
* `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, `first`,
* `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, `slice`,
* `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `where`
*
* The chainable wrapper functions are:
* `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
* `callback`, `chain`, `chunk`, `compact`, `concat`, `constant`, `countBy`,
* `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`, `difference`,
* `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, `flatten`,
* `flattenDeep`, `flow`, `flowRight`, `forEach`, `forEachRight`, `forIn`,
* `forInRight`, `forOwn`, `forOwnRight`, `functions`, `groupBy`, `indexBy`,
* `initial`, `intersection`, `invert`, `invoke`, `keys`, `keysIn`, `map`,
* `mapValues`, `matches`, `memoize`, `merge`, `mixin`, `negate`, `noop`,
* `omit`, `once`, `pairs`, `partial`, `partialRight`, `partition`, `pick`,
* `pluck`, `property`, `propertyOf`, `pull`, `pullAt`, `push`, `range`,
* `rearg`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
* `sortBy`, `sortByAll`, `splice`, `take`, `takeRight`, `takeRightWhile`,
* `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
* `transform`, `union`, `uniq`, `unshift`, `unzip`, `values`, `valuesIn`,
* `where`, `without`, `wrap`, `xor`, `zip`, and `zipObject`
*
* The wrapper functions that are **not** chainable by default are:
* `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`,
* `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`,
* `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `has`,
* `identity`, `includes`, `indexOf`, `isArguments`, `isArray`, `isBoolean`,
* `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, `isFinite`,
* `isFunction`, `isMatch` , `isNative`, `isNaN`, `isNull`, `isNumber`,
* `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`,
* `isTypedArray`, `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`,
* `noConflict`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`,
* `random`, `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`,
* `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`,
* `startsWith`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
* `unescape`, `uniqueId`, `value`, and `words`
*
* The wrapper function `sample` will return a wrapped value when `n` is provided,
* otherwise an unwrapped value is returned.
*
* @name _
* @constructor
* @category Chain
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns a `lodash` instance.
* @example
*
* var wrapped = _([1, 2, 3]);
*
* // returns an unwrapped value
* wrapped.reduce(function(sum, n) { return sum + n; });
* // => 6
*
* // returns a wrapped value
* var squares = wrapped.map(function(n) { return n * n; });
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return new LodashWrapper(value.__wrapped__, value.__chain__, arrayCopy(value.__actions__));
}
}
return new LodashWrapper(value);
}
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable chaining for all wrapper methods.
* @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
*/
function LodashWrapper(value, chainAll, actions) {
this.__actions__ = actions || [];
this.__chain__ = !!chainAll;
this.__wrapped__ = value;
}
/**
* An object environment feature flags.
*
* @static
* @memberOf _
* @type Object
*/
var support = lodash.support = {};
(function(x) {
/**
* Detect if functions can be decompiled by `Function#toString`
* (all but Firefox OS certified apps, older Opera mobile browsers, and
* the PlayStation 3; forced `false` for Windows 8 apps).
*
* @memberOf _.support
* @type boolean
*/
support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);
/**
* Detect if `Function#name` is supported (all but IE).
*
* @memberOf _.support
* @type boolean
*/
support.funcNames = typeof Function.name == 'string';
/**
* Detect if the DOM is supported.
*
* @memberOf _.support
* @type boolean
*/
try {
support.dom = document.createDocumentFragment().nodeType === 11;
} catch(e) {
support.dom = false;
}
/**
* Detect if `arguments` object indexes are non-enumerable.
*
* In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object
* indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat
* `arguments` object indexes as non-enumerable and fail `hasOwnProperty`
* checks for indexes that exceed their function's formal parameters with
* associated values of `0`.
*
* @memberOf _.support
* @type boolean
*/
try {
support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1);
} catch(e) {
support.nonEnumArgs = true;
}
}(0, 0));
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB). Change the following template settings to use
* alternative delimiters.
*
* @static
* @memberOf _
* @type Object
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'escape': reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type string
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type Object
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type Function
*/
'_': lodash
}
};
/*------------------------------------------------------------------------*/
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.actions = null;
this.dir = 1;
this.dropCount = 0;
this.filtered = false;
this.iteratees = null;
this.takeCount = POSITIVE_INFINITY;
this.views = null;
this.wrapped = value;
}
/**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/
function lazyClone() {
var actions = this.actions,
iteratees = this.iteratees,
views = this.views,
result = new LazyWrapper(this.wrapped);
result.actions = actions ? arrayCopy(actions) : null;
result.dir = this.dir;
result.dropCount = this.dropCount;
result.filtered = this.filtered;
result.iteratees = iteratees ? arrayCopy(iteratees) : null;
result.takeCount = this.takeCount;
result.views = views ? arrayCopy(views) : null;
return result;
}
/**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/
function lazyReverse() {
if (this.filtered) {
var result = new LazyWrapper(this);
result.dir = -1;
result.filtered = true;
} else {
result = this.clone();
result.dir *= -1;
}
return result;
}
/**
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
*/
function lazyValue() {
var array = this.wrapped.value();
if (!isArray(array)) {
return baseWrapperValue(array, this.actions);
}
var dir = this.dir,
isRight = dir < 0,
view = getView(0, array.length, this.views),
start = view.start,
end = view.end,
length = end - start,
dropCount = this.dropCount,
takeCount = nativeMin(length, this.takeCount - dropCount),
index = isRight ? end : start - 1,
iteratees = this.iteratees,
iterLength = iteratees ? iteratees.length : 0,
resIndex = 0,
result = [];
outer:
while (length-- && resIndex < takeCount) {
index += dir;
var iterIndex = -1,
value = array[index];
while (++iterIndex < iterLength) {
var data = iteratees[iterIndex],
iteratee = data.iteratee,
computed = iteratee(value, index, array),
type = data.type;
if (type == LAZY_MAP_FLAG) {
value = computed;
} else if (!computed) {
if (type == LAZY_FILTER_FLAG) {
continue outer;
} else {
break outer;
}
}
}
if (dropCount) {
dropCount--;
} else {
result[resIndex++] = value;
}
}
return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates a cache object to store key/value pairs.
*
* @private
* @static
* @name Cache
* @memberOf _.memoize
*/
function MapCache() {
this.__data__ = {};
}
/**
* Removes `key` and its value from the cache.
*
* @private
* @name delete
* @memberOf _.memoize.Cache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
*/
function mapDelete(key) {
return this.has(key) && delete this.__data__[key];
}
/**
* Gets the cached value for `key`.
*
* @private
* @name get
* @memberOf _.memoize.Cache
* @param {string} key The key of the value to get.
* @returns {*} Returns the cached value.
*/
function mapGet(key) {
return key == '__proto__' ? undefined : this.__data__[key];
}
/**
* Checks if a cached value for `key` exists.
*
* @private
* @name has
* @memberOf _.memoize.Cache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapHas(key) {
return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
}
/**
* Adds `value` to `key` of the cache.
*
* @private
* @name set
* @memberOf _.memoize.Cache
* @param {string} key The key of the value to cache.
* @param {*} value The value to cache.
* @returns {Object} Returns the cache object.
*/
function mapSet(key, value) {
if (key != '__proto__') {
this.__data__[key] = value;
}
return this;
}
/*------------------------------------------------------------------------*/
/**
*
* Creates a cache object to store unique values.
*
* @private
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var length = values ? values.length : 0;
this.data = { 'hash': nativeCreate(null), 'set': new Set };
while (length--) {
this.push(values[length]);
}
}
/**
* Checks if `value` is in `cache` mimicking the return signature of
* `_.indexOf` by returning `0` if the value is found, else `-1`.
*
* @private
* @param {Object} cache The cache to search.
* @param {*} value The value to search for.
* @returns {number} Returns `0` if `value` is found, else `-1`.
*/
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;
}
/**
* Adds `value` to the cache.
*
* @private
* @name push
* @memberOf SetCache
* @param {*} value The value to cache.
*/
function cachePush(value) {
var data = this.data;
if (typeof value == 'string' || isObject(value)) {
data.set.add(value);
} else {
data.hash[value] = true;
}
}
/*------------------------------------------------------------------------*/
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function arrayCopy(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* A specialized version of `_.forEach` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.forEachRight` for arrays without support for
* callback shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEachRight(array, iteratee) {
var length = array.length;
while (length--) {
if (iteratee(array[length], length, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.every` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
/**
* A specialized version of `_.filter` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array.length,
resIndex = -1,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[++resIndex] = value;
}
}
return result;
}
/**
* A specialized version of `_.map` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
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;
}
/**
* A specialized version of `_.max` for arrays without support for iteratees.
*
* @private
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
*/
function arrayMax(array) {
var index = -1,
length = array.length,
result = NEGATIVE_INFINITY;
while (++index < length) {
var value = array[index];
if (value > result) {
result = value;
}
}
return result;
}
/**
* A specialized version of `_.min` for arrays without support for iteratees.
*
* @private
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
*/
function arrayMin(array) {
var index = -1,
length = array.length,
result = POSITIVE_INFINITY;
while (++index < length) {
var value = array[index];
if (value < result) {
result = value;
}
}
return result;
}
/**
* A specialized version of `_.reduce` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initFromArray] Specify using the first element of `array`
* as the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initFromArray) {
var index = -1,
length = array.length;
if (initFromArray && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* A specialized version of `_.reduceRight` for arrays without support for
* callback shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initFromArray] Specify using the last element of `array`
* as the initial value.
* @returns {*} Returns the accumulated value.
*/
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;
}
/**
* A specialized version of `_.some` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* Used by `_.defaults` to customize its `_.assign` use.
*
* @private
* @param {*} objectValue The destination object property value.
* @param {*} sourceValue The source object property value.
* @returns {*} Returns the value to assign to the destination object.
*/
function assignDefaults(objectValue, sourceValue) {
return typeof objectValue == 'undefined' ? sourceValue : objectValue;
}
/**
* Used by `_.template` to customize its `_.assign` use.
*
* **Note:** This method is like `assignDefaults` except that it ignores
* inherited property values when checking if a property is `undefined`.
*
* @private
* @param {*} objectValue The destination object property value.
* @param {*} sourceValue The source object property value.
* @param {string} key The key associated with the object and source values.
* @param {Object} object The destination object.
* @returns {*} Returns the value to assign to the destination object.
*/
function assignOwnDefaults(objectValue, sourceValue, key, object) {
return (typeof objectValue == 'undefined' || !hasOwnProperty.call(object, key))
? sourceValue
: objectValue;
}
/**
* The base implementation of `_.assign` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize assigning values.
* @returns {Object} Returns the destination object.
*/
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;
}
/**
* The base implementation of `_.at` without support for strings and individual
* key arguments.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {number[]|string[]} [props] The property names or indexes of elements to pick.
* @returns {Array} Returns the new array of picked elements.
*/
function baseAt(collection, props) {
var index = -1,
length = collection.length,
isArr = isLength(length),
propsLength = props.length,
result = Array(propsLength);
while(++index < propsLength) {
var key = props[index];
if (isArr) {
key = parseFloat(key);
result[index] = isIndex(key, length) ? collection[key] : undefined;
} else {
result[index] = collection[key];
}
}
return result;
}
/**
* Copies the properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Object} [object={}] The object to copy properties to.
* @param {Array} props The property names to copy.
* @returns {Object} Returns `object`.
*/
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;
}
/**
* The base implementation of `_.bindAll` without support for individual
* method name arguments.
*
* @private
* @param {Object} object The object to bind and assign the bound methods to.
* @param {string[]} methodNames The object method names to bind.
* @returns {Object} Returns `object`.
*/
function baseBindAll(object, methodNames) {
var index = -1,
length = methodNames.length;
while (++index < length) {
var key = methodNames[index];
object[key] = createWrapper(object[key], BIND_FLAG, object);
}
return object;
}
/**
* The base implementation of `_.callback` which supports specifying the
* number of arguments to provide to `func`.
*
* @private
* @param {*} [func=_.identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
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;
}
// Handle "_.property" and "_.matches" style callback shorthands.
return type == 'object'
? baseMatches(func, !argCount)
: baseProperty(func + '');
}
/**
* The base implementation of `_.clone` without support for argument juggling
* and `this` binding `customizer` functions.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @param {Function} [customizer] The function to customize cloning values.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The object `value` belongs to.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates clones with source counterparts.
* @returns {*} Returns the cloned value.
*/
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 : {});
}
}
// Check for circular references and return corresponding clone.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
// Add the source value to the stack of traversed objects and associate it with its clone.
stackA.push(value);
stackB.push(result);
// Recursively populate clone (susceptible to call stack limits).
(isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
});
return result;
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function Object() {}
return function(prototype) {
if (isObject(prototype)) {
Object.prototype = prototype;
var result = new Object;
Object.prototype = null;
}
return result || context.Object();
};
}());
/**
* The base implementation of `_.delay` and `_.defer` which accepts an index
* of where to slice the arguments to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Object} args The `arguments` object to slice and provide to `func`.
* @returns {number} Returns the timer id.
*/
function baseDelay(func, wait, args, fromIndex) {
if (!isFunction(func)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
return setTimeout(function() { func.apply(undefined, baseSlice(args, fromIndex)); }, wait);
}
/**
* The base implementation of `_.difference` which accepts a single array
* of values to exclude.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values) {
var length = array ? array.length : 0,
result = [];
if (!length) {
return result;
}
var index = -1,
indexOf = getIndexOf(),
isCommon = indexOf == baseIndexOf,
cache = isCommon && values.length >= 200 && createCache(values),
valuesLength = values.length;
if (cache) {
indexOf = cacheIndexOf;
isCommon = false;
values = cache;
}
outer:
while (++index < length) {
var value = array[index];
if (isCommon && value === value) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === value) {
continue outer;
}
}
result.push(value);
}
else if (indexOf(values, value) < 0) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.forEach` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object|string} Returns `collection`.
*/
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;
}
/**
* The base implementation of `_.forEachRight` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object|string} Returns `collection`.
*/
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;
}
/**
* The base implementation of `_.every` without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
/**
* The base implementation of `_.filter` without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
/**
* The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
* without support for callback shorthands and `this` binding, which iterates
* over `collection` using the provided `eachFunc`.
*
* @private
* @param {Array|Object|string} collection The collection to search.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @param {boolean} [retKey] Specify returning the key of the found element
* instead of the element itself.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFind(collection, predicate, eachFunc, retKey) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = retKey ? key : value;
return false;
}
});
return result;
}
/**
* The base implementation of `_.flatten` with added support for restricting
* flattening and specifying the start index.
*
* @private
* @param {Array} array The array to flatten.
* @param {boolean} [isDeep] Specify a deep flatten.
* @param {boolean} [isStrict] Restrict flattening to arrays and `arguments` objects.
* @param {number} [fromIndex=0] The index to start from.
* @returns {Array} Returns the new flattened array.
*/
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) {
// Recursively flatten arrays (susceptible to call stack limits).
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;
}
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iterator functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
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;
}
/**
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
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;
}
/**
* The base implementation of `_.forIn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForIn(object, iteratee) {
return baseFor(object, iteratee, keysIn);
}
/**
* The base implementation of `_.forOwn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.forOwnRight` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
return baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from those provided.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the new array of filtered property names.
*/
function baseFunctions(object, props) {
var index = -1,
length = props.length,
resIndex = -1,
result = [];
while (++index < length) {
var key = props[index];
if (isFunction(object[key])) {
result[++resIndex] = key;
}
}
return result;
}
/**
* The base implementation of `_.invoke` which requires additional arguments
* to be provided as an array of arguments rather than individually.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|string} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {Array} [args] The arguments to invoke the method with.
* @returns {Array} Returns the array of results.
*/
function baseInvoke(collection, methodName, args) {
var index = -1,
isFunc = typeof methodName == 'function',
length = collection ? collection.length : 0,
result = isLength(length) ? Array(length) : [];
baseEach(collection, function(value) {
var func = isFunc ? methodName : (value != null && value[methodName]);
result[++index] = func ? func.apply(value, args) : undefined;
});
return result;
}
/**
* The base implementation of `_.isEqual` without support for `this` binding
* `customizer` functions.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isWhere] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, isWhere, stackA, stackB) {
// Exit early for identical values.
if (value === other) {
// Treat `+0` vs. `-0` as not equal.
return value !== 0 || (1 / value == 1 / other);
}
var valType = typeof value,
othType = typeof other;
// Exit early for unlike primitive values.
if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') ||
value == null || other == null) {
// Return `false` unless both values are `NaN`.
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, isWhere, stackA, stackB);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing objects.
* @param {boolean} [isWhere] Specify performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `value` objects.
* @param {Array} [stackB=[]] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
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;
}
// Assume cyclic values are equal.
// For more information on detecting circular references see https://es5.github.io/#JO.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == object) {
return stackB[length] == other;
}
}
// Add `object` and `other` to the stack of traversed objects.
stackA.push(object);
stackB.push(other);
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isWhere, stackA, stackB);
stackA.pop();
stackB.pop();
return result;
}
/**
* The base implementation of `_.isMatch` without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Object} source The object to inspect.
* @param {Array} props The source property names to match.
* @param {Array} values The source values to match.
* @param {Array} strictCompareFlags Strict comparison flags for source values.
* @param {Function} [customizer] The function to customize comparing objects.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
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;
}
/**
* The base implementation of `_.map` without support for callback shorthands
* or `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var result = [];
baseEach(collection, function(value, key, collection) {
result.push(iteratee(value, key, collection));
});
return result;
}
/**
* The base implementation of `_.matches` which supports specifying whether
* `source` should be cloned.
*
* @private
* @param {Object} source The object of property values to match.
* @param {boolean} [isCloned] Specify cloning the source object.
* @returns {Function} Returns the new function.
*/
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);
};
}
/**
* The base implementation of `_.merge` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize merging properties.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {Object} Returns the destination object.
*/
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;
}
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize merging properties.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
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 : {});
}
else {
isCommon = false;
}
}
// Add the source value to the stack of traversed objects and associate
// it with its merged value.
stackA.push(srcValue);
stackB.push(result);
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
} else if (result === result ? result !== value : value === value) {
object[key] = result;
}
}
/**
* The base implementation of `_.property` which does not coerce `key` to a string.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.pullAt` without support for individual
* index arguments.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
*/
function basePullAt(array, indexes) {
var length = indexes.length,
result = baseAt(array, indexes);
indexes.sort(baseCompareAscending);
while (length--) {
var index = parseFloat(indexes[length]);
if (index != previous && isIndex(index)) {
var previous = index;
splice.call(array, index, 1);
}
}
return result;
}
/**
* The base implementation of `_.random` without support for argument juggling
* and returning floating-point numbers.
*
* @private
* @param {number} min The minimum possible value.
* @param {number} max The maximum possible value.
* @returns {number} Returns the random number.
*/
function baseRandom(min, max) {
return min + floor(nativeRandom() * (max - min + 1));
}
/**
* The base implementation of `_.reduce` and `_.reduceRight` without support
* for callback shorthands or `this` binding, which iterates over `collection`
* using the provided `eachFunc`.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initFromCollection Specify using the first or last element
* of `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
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;
}
/**
* The base implementation of `setData` without support for hot loop detection.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
start = start == null ? 0 : (+start || 0);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (typeof end == 'undefined' || end > length) ? length : (+end || 0);
if (end < 0) {
end += length;
}
length = start > end ? 0 : (end - start) >>> 0;
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* The base implementation of `_.some` without support for callback shorthands
* or `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
/**
* The base implementation of `_.uniq` without support for callback shorthands
* and `this` binding.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The function invoked per iteration.
* @returns {Array} Returns the new duplicate-value-free array.
*/
function baseUniq(array, iteratee) {
var index = -1,
indexOf = getIndexOf(),
length = array.length,
isCommon = indexOf == baseIndexOf,
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;
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* returned by `keysFunc`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
var index = -1,
length = props.length,
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
/**
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to peform to resolve the unwrapped value.
* @returns {*} Returns the resolved unwrapped value.
*/
function baseWrapperValue(value, actions) {
var result = value;
if (result instanceof LazyWrapper) {
result = result.value();
}
var index = -1,
length = actions.length;
while (++index < length) {
var args = [result],
action = actions[index];
push.apply(args, action.args);
result = action.func.apply(action.thisArg, args);
}
return result;
}
/**
* Performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest, instead
* of the lowest, index at which a value should be inserted into `array`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function binaryIndex(array, value, retHighest) {
var low = 0,
high = array ? array.length : low;
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
while (low < high) {
var mid = (low + high) >>> 1,
computed = array[mid];
if (retHighest ? (computed <= value) : (computed < value)) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
return binaryIndexBy(array, value, identity, retHighest);
}
/**
* This function is like `binaryIndex` except that it invokes `iteratee` for
* `value` and each element of `array` to compute their sort ranking. The
* iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The function invoked per iteration.
* @param {boolean} [retHighest] Specify returning the highest, instead
* of the lowest, index at which a value should be inserted into `array`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function binaryIndexBy(array, value, iteratee, retHighest) {
value = iteratee(value);
var low = 0,
high = array ? array.length : 0,
valIsNaN = value !== value,
valIsUndef = typeof value == 'undefined';
while (low < high) {
var mid = floor((low + high) / 2),
computed = iteratee(array[mid]),
isReflexive = computed === computed;
if (valIsNaN) {
var setLow = isReflexive || retHighest;
} else if (valIsUndef) {
setLow = isReflexive && (retHighest || typeof computed != 'undefined');
} else {
setLow = retHighest ? (computed <= value) : (computed < value);
}
if (setLow) {
low = mid + 1;
} else {
high = mid;
}
}
return nativeMin(high, MAX_ARRAY_INDEX);
}
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
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);
};
}
/**
* Creates a clone of the given array buffer.
*
* @private
* @param {ArrayBuffer} buffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function bufferClone(buffer) {
return bufferSlice.call(buffer, 0);
}
if (!bufferSlice) {
// PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`.
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;
};
}
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array|Object} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders) {
var holdersLength = holders.length,
argsIndex = -1,
argsLength = nativeMax(args.length - holdersLength, 0),
leftIndex = -1,
leftLength = partials.length,
result = Array(argsLength + leftLength);
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
result[holders[argsIndex]] = args[argsIndex];
}
while (argsLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array|Object} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders) {
var holdersIndex = -1,
holdersLength = holders.length,
argsIndex = -1,
argsLength = nativeMax(args.length - holdersLength, 0),
rightIndex = -1,
rightLength = partials.length,
result = Array(argsLength + rightLength);
while (++argsIndex < argsLength) {
result[argsIndex] = args[argsIndex];
}
var pad = argsIndex;
while (++rightIndex < rightLength) {
result[pad + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
result[pad + holders[holdersIndex]] = args[argsIndex++];
}
return result;
}
/**
* Creates a function that aggregates a collection, creating an accumulator
* object composed from the results of running each element in the collection
* through an iteratee. The `setter` sets the keys and values of the accumulator
* object. If `initializer` is provided initializes the accumulator object.
*
* @private
* @param {Function} setter The function to set keys and values of the accumulator object.
* @param {Function} [initializer] The function to initialize the accumulator object.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee, thisArg) {
var result = initializer ? initializer() : {};
iteratee = getCallback(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;
};
}
/**
* Creates a function that assigns properties of source object(s) to a given
* destination object.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
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;
}
// Juggle arguments.
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;
};
}
/**
* Creates a function that wraps `func` and invokes it with the `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new bound function.
*/
function createBindWrapper(func, thisArg) {
var Ctor = createCtorWrapper(func);
function wrapper() {
return (this instanceof wrapper ? Ctor : func).apply(thisArg, arguments);
}
return wrapper;
}
/**
* Creates a `Set` cache object to optimize linear searches of large arrays.
*
* @private
* @param {Array} [values] The values to cache.
* @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
*/
var createCache = !(nativeCreate && Set) ? constant(null) : function(values) {
return new SetCache(values);
};
/**
* Creates a function that produces compound words out of the words in a
* given string.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder(callback) {
return function(string) {
var index = -1,
array = words(deburr(string)),
length = array.length,
result = '';
while (++index < length) {
result = callback(result, array[index], index);
}
return result;
};
}
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtorWrapper(Ctor) {
return function() {
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, arguments);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
/**
* Creates a function that gets the extremum value of a collection.
*
* @private
* @param {Function} arrayFunc The function to get the extremum value from an array.
* @param {boolean} [isMin] Specify returning the minimum, instead of the maximum,
* extremum value.
* @returns {Function} Returns the new extremum function.
*/
function createExtremum(arrayFunc, isMin) {
return function(collection, iteratee, thisArg) {
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = null;
}
var func = getCallback(),
noIteratee = iteratee == null;
if (!(func === baseCallback && noIteratee)) {
noIteratee = false;
iteratee = func(iteratee, thisArg, 3);
}
if (noIteratee) {
var isArr = isArray(collection);
if (!isArr && isString(collection)) {
iteratee = charAtCallback;
} else {
return arrayFunc(isArr ? collection : toIterable(collection));
}
}
return extremumBy(collection, iteratee, isMin);
};
}
/**
* Creates a function that wraps `func` and invokes it with optional `this`
* binding of, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & ARY_FLAG,
isBind = bitmask & BIND_FLAG,
isBindKey = bitmask & BIND_KEY_FLAG,
isCurry = bitmask & CURRY_FLAG,
isCurryBound = bitmask & CURRY_BOUND_FLAG,
isCurryRight = bitmask & CURRY_RIGHT_FLAG;
var Ctor = !isBindKey && createCtorWrapper(func),
key = func;
function wrapper() {
// Avoid `arguments` object use disqualifying optimizations by
// converting it to an array before providing it to other functions.
var length = arguments.length,
index = length,
args = Array(length);
while (index--) {
args[index] = arguments[index];
}
if (partials) {
args = composeArgs(args, partials, holders);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight);
}
if (isCurry || isCurryRight) {
var placeholder = wrapper.placeholder,
argsHolders = replaceHolders(args, placeholder);
length -= argsHolders.length;
if (length < arity) {
var newArgPos = argPos ? arrayCopy(argPos) : null,
newArity = nativeMax(arity - length, 0),
newsHolders = isCurry ? argsHolders : null,
newHoldersRight = isCurry ? null : argsHolders,
newPartials = isCurry ? args : null,
newPartialsRight = isCurry ? null : args;
bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
if (!isCurryBound) {
bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
}
var result = createHybridWrapper(func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity);
result.placeholder = placeholder;
return result;
}
}
var thisBinding = isBind ? thisArg : this;
if (isBindKey) {
func = thisBinding[key];
}
if (argPos) {
args = reorder(args, argPos);
}
if (isAry && ary < args.length) {
args.length = ary;
}
return (this instanceof wrapper ? (Ctor || createCtorWrapper(func)) : func).apply(thisBinding, args);
}
return wrapper;
}
/**
* Creates the pad required for `string` based on the given padding length.
* The `chars` string may be truncated if the number of padding characters
* exceeds the padding length.
*
* @private
* @param {string} string The string to create padding for.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the pad for `string`.
*/
function createPad(string, length, chars) {
var strLength = string.length;
length = +length;
if (strLength >= length || !nativeIsFinite(length)) {
return '';
}
var padLength = length - strLength;
chars = chars == null ? ' ' : (chars + '');
return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength);
}
/**
* Creates a function that wraps `func` and invokes it with the optional `this`
* binding of `thisArg` and the `partials` prepended to those provided to
* the wrapper.
*
* @private
* @param {Function} func The function to partially apply arguments to.
* @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to the new function.
* @returns {Function} Returns the new bound function.
*/
function createPartialWrapper(func, bitmask, thisArg, partials) {
var isBind = bitmask & BIND_FLAG,
Ctor = createCtorWrapper(func);
function wrapper() {
// Avoid `arguments` object use disqualifying optimizations by
// converting it to an array before providing it `func`.
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(argsLength + leftLength);
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return (this instanceof wrapper ? Ctor : func).apply(isBind ? thisArg : this, args);
}
return wrapper;
}
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of flags.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & BIND_KEY_FLAG;
if (!isBindKey && !isFunction(func)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
partials = holders = null;
}
length -= (holders ? holders.length : 0);
if (bitmask & PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = null;
}
var data = !isBindKey && getData(func),
newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
if (data && data !== true) {
mergeData(newData, data);
bitmask = newData[1];
arity = newData[9];
}
newData[9] = arity == null
? (isBindKey ? 0 : func.length)
: (nativeMax(arity - length, 0) || 0);
if (bitmask == BIND_FLAG) {
var result = createBindWrapper(newData[0], newData[2]);
} else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
result = createPartialWrapper.apply(null, newData);
} else {
result = createHybridWrapper.apply(null, newData);
}
var setter = data ? baseSetData : setData;
return setter(result, newData);
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing arrays.
* @param {boolean} [isWhere] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
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;
}
// Deep compare the contents, ignoring non-numeric properties.
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') {
// Recursively compare arrays (susceptible to call stack limits).
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;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} value The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag) {
switch (tag) {
case boolTag:
case dateTag:
// 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 +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
return (object != +object)
? other != +other
// But, treat `-0` vs. `+0` as not equal.
: (object == 0 ? ((1 / object) == (1 / other)) : object == +other);
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings primitives and string
// objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
return object == (other + '');
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isWhere] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
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') {
// Recursively compare objects (susceptible to call stack limits).
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;
// Non `Object` object instances with different constructors are not equal.
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;
}
/**
* Gets the extremum value of `collection` invoking `iteratee` for each value
* in `collection` to generate the criterion by which the value is ranked.
* The `iteratee` is invoked with three arguments; (value, index, collection).
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {boolean} [isMin] Specify returning the minimum, instead of the
* maximum, extremum value.
* @returns {*} Returns the extremum value.
*/
function extremumBy(collection, iteratee, isMin) {
var exValue = isMin ? POSITIVE_INFINITY : NEGATIVE_INFINITY,
computed = exValue,
result = computed;
baseEach(collection, function(value, index, collection) {
var current = iteratee(value, index, collection);
if ((isMin ? current < computed : current > computed) || (current === exValue && current === result)) {
computed = current;
result = value;
}
});
return result;
}
/**
* Gets the appropriate "callback" function. If the `_.callback` method is
* customized this function returns the custom method, otherwise it returns
* the `baseCallback` function. If arguments are provided the chosen function
* is invoked with them and its result is returned.
*
* @private
* @returns {Function} Returns the chosen function or its result.
*/
function getCallback(func, thisArg, argCount) {
var result = lodash.callback || callback;
result = result === callback ? baseCallback : result;
return argCount ? result(func, thisArg, argCount) : result;
}
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
/**
* Gets the appropriate "indexOf" function. If the `_.indexOf` method is
* customized this function returns the custom method, otherwise it returns
* the `baseIndexOf` function. If arguments are provided the chosen function
* is invoked with them and its result is returned.
*
* @private
* @returns {Function|number} Returns the chosen function or its result.
*/
function getIndexOf(collection, target, fromIndex) {
var result = lodash.indexOf || indexOf;
result = result === indexOf ? baseIndexOf : result;
return collection ? result(collection, target, fromIndex) : result;
}
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} [transforms] The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms ? transforms.length : 0;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add array properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
var Ctor = object.constructor;
if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
Ctor = Object;
}
return new Ctor;
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
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;
}
/**
* Checks if `func` is eligible for `this` binding.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is eligible, else `false`.
*/
function isBindable(func) {
var support = lodash.support,
result = !(support.funcNames ? func.name : support.funcDecomp);
if (!result) {
var source = fnToString.call(func);
if (!support.funcNames) {
result = !reFuncName.test(source);
}
if (!result) {
// Check if `func` references the `this` keyword and store the result.
result = reThis.test(source) || isNative(func);
baseSetData(func, result);
}
}
return result;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = +value;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
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;
}
/**
* Checks if `value` is a valid array-like length.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value));
}
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers required to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
* augment function arguments, making the order in which they are executed important,
* preventing the merging of metadata. However, we make an exception for a safe
* common case where curried functions have `_.ary` and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask;
var arityFlags = ARY_FLAG | REARG_FLAG,
bindFlags = BIND_FLAG | BIND_KEY_FLAG,
comboFlags = arityFlags | bindFlags | CURRY_BOUND_FLAG | CURRY_RIGHT_FLAG;
var isAry = bitmask & ARY_FLAG && !(srcBitmask & ARY_FLAG),
isRearg = bitmask & REARG_FLAG && !(srcBitmask & REARG_FLAG),
argPos = (isRearg ? data : source)[7],
ary = (isAry ? data : source)[8];
var isCommon = !(bitmask >= REARG_FLAG && srcBitmask > bindFlags) &&
!(bitmask > bindFlags && srcBitmask >= REARG_FLAG);
var isCombo = (newBitmask >= arityFlags && newBitmask <= comboFlags) &&
(bitmask < REARG_FLAG || ((isRearg || isAry) && argPos.length <= ary));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = arrayCopy(value);
}
// Use source `ary` if it's smaller.
if (srcBitmask & ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
/**
* A specialized version of `_.pick` that picks `object` properties specified
* by the `props` array.
*
* @private
* @param {Object} object The source object.
* @param {string[]} props The property names to pick.
* @returns {Object} Returns the new object.
*/
function pickByArray(object, props) {
object = toObject(object);
var index = -1,
length = props.length,
result = {};
while (++index < length) {
var key = props[index];
if (key in object) {
result[key] = object[key];
}
}
return result;
}
/**
* A specialized version of `_.pick` that picks `object` properties `predicate`
* returns truthy for.
*
* @private
* @param {Object} object The source object.
* @param {Function} predicate The function invoked per iteration.
* @returns {Object} Returns the new object.
*/
function pickByCallback(object, predicate) {
var result = {};
baseForIn(object, function(value, key, object) {
if (predicate(value, key, object)) {
result[key] = value;
}
});
return result;
}
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = arrayCopy(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity function
* to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = (function() {
var count = 0,
lastCalled = 0;
return function(key, value) {
var stamp = now(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return key;
}
} else {
count = 0;
}
return baseSetData(key, value);
};
}());
/**
* A fallback implementation of `_.isPlainObject` which checks if `value`
* is an object created by the `Object` constructor or has a `[[Prototype]]`
* of `null`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
*/
function shimIsPlainObject(value) {
var Ctor,
support = lodash.support;
// Exit early for non `Object` objects.
if (!(isObjectLike(value) && objToString.call(value) == objectTag) ||
(!hasOwnProperty.call(value, 'constructor') &&
(Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
var result;
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
baseForIn(value, function(subValue, key) {
result = key;
});
return typeof result == 'undefined' || hasOwnProperty.call(value, result);
}
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length,
support = lodash.support;
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;
}
/**
* Converts `value` to an array-like object if it is not one.
*
* @private
* @param {*} value The value to process.
* @returns {Array|Object} Returns the array-like object.
*/
function toIterable(value) {
if (value == null) {
return [];
}
if (!isLength(value.length)) {
return values(value);
}
return isObject(value) ? value : Object(value);
}
/**
* Converts `value` to an object if it is not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements split into groups the length of `size`.
* If `collection` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to process.
* @param {numer} [size=1] The length of each chunk.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the new array containing chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size, guard) {
if (guard ? isIterateeCall(array, size, guard) : size == null) {
size = 1;
} else {
size = nativeMax(+size || 1, 1);
}
var index = 0,
length = array ? array.length : 0,
resIndex = -1,
result = Array(ceil(length / size));
while (index < length) {
result[++resIndex] = baseSlice(array, index, (index += size));
}
return result;
}
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
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;
}
/**
* Creates an array excluding all values of the provided arrays using
* `SameValueZero` for equality comparisons.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The arrays of values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.difference([1, 2, 3], [5, 2, 10]);
* // => [1, 3]
*/
function difference() {
var index = -1,
length = arguments.length;
while (++index < length) {
var value = arguments[index];
if (isArray(value) || isArguments(value)) {
break;
}
}
return baseDifference(value, baseFlatten(arguments, false, true, ++index));
}
/**
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @type Function
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function drop(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (guard ? isIterateeCall(array, n, guard) : n == null) {
n = 1;
}
return baseSlice(array, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @type Function
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function dropRight(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (guard ? isIterateeCall(array, n, guard) : n == null) {
n = 1;
}
n = length - (+n || 0);
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* bound to `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @type Function
* @category Array
* @param {Array} array The array to query.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per element.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRightWhile([1, 2, 3], function(n) { return n > 1; });
* // => [1]
*
* var users = [
* { 'user': 'barney', 'status': 'busy', 'active': false },
* { 'user': 'fred', 'status': 'busy', 'active': true },
* { 'user': 'pebbles', 'status': 'away', 'active': true }
* ];
*
* // using the "_.property" callback shorthand
* _.pluck(_.dropRightWhile(users, 'active'), 'user');
* // => ['barney']
*
* // using the "_.matches" callback shorthand
* _.pluck(_.dropRightWhile(users, { 'status': 'away' }), 'user');
* // => ['barney', 'fred']
*/
function dropRightWhile(array, predicate, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
predicate = getCallback(predicate, thisArg, 3);
while (length-- && predicate(array[length], length, array)) {}
return baseSlice(array, 0, length + 1);
}
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* bound to `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @type Function
* @category Array
* @param {Array} array The array to query.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per element.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropWhile([1, 2, 3], function(n) { return n < 3; });
* // => [3]
*
* var users = [
* { 'user': 'barney', 'status': 'busy', 'active': true },
* { 'user': 'fred', 'status': 'busy', 'active': false },
* { 'user': 'pebbles', 'status': 'away', 'active': true }
* ];
*
* // using the "_.property" callback shorthand
* _.pluck(_.dropWhile(users, 'active'), 'user');
* // => ['fred', 'pebbles']
*
* // using the "_.matches" callback shorthand
* _.pluck(_.dropWhile(users, { 'status': 'busy' }), 'user');
* // => ['pebbles']
*/
function dropWhile(array, predicate, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
var index = -1;
predicate = getCallback(predicate, thisArg, 3);
while (++index < length && predicate(array[index], index, array)) {}
return baseSlice(array, index);
}
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for, instead of the element itself.
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.findIndex(users, function(chr) { return chr.age < 40; });
* // => 0
*
* // using the "_.matches" callback shorthand
* _.findIndex(users, { 'age': 1 });
* // => 2
*
* // using the "_.property" callback shorthand
* _.findIndex(users, 'active');
* // => 1
*/
function findIndex(array, predicate, thisArg) {
var index = -1,
length = array ? array.length : 0;
predicate = getCallback(predicate, thisArg, 3);
while (++index < length) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.findLastIndex(users, function(chr) { return chr.age < 40; });
* // => 2
*
* // using the "_.matches" callback shorthand
* _.findLastIndex(users, { 'age': 40 });
* // => 1
*
* // using the "_.property" callback shorthand
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, thisArg) {
var length = array ? array.length : 0;
predicate = getCallback(predicate, thisArg, 3);
while (length--) {
if (predicate(array[length], length, array)) {
return length;
}
}
return -1;
}
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @alias head
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.first([1, 2, 3]);
* // => 1
*
* _.first([]);
* // => undefined
*/
function first(array) {
return array ? array[0] : undefined;
}
/**
* Flattens a nested array. If `isDeep` is `true` the array is recursively
* flattened, otherwise it is only flattened a single level.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to flatten.
* @param {boolean} [isDeep] Specify a deep flatten.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, [[4]]];
*
* // using `isDeep`
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, 4];
*/
function flatten(array, isDeep, guard) {
var length = array ? array.length : 0;
if (guard && isIterateeCall(array, isDeep, guard)) {
isDeep = false;
}
return length ? baseFlatten(array, isDeep) : [];
}
/**
* Recursively flattens a nested array.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to recursively flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*/
function flattenDeep(array) {
var length = array ? array.length : 0;
return length ? baseFlatten(array, true) : [];
}
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using `SameValueZero` for equality comparisons. If `fromIndex` is negative,
* it is used as the offset from the end of `array`. If `array` is sorted
* providing `true` for `fromIndex` performs a faster binary search.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
* to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* // using `fromIndex`
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
*
* // performing a binary search
* _.indexOf([4, 4, 5, 5, 6, 6], 5, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
if (typeof fromIndex == 'number') {
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
} else if (fromIndex) {
var index = binaryIndex(array, value),
other = array[index];
return (value === value ? value === other : other !== other) ? index : -1;
}
return baseIndexOf(array, value, fromIndex);
}
/**
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*/
function initial(array) {
return dropRight(array, 1);
}
/**
* Creates an array of unique values in all provided arrays using `SameValueZero`
* for equality comparisons.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of shared values.
* @example
*
* _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
* // => [1, 2]
*/
function intersection() {
var args = [],
argsIndex = -1,
argsLength = arguments.length,
caches = [],
indexOf = getIndexOf(),
isCommon = indexOf == baseIndexOf;
while (++argsIndex < argsLength) {
var value = arguments[argsIndex];
if (isArray(value) || isArguments(value)) {
args.push(value);
caches.push(isCommon && value.length >= 120 && createCache(argsIndex && value));
}
}
argsLength = args.length;
var array = args[0],
index = -1,
length = array ? array.length : 0,
result = [],
seen = caches[0];
outer:
while (++index < length) {
value = array[index];
if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value)) < 0) {
argsIndex = argsLength;
while (--argsIndex) {
var cache = caches[argsIndex];
if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
continue outer;
}
}
if (seen) {
seen.push(value);
}
result.push(value);
}
}
return result;
}
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array ? array.length : 0;
return length ? array[length - 1] : undefined;
}
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {boolean|number} [fromIndex=array.length-1] The index to search from
* or `true` to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
* // => 4
*
* // using `fromIndex`
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 1
*
* // performing a binary search
* _.lastIndexOf([4, 4, 5, 5, 6, 6], 5, true);
* // => 3
*/
function lastIndexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
var index = length;
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
} else if (fromIndex) {
index = binaryIndex(array, value, true) - 1;
var other = array[index];
return (value === value ? value === other : other !== other) ? index : -1;
}
if (value !== value) {
return indexOfNaN(array, index, true);
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Removes all provided values from `array` using `SameValueZero` for equality
* comparisons.
*
* **Notes:**
* - Unlike `_.without`, this method mutates `array`.
* - `SameValueZero` comparisons are like strict equality comparisons, e.g. `===`,
* except that `NaN` matches `NaN`. See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3, 1, 2, 3];
* _.pull(array, 2, 3);
* console.log(array);
* // => [1, 1]
*/
function pull() {
var array = arguments[0];
if (!(array && array.length)) {
return array;
}
var index = 0,
indexOf = getIndexOf(),
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;
}
/**
* Removes elements from `array` corresponding to the given indexes and returns
* an array of the removed elements. Indexes may be specified as an array of
* indexes or as individual arguments.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove,
* specified as individual indexes or arrays of indexes.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [5, 10, 15, 20];
* var evens = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => [5, 15]
*
* console.log(evens);
* // => [10, 20]
*/
function pullAt(array) {
return basePullAt(array || [], baseFlatten(arguments, false, false, 1));
}
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is bound to
* `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* **Note:** Unlike `_.filter`, this method mutates `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) { return n % 2 == 0; });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate, thisArg) {
var index = -1,
length = array ? array.length : 0,
result = [];
predicate = getCallback(predicate, thisArg, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
splice.call(array, index--, 1);
length--;
}
}
return result;
}
/**
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @alias tail
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.rest([1, 2, 3]);
* // => [2, 3]
*/
function rest(array) {
return drop(array, 1);
}
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This function is used instead of `Array#slice` to support node
* lists in IE < 9 and to ensure dense arrays are returned.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function slice(array, start, end) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
return baseSlice(array, start, end);
}
/**
* Uses a binary search to determine the lowest index at which `value` should
* be inserted into `array` in order to maintain its sort order. If an iteratee
* function is provided it is invoked for `value` and each element of `array`
* to compute their sort ranking. The iteratee is bound to `thisArg` and
* invoked with one argument; (value).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*
* _.sortedIndex([4, 4, 5, 5, 6, 6], 5);
* // => 2
*
* var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
*
* // using an iteratee function
* _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
* return this.data[word];
* }, dict);
* // => 1
*
* // using the "_.property" callback shorthand
* _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
* // => 1
*/
function sortedIndex(array, value, iteratee, thisArg) {
var func = getCallback(iteratee);
return (func === baseCallback && iteratee == null)
? binaryIndex(array, value)
: binaryIndexBy(array, value, func(iteratee, thisArg, 1));
}
/**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 4, 5, 5, 6, 6], 5);
* // => 4
*/
function sortedLastIndex(array, value, iteratee, thisArg) {
var func = getCallback(iteratee);
return (func === baseCallback && iteratee == null)
? binaryIndex(array, value, true)
: binaryIndexBy(array, value, func(iteratee, thisArg, 1), true);
}
/**
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @type Function
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
*/
function take(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (guard ? isIterateeCall(array, n, guard) : n == null) {
n = 1;
}
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @type Function
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/
function takeRight(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (guard ? isIterateeCall(array, n, guard) : n == null) {
n = 1;
}
n = length - (+n || 0);
return baseSlice(array, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is bound to `thisArg`
* and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @type Function
* @category Array
* @param {Array} array The array to query.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per element.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRightWhile([1, 2, 3], function(n) { return n > 1; });
* // => [2, 3]
*
* var users = [
* { 'user': 'barney', 'status': 'busy', 'active': false },
* { 'user': 'fred', 'status': 'busy', 'active': true },
* { 'user': 'pebbles', 'status': 'away', 'active': true }
* ];
*
* // using the "_.property" callback shorthand
* _.pluck(_.takeRightWhile(users, 'active'), 'user');
* // => ['fred', 'pebbles']
*
* // using the "_.matches" callback shorthand
* _.pluck(_.takeRightWhile(users, { 'status': 'away' }), 'user');
* // => ['pebbles']
*/
function takeRightWhile(array, predicate, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
predicate = getCallback(predicate, thisArg, 3);
while (length-- && predicate(array[length], length, array)) {}
return baseSlice(array, length + 1);
}
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is bound to
* `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @type Function
* @category Array
* @param {Array} array The array to query.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per element.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeWhile([1, 2, 3], function(n) { return n < 3; });
* // => [1, 2]
*
* var users = [
* { 'user': 'barney', 'status': 'busy', 'active': true },
* { 'user': 'fred', 'status': 'busy', 'active': false },
* { 'user': 'pebbles', 'status': 'away', 'active': true }
* ];
*
* // using the "_.property" callback shorthand
* _.pluck(_.takeWhile(users, 'active'), 'user');
* // => ['barney']
*
* // using the "_.matches" callback shorthand
* _.pluck(_.takeWhile(users, { 'status': 'busy' }), 'user');
* // => ['barney', 'fred']
*/
function takeWhile(array, predicate, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
var index = -1;
predicate = getCallback(predicate, thisArg, 3);
while (++index < length && predicate(array[index], index, array)) {}
return baseSlice(array, 0, index);
}
/**
* Creates an array of unique values, in order, of the provided arrays using
* `SameValueZero` for equality comparisons.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
* // => [1, 2, 3, 5, 4]
*/
function union() {
return baseUniq(baseFlatten(arguments, false, true));
}
/**
* Creates a duplicate-value-free version of an array using `SameValueZero`
* for equality comparisons. Providing `true` for `isSorted` performs a faster
* search algorithm for sorted arrays. If an iteratee function is provided it
* is invoked for each value in the array to generate the criterion by which
* uniqueness is computed. The `iteratee` is bound to `thisArg` and invoked
* with three arguments; (value, index, array).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @alias unique
* @category Array
* @param {Array} array The array to inspect.
* @param {boolean} [isSorted] Specify the array is sorted.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* If a property name or object is provided it is used to create a "_.property"
* or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new duplicate-value-free array.
* @example
*
* _.uniq([1, 2, 1]);
* // => [1, 2]
*
* // using `isSorted`
* _.uniq([1, 1, 2], true);
* // => [1, 2]
*
* // using an iteratee function
* _.uniq([1, 2.5, 1.5, 2], function(n) { return this.floor(n); }, Math);
* // => [1, 2.5]
*
* // using the "_.property" callback shorthand
* _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniq(array, isSorted, iteratee, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
// Juggle arguments.
if (typeof isSorted != 'boolean' && isSorted != null) {
thisArg = iteratee;
iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted;
isSorted = false;
}
var func = getCallback();
if (!(func === baseCallback && iteratee == null)) {
iteratee = func(iteratee, thisArg, 3);
}
return (isSorted && getIndexOf() == baseIndexOf)
? sortedUniq(array, iteratee)
: baseUniq(array, iteratee);
}
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-`_.zip`
* configuration.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*
* _.unzip(zipped);
* // => [['fred', 'barney'], [30, 40], [true, false]]
*/
function unzip(array) {
var index = -1,
length = (array && array.length && arrayMax(arrayMap(array, getLength))) >>> 0,
result = Array(length);
while (++index < length) {
result[index] = arrayMap(array, baseProperty(index));
}
return result;
}
/**
* Creates an array excluding all provided values using `SameValueZero` for
* equality comparisons.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to filter.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
* // => [2, 3, 4]
*/
function without(array) {
return baseDifference(array, baseSlice(arguments, 1));
}
/**
* Creates an array that is the symmetric difference of the provided arrays.
* See [Wikipedia](https://en.wikipedia.org/wiki/Symmetric_difference) for
* more details.
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of values.
* @example
*
* _.xor([1, 2, 3], [5, 2, 1, 4]);
* // => [3, 5, 4]
*
* _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
* // => [1, 4, 5]
*/
function xor() {
var index = -1,
length = arguments.length;
while (++index < length) {
var array = arguments[index];
if (isArray(array) || isArguments(array)) {
var result = result
? baseDifference(result, array).concat(baseDifference(array, result))
: array;
}
}
return result ? baseUniq(result) : [];
}
/**
* Creates an array of grouped elements, the first of which contains the first
* elements of the given arrays, the second of which contains the second elements
* of the given arrays, and so on.
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*/
function zip() {
var length = arguments.length,
array = Array(length);
while (length--) {
array[length] = arguments[length];
}
return unzip(array);
}
/**
* Creates an object composed from arrays of property names and values. Provide
* either a single two dimensional array, e.g. `[[key1, value1], [key2, value2]]`
* or two arrays, one of property names and one of corresponding values.
*
* @static
* @memberOf _
* @alias object
* @category Array
* @param {Array} props The property names.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject(['fred', 'barney'], [30, 40]);
* // => { 'fred': 30, 'barney': 40 }
*/
function zipObject(props, values) {
var index = -1,
length = props ? props.length : 0,
result = {};
if (length && !values && !isArray(props[0])) {
values = [];
}
while (++index < length) {
var key = props[index];
if (values) {
result[key] = values[index];
} else if (key) {
result[key[0]] = key[1];
}
}
return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object that wraps `value` with explicit method
* chaining enabled.
*
* @static
* @memberOf _
* @category Chain
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` object.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _.chain(users)
* .sortBy('age')
* .map(function(chr) { return chr.user + ' is ' + chr.age; })
* .first()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
var result = lodash(value);
result.__chain__ = true;
return result;
}
/**
* This method invokes `interceptor` and returns `value`. The interceptor is
* bound to `thisArg` and invoked with one argument; (value). The purpose of
* this method is to "tap into" a method chain in order to perform operations
* on intermediate results within the chain.
*
* @static
* @memberOf _
* @category Chain
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @param {*} [thisArg] The `this` binding of `interceptor`.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) { array.pop(); })
* .reverse()
* .value();
* // => [2, 1]
*/
function tap(value, interceptor, thisArg) {
interceptor.call(thisArg, value);
return value;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
*
* @static
* @memberOf _
* @category Chain
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @param {*} [thisArg] The `this` binding of `interceptor`.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _([1, 2, 3])
* .last()
* .thru(function(value) { return [value]; })
* .value();
* // => [3]
*/
function thru(value, interceptor, thisArg) {
return interceptor.call(thisArg, value);
}
/**
* Enables explicit method chaining on the wrapper object.
*
* @name chain
* @memberOf _
* @category Chain
* @returns {*} Returns the `lodash` object.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // without explicit chaining
* _(users).first();
* // => { 'user': 'barney', 'age': 36 }
*
* // with explicit chaining
* _(users).chain()
* .first()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*/
function wrapperChain() {
return chain(this);
}
/**
* Reverses the wrapped array so the first element becomes the last, the
* second element becomes the second to last, and so on.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @category Chain
* @returns {Object} Returns the new reversed `lodash` object.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
if (this.__actions__.length) {
value = new LazyWrapper(this);
}
return new LodashWrapper(value.reverse());
}
return this.thru(function(value) {
return value.reverse();
});
}
/**
* Produces the result of coercing the unwrapped value to a string.
*
* @name toString
* @memberOf _
* @category Chain
* @returns {string} Returns the coerced string value.
* @example
*
* _([1, 2, 3]).toString();
* // => '1,2,3'
*/
function wrapperToString() {
return (this.value() + '');
}
/**
* Executes the chained sequence to extract the unwrapped value.
*
* @name value
* @memberOf _
* @alias toJSON, valueOf
* @category Chain
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements corresponding to the given keys, or indexes,
* of `collection`. Keys may be specified as individual arguments or as arrays
* of keys.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {...(number|number[]|string|string[])} [props] The property names
* or indexes of elements to pick, specified individually or in arrays.
* @returns {Array} Returns the new array of picked elements.
* @example
*
* _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
* // => ['a', 'c', 'e']
*
* _.at(['fred', 'barney', 'pebbles'], 0, 2);
* // => ['fred', 'pebbles']
*/
function at(collection) {
var length = collection ? collection.length : 0;
if (isLength(length)) {
collection = toIterable(collection);
}
return baseAt(collection, baseFlatten(arguments, false, false, 1));
}
/**
* Checks if `value` is in `collection` using `SameValueZero` for equality
* comparisons. If `fromIndex` is negative, it is used as the offset from
* the end of `collection`.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @alias contains, include
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {*} target The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {boolean} Returns `true` if a matching element is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
* // => true
*
* _.includes('pebbles', 'eb');
* // => true
*/
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)
: (getIndexOf(collection, target, fromIndex) > -1);
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is the number of times the key was returned by `iteratee`.
* The `iteratee` is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(n) { return Math.floor(n); });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(n) { return this.floor(n); }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
});
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* The predicate is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias all
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes']);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // using the "_.property" callback shorthand
* _.every(users, 'age');
* // => true
*
* // using the "_.matches" callback shorthand
* _.every(users, { 'age': 36 });
* // => false
*/
function every(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (typeof predicate != 'function' || typeof thisArg != 'undefined') {
predicate = getCallback(predicate, thisArg, 3);
}
return func(collection, predicate);
}
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias select
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new filtered array.
* @example
*
* var evens = _.filter([1, 2, 3, 4], function(n) { return n % 2 == 0; });
* // => [2, 4]
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* // using the "_.property" callback shorthand
* _.pluck(_.filter(users, 'active'), 'user');
* // => ['fred']
*
* // using the "_.matches" callback shorthand
* _.pluck(_.filter(users, { 'age': 36 }), 'user');
* // => ['barney']
*/
function filter(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayFilter : baseFilter;
predicate = getCallback(predicate, thisArg, 3);
return func(collection, predicate);
}
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias detect
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.result(_.find(users, function(chr) { return chr.age < 40; }), 'user');
* // => 'barney'
*
* // using the "_.matches" callback shorthand
* _.result(_.find(users, { 'age': 1 }), 'user');
* // => 'pebbles'
*
* // using the "_.property" callback shorthand
* _.result(_.find(users, 'active'), 'user');
* // => 'fred'
*/
function find(collection, predicate, thisArg) {
if (isArray(collection)) {
var index = findIndex(collection, predicate, thisArg);
return index > -1 ? collection[index] : undefined;
}
predicate = getCallback(predicate, thisArg, 3);
return baseFind(collection, predicate, baseEach);
}
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) { return n % 2 == 1; });
* // => 3
*/
function findLast(collection, predicate, thisArg) {
predicate = getCallback(predicate, thisArg, 3);
return baseFind(collection, predicate, baseEachRight);
}
/**
* Performs a deep comparison between each element in `collection` and the
* source object, returning the first element that has equivalent property
* values.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Object} source The object of property values to match.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'status': 'busy' },
* { 'user': 'fred', 'age': 40, 'status': 'busy' }
* ];
*
* _.result(_.findWhere(users, { 'status': 'busy' }), 'user');
* // => 'barney'
*
* _.result(_.findWhere(users, { 'age': 40 }), 'user');
* // => 'fred'
*/
function findWhere(collection, source) {
return find(collection, matches(source));
}
/**
* Iterates over elements of `collection` invoking `iteratee` for each element.
* The `iteratee` is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection). Iterator functions may exit iteration early
* by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a `length` property
* are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
* may be used for object iteration.
*
* @static
* @memberOf _
* @alias each
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEach(function(n) { console.log(n); }).value();
* // => logs each value from left to right and returns the array
*
* _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(n, key) { console.log(n, key); });
* // => logs each value-key pair and returns the object (iteration order is not guaranteed)
*/
function forEach(collection, iteratee, thisArg) {
return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection))
? arrayEach(collection, iteratee)
: baseEach(collection, bindCallback(iteratee, thisArg, 3));
}
/**
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @alias eachRight
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEachRight(function(n) { console.log(n); }).join(',');
* // => logs each value from right to left and returns the array
*/
function forEachRight(collection, iteratee, thisArg) {
return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection))
? arrayEachRight(collection, iteratee)
: baseEachRight(collection, bindCallback(iteratee, thisArg, 3));
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is an array of the elements responsible for generating the key.
* The `iteratee` is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([4.2, 6.1, 6.4], function(n) { return Math.floor(n); });
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* _.groupBy([4.2, 6.1, 6.4], function(n) { return this.floor(n); }, Math);
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* // using the "_.property" callback shorthand
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
result[key] = [value];
}
});
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is the last element responsible for generating the key. The
* iteratee function is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var keyData = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.indexBy(keyData, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(keyData, function(object) { return String.fromCharCode(object.code); });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(keyData, function(object) { return this.fromCharCode(object.code); }, String);
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*/
var indexBy = createAggregator(function(result, value, key) {
result[key] = value;
});
/**
* Invokes the method named by `methodName` on each element in `collection`,
* returning an array of the results of each invoked method. Any additional
* arguments are provided to each invoked method. If `methodName` is a function
* it is invoked for, and `this` bound to, each element in `collection`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|string} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Array} Returns the array of results.
* @example
*
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invoke([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
function invoke(collection, methodName) {
return baseInvoke(collection, methodName, baseSlice(arguments, 2));
}
/**
* Creates an array of values by running each element in `collection` through
* `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias collect
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new mapped array.
* @example
*
* _.map([1, 2, 3], function(n) { return n * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(n) { return n * 3; });
* // => [3, 6, 9] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // using the "_.property" callback shorthand
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee, thisArg) {
var func = isArray(collection) ? arrayMap : baseMap;
iteratee = getCallback(iteratee, thisArg, 3);
return func(collection, iteratee);
}
/**
* Gets the maximum value of `collection`. If `collection` is empty or falsey
* `-Infinity` is returned. If an iteratee function is provided it is invoked
* for each value in `collection` to generate the criterion by which the value
* is ranked. The `iteratee` is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* If a property name or object is provided it is used to create a "_.property"
* or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => -Infinity
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* _.max(users, function(chr) { return chr.age; });
* // => { 'user': 'fred', 'age': 40 };
*
* // using the "_.property" callback shorthand
* _.max(users, 'age');
* // => { 'user': 'fred', 'age': 40 };
*/
var max = createExtremum(arrayMax);
/**
* Gets the minimum value of `collection`. If `collection` is empty or falsey
* `Infinity` is returned. If an iteratee function is provided it is invoked
* for each value in `collection` to generate the criterion by which the value
* is ranked. The `iteratee` is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* If a property name or object is provided it is used to create a "_.property"
* or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => Infinity
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* _.min(users, function(chr) { return chr.age; });
* // => { 'user': 'barney', 'age': 36 };
*
* // using the "_.property" callback shorthand
* _.min(users, 'age');
* // => { 'user': 'barney', 'age': 36 };
*/
var min = createExtremum(arrayMin, true);
/**
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, while the second of which
* contains elements `predicate` returns falsey for. The predicate is bound
* to `thisArg` and invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the array of grouped elements.
* @example
*
* _.partition([1, 2, 3], function(n) { return n % 2; });
* // => [[1, 3], [2]]
*
* _.partition([1.2, 2.3, 3.4], function(n) { return this.floor(n) % 2; }, Math);
* // => [[1, 3], [2]]
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* // using the "_.matches" callback shorthand
* _.map(_.partition(users, { 'age': 1 }), function(array) { return _.pluck(array, 'user'); });
* // => [['pebbles'], ['barney', 'fred']]
*
* // using the "_.property" callback shorthand
* _.map(_.partition(users, 'active'), function(array) { return _.pluck(array, 'user'); });
* // => [['fred'], ['barney', 'pebbles']]
*/
var partition = createAggregator(function(result, value, key) {
result[key ? 0 : 1].push(value);
}, function() { return [[], []]; });
/**
* Gets the value of `key` from all elements in `collection`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {string} key The key of the property to pluck.
* @returns {Array} Returns the property values.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* _.pluck(users, 'user');
* // => ['barney', 'fred']
*
* var userIndex = _.indexBy(users, 'user');
* _.pluck(userIndex, 'age');
* // => [36, 40] (iteration order is not guaranteed)
*/
function pluck(collection, key) {
return map(collection, property(key));
}
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` through `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not provided the first element of `collection` is used as the initial
* value. The `iteratee` is bound to `thisArg`and invoked with four arguments;
* (accumulator, value, index|key, collection).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(sum, n) { return sum + n; });
* // => 6
*
* var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, n, key) {
* result[key] = n * 3;
* return result;
* }, {});
* // => { 'a': 3, 'b': 6, 'c': 9 } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator, thisArg) {
var func = isArray(collection) ? arrayReduce : baseReduce;
return func(collection, getCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEach);
}
/**
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @alias foldr
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
* _.reduceRight(array, function(flattened, other) { return flattened.concat(other); }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, iteratee, accumulator, thisArg) {
var func = isArray(collection) ? arrayReduceRight : baseReduce;
return func(collection, getCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEachRight);
}
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new filtered array.
* @example
*
* var odds = _.reject([1, 2, 3, 4], function(n) { return n % 2 == 0; });
* // => [1, 3]
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* // using the "_.property" callback shorthand
* _.pluck(_.reject(users, 'active'), 'user');
* // => ['barney']
*
* // using the "_.matches" callback shorthand
* _.pluck(_.reject(users, { 'age': 36 }), 'user');
* // => ['fred']
*/
function reject(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayFilter : baseFilter;
predicate = getCallback(predicate, thisArg, 3);
return func(collection, function(value, index, collection) {
return !predicate(value, index, collection);
});
}
/**
* Gets a random element or `n` random elements from a collection.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to sample.
* @param {number} [n] The number of elements to sample.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {*} Returns the random sample(s).
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*
* _.sample([1, 2, 3, 4], 2);
* // => [3, 1]
*/
function sample(collection, n, guard) {
if (guard ? isIterateeCall(collection, n, guard) : n == null) {
collection = toIterable(collection);
var length = collection.length;
return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
}
var result = shuffle(collection);
result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length);
return result;
}
/**
* Creates an array of shuffled values, using a version of the Fisher-Yates
* shuffle. See [Wikipedia](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle)
* for more details.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
collection = toIterable(collection);
var index = -1,
length = collection.length,
result = Array(length);
while (++index < length) {
var rand = baseRandom(0, index);
if (index != rand) {
result[index] = result[rand];
}
result[rand] = collection[index];
}
return result;
}
/**
* Gets the size of `collection` by returning `collection.length` for
* array-like values or the number of own enumerable properties for objects.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the size of `collection`.
* @example
*
* _.size([1, 2]);
* // => 2
*
* _.size({ 'one': 1, 'two': 2, 'three': 3 });
* // => 3
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
var length = collection ? collection.length : 0;
return isLength(length) ? length : keys(collection).length;
}
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* The function returns as soon as it finds a passing value and does not iterate
* over the entire collection. The predicate is bound to `thisArg` and invoked
* with three arguments; (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias any
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* // using the "_.property" callback shorthand
* _.some(users, 'active');
* // => true
*
* // using the "_.matches" callback shorthand
* _.some(users, { 'age': 1 });
* // => false
*/
function some(collection, predicate, thisArg) {
var func = isArray(collection) ? arraySome : baseSome;
if (typeof predicate != 'function' || typeof thisArg != 'undefined') {
predicate = getCallback(predicate, thisArg, 3);
}
return func(collection, predicate);
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection through `iteratee`. This method performs
* a stable sort, that is, it preserves the original sort order of equal elements.
* The `iteratee` is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Array|Function|Object|string} [iteratee=_.identity] The function
* invoked per iteration. If a property name or an object is provided it is
* used to create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new sorted array.
* @example
*
* _.sortBy([1, 2, 3], function(n) { return Math.sin(n); });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(n) { return this.sin(n); }, Math);
* // => [3, 1, 2]
*
* var users = [
* { 'user': 'fred' },
* { 'user': 'pebbles' },
* { 'user': 'barney' }
* ];
*
* // using the "_.property" callback shorthand
* _.pluck(_.sortBy(users, 'user'), 'user');
* // => ['barney', 'fred', 'pebbles']
*/
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 = getCallback(iteratee, thisArg, 3);
baseEach(collection, function(value, key, collection) {
result[++index] = { 'criteria': iteratee(value, key, collection), 'index': index, 'value': value };
});
return baseSortBy(result, compareAscending);
}
/**
* This method is like `_.sortBy` except that it sorts by property names
* instead of an iteratee function.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {...(string|string[])} props The property names to sort by,
* specified as individual property names or arrays of property names.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 26 },
* { 'user': 'fred', 'age': 30 }
* ];
*
* _.map(_.sortByAll(users, ['user', 'age']), _.values);
* // => [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
*/
function sortByAll(collection) {
var args = arguments;
if (args.length > 3 && isIterateeCall(args[1], args[2], args[3])) {
args = [collection, args[1]];
}
var index = -1,
length = collection ? collection.length : 0,
props = baseFlatten(args, false, false, 1),
result = isLength(length) ? Array(length) : [];
baseEach(collection, function(value, key, collection) {
var length = props.length,
criteria = Array(length);
while (length--) {
criteria[length] = value == null ? undefined : value[props[length]];
}
result[++index] = { 'criteria': criteria, 'index': index, 'value': value };
});
return baseSortBy(result, compareMultipleAscending);
}
/**
* Performs a deep comparison between each element in `collection` and the
* source object, returning an array of all elements that have equivalent
* property values.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Object} source The object of property values to match.
* @returns {Array} Returns the new filtered array.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'status': 'busy', 'pets': ['hoppy'] },
* { 'user': 'fred', 'age': 40, 'status': 'busy', 'pets': ['baby puss', 'dino'] }
* ];
*
* _.pluck(_.where(users, { 'age': 36 }), 'user');
* // => ['barney']
*
* _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
* // => ['fred']
*
* _.pluck(_.where(users, { 'status': 'busy' }), 'user');
* // => ['barney', 'fred']
*/
function where(collection, source) {
return filter(collection, matches(source));
}
/*------------------------------------------------------------------------*/
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Date
* @example
*
* _.defer(function(stamp) { console.log(_.now() - stamp); }, _.now());
* // => logs the number of milliseconds it took for the deferred function to be invoked
*/
var now = nativeNow || function() {
return new Date().getTime();
};
/*------------------------------------------------------------------------*/
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it is called `n` or more times.
*
* @static
* @memberOf _
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => logs 'done saving!' after the two async saves have completed
*/
function after(n, func) {
if (!isFunction(func)) {
if (isFunction(n)) {
var temp = n;
n = func;
func = temp;
} else {
throw new TypeError(FUNC_ERROR_TEXT);
}
}
n = nativeIsFinite(n = +n) ? n : 0;
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that accepts up to `n` arguments ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the new function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
if (guard && isIterateeCall(func, n, guard)) {
n = null;
}
n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
return createWrapper(func, ARY_FLAG, null, null, null, null, n);
}
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it is called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery('#add').on('click', _.before(5, addContactToList));
* // => allows adding up to 4 contacts to the list
*/
function before(n, func) {
var result;
if (!isFunction(func)) {
if (isFunction(n)) {
var temp = n;
n = func;
func = temp;
} else {
throw new TypeError(FUNC_ERROR_TEXT);
}
}
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
} else {
func = null;
}
return result;
};
}
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and prepends any additional `_.bind` arguments to those provided to the
* bound function.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind` this method does not set the `length`
* property of bound functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [args] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var greet = function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* };
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // using placeholders
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
function bind(func, thisArg) {
var bitmask = BIND_FLAG;
if (arguments.length > 2) {
var partials = baseSlice(arguments, 2),
holders = replaceHolders(partials, bind.placeholder);
bitmask |= PARTIAL_FLAG;
}
return createWrapper(func, bitmask, thisArg, partials, holders);
}
/**
* Binds methods of an object to the object itself, overwriting the existing
* method. Method names may be specified as individual arguments or as arrays
* of method names. If no method names are provided all enumerable function
* properties, own and inherited, of `object` are bound.
*
* **Note:** This method does not set the `length` property of bound functions.
*
* @static
* @memberOf _
* @category Function
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} [methodNames] The object method names to bind,
* specified as individual method names or arrays of method names.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'onClick': function() { console.log('clicked ' + this.label); }
* };
*
* _.bindAll(view);
* jQuery('#docs').on('click', view.onClick);
* // => logs 'clicked docs' when the element is clicked
*/
function bindAll(object) {
return baseBindAll(object,
arguments.length > 1
? baseFlatten(arguments, false, false, 1)
: functions(object)
);
}
/**
* Creates a function that invokes the method at `object[key]` and prepends
* any additional `_.bindKey` arguments to those provided to the bound function.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist.
* See [Peter Michaux's article](http://michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @category Function
* @param {Object} object The object the method belongs to.
* @param {string} key The key of the method.
* @param {...*} [args] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // using placeholders
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
function bindKey(object, key) {
var bitmask = BIND_FLAG | BIND_KEY_FLAG;
if (arguments.length > 2) {
var partials = baseSlice(arguments, 2),
holders = replaceHolders(partials, bindKey.placeholder);
bitmask |= PARTIAL_FLAG;
}
return createWrapper(key, bitmask, object, partials, holders);
}
/**
* Creates a function that accepts one or more arguments of `func` that when
* called either invokes `func` returning its result, if all `func` arguments
* have been provided, or returns a function that accepts one or more of the
* remaining `func` arguments, and so on. The arity of `func` may be specified
* if `func.length` is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method does not set the `length` property of curried functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // using placeholders
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
if (guard && isIterateeCall(func, arity, guard)) {
arity = null;
}
var result = createWrapper(func, CURRY_FLAG, null, null, null, null, null, arity);
result.placeholder = curry.placeholder;
return result;
}
/**
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method does not set the `length` property of curried functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // using placeholders
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
function curryRight(func, arity, guard) {
if (guard && isIterateeCall(func, arity, guard)) {
arity = null;
}
var result = createWrapper(func, CURRY_RIGHT_FLAG, null, null, null, null, null, arity);
result.placeholder = curryRight.placeholder;
return result;
}
/**
* Creates a function that delays invoking `func` until after `wait` milliseconds
* have elapsed since the last time it was invoked. The created function comes
* with a `cancel` method to cancel delayed invocations. Provide an options
* object to indicate that `func` should be invoked on the leading and/or
* trailing edge of the `wait` timeout. Subsequent calls to the debounced
* function return the result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to debounce.
* @param {number} wait The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it is invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // ensure `batchLog` is invoked once after 1 second of debounced calls
* var source = new EventSource('/stream');
* jQuery(source).on('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }));
*
* // cancel a debounced call
* var todoChanges = _.debounce(batchLog, 1000);
* Object.observe(models.todo, todoChanges);
*
* Object.observe(models, function(changes) {
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
* todoChanges.cancel();
* }
* }, ['delete']);
*
* // ...at some point `models.todo` is changed
* models.todo.completed = true;
*
* // ...before 1 second has passed `models.todo` is deleted
* // which cancels the debounced `todoChanges` call
* delete models.todo;
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (!isFunction(func)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = wait < 0 ? 0 : wait;
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? options.trailing : trailing;
}
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
var isCalled = trailingCall;
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
if (timeoutId) {
clearTimeout(timeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (trailing || (maxWait !== wait)) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
}
function debounced() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0 || remaining > maxWait;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
return result;
}
debounced.cancel = cancel;
return debounced;
}
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) { console.log(text); }, 'deferred');
* // logs 'deferred' after one or more milliseconds
*/
function defer(func) {
return baseDelay(func, 1, arguments, 1);
}
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) { console.log(text); }, 1000, 'later');
* // => logs 'later' after one second
*/
function delay(func, wait) {
return baseDelay(func, wait, arguments, 2);
}
/**
* Creates a function that returns the result of invoking the provided
* functions with the `this` binding of the created function, where each
* successive invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @category Function
* @param {...Function} [funcs] Functions to invoke.
* @returns {Function} Returns the new function.
* @example
*
* function add(x, y) {
* return x + y;
* }
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow(add, square);
* addSquare(1, 2);
* // => 9
*/
function flow() {
var funcs = arguments,
length = funcs.length;
if (!length) {
return function() {};
}
if (!arrayEvery(funcs, isFunction)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var index = 0,
result = funcs[index].apply(this, arguments);
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
}
/**
* This method is like `_.flow` except that it creates a function that
* invokes the provided functions from right to left.
*
* @static
* @memberOf _
* @alias backflow, compose
* @category Function
* @param {...Function} [funcs] Functions to invoke.
* @returns {Function} Returns the new function.
* @example
*
* function add(x, y) {
* return x + y;
* }
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight(square, add);
* addSquare(1, 2);
* // => 9
*/
function flowRight() {
var funcs = arguments,
fromIndex = funcs.length - 1;
if (fromIndex < 0) {
return function() {};
}
if (!arrayEvery(funcs, isFunction)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var index = fromIndex,
result = funcs[index].apply(this, arguments);
while (index--) {
result = funcs[index].call(this, result);
}
return result;
};
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is coerced to a string and used as the
* cache key. The `func` is invoked with the `this` binding of the memoized
* function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the ES `Map` method interface
* of `get`, `has`, and `set`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object)
* for more details.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var upperCase = _.memoize(function(string) {
* return string.toUpperCase();
* });
*
* upperCase('fred');
* // => 'FRED'
*
* // modifying the result cache
* upperCase.cache.set('fred', 'BARNEY');
* upperCase('fred');
* // => 'BARNEY'
*
* // replacing `_.memoize.Cache`
* var object = { 'user': 'fred' };
* var other = { 'user': 'barney' };
* var identity = _.memoize(_.identity);
*
* identity(object);
* // => { 'user': 'fred' }
* identity(other);
* // => { 'user': 'fred' }
*
* _.memoize.Cache = WeakMap;
* var identity = _.memoize(_.identity);
*
* identity(object);
* // => { 'user': 'fred' }
* identity(other);
* // => { 'user': 'barney' }
*/
function memoize(func, resolver) {
if (!isFunction(func) || (resolver && !isFunction(resolver))) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : arguments[0];
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, arguments);
cache.set(key, result);
return result;
};
memoized.cache = new memoize.Cache;
return memoized;
}
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/
function negate(predicate) {
if (!isFunction(predicate)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
return !predicate.apply(this, arguments);
};
}
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first call. The `func` is invoked
* with the `this` binding of the created function.
*
* @static
* @memberOf _
* @type Function
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // `initialize` invokes `createApplication` once
*/
function once(func) {
return before(func, 2);
}
/**
* Creates a function that invokes `func` with `partial` arguments prepended
* to those provided to the new function. This method is like `_.bind` except
* it does **not** alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method does not set the `length` property of partially
* applied functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [args] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) {
* return greeting + ' ' + name;
* };
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // using placeholders
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
function partial(func) {
var partials = baseSlice(arguments, 1),
holders = replaceHolders(partials, partial.placeholder);
return createWrapper(func, PARTIAL_FLAG, null, partials, holders);
}
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to those provided to the new function.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method does not set the `length` property of partially
* applied functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [args] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) {
* return greeting + ' ' + name;
* };
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // using placeholders
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
function partialRight(func) {
var partials = baseSlice(arguments, 1),
holders = replaceHolders(partials, partialRight.placeholder);
return createWrapper(func, PARTIAL_RIGHT_FLAG, null, partials, holders);
}
/**
* Creates a function that invokes `func` with arguments arranged according
* to the specified indexes where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes,
* specified as individual indexes or arrays of indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, 2, 0, 1);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
*
* var map = _.rearg(_.map, [1, 0]);
* map(function(n) { return n * 3; }, [1, 2, 3]);
* // => [3, 6, 9]
*/
function rearg(func) {
var indexes = baseFlatten(arguments, false, false, 1);
return createWrapper(func, REARG_FLAG, null, null, null, indexes);
}
/**
* Creates a function that only invokes `func` at most once per every `wait`
* milliseconds. The created function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the throttled function return the result of the last
* `func` call.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to throttle.
* @param {number} wait The number of milliseconds to throttle invocations to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify invoking on the leading
* edge of the timeout.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false })
* jQuery('.interactive').on('click', throttled);
*
* // cancel a trailing throttled call
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (!isFunction(func)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (options === false) {
leading = false;
} else if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
debounceOptions.leading = leading;
debounceOptions.maxWait = +wait;
debounceOptions.trailing = trailing;
return debounce(func, wait, debounceOptions);
}
/**
* Creates a function that provides `value` to the wrapper function as its
* first argument. Any additional arguments provided to the function are
* appended to those provided to the wrapper function. The wrapper is invoked
* with the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Function
* @param {*} value The value to wrap.
* @param {Function} wrapper The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, &amp; pebbles</p>'
*/
function wrap(value, wrapper) {
wrapper = wrapper == null ? identity : wrapper;
return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []);
}
/*------------------------------------------------------------------------*/
/**
* Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
* otherwise they are assigned by reference. If `customizer` is provided it is
* invoked to produce the cloned values. If `customizer` returns `undefined`
* cloning is handled by the method instead. The `customizer` is bound to
* `thisArg` and invoked with two argument; (value [, index|key, object]).
*
* **Note:** This method is loosely based on the structured clone algorithm.
* The enumerable properties of `arguments` objects and objects created by
* constructors other than `Object` are cloned to plain `Object` objects. An
* empty object is returned for uncloneable values such as functions, DOM nodes,
* Maps, Sets, and WeakMaps. See the [HTML5 specification](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm)
* for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @param {Function} [customizer] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {*} Returns the cloned value.
* @example
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* var shallow = _.clone(users);
* shallow[0] === users[0];
* // => true
*
* var deep = _.clone(users, true);
* deep[0] === users[0];
* // => false
*
* // using a customizer callback
* var body = _.clone(document.body, function(value) {
* return _.isElement(value) ? value.cloneNode(false) : undefined;
* });
*
* body === document.body
* // => false
* body.nodeName
* // => BODY
* body.childNodes.length;
* // => 0
*/
function clone(value, isDeep, customizer, thisArg) {
// Juggle arguments.
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);
}
/**
* Creates a deep clone of `value`. If `customizer` is provided it is invoked
* to produce the cloned values. If `customizer` returns `undefined` cloning
* is handled by the method instead. The `customizer` is bound to `thisArg`
* and invoked with two argument; (value [, index|key, object]).
*
* **Note:** This method is loosely based on the structured clone algorithm.
* The enumerable properties of `arguments` objects and objects created by
* constructors other than `Object` are cloned to plain `Object` objects. An
* empty object is returned for uncloneable values such as functions, DOM nodes,
* Maps, Sets, and WeakMaps. See the [HTML5 specification](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm)
* for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to deep clone.
* @param {Function} [customizer] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {*} Returns the deep cloned value.
* @example
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* var deep = _.cloneDeep(users);
* deep[0] === users[0];
* // => false
*
* // using a customizer callback
* var el = _.cloneDeep(document.body, function(value) {
* return _.isElement(value) ? value.cloneNode(true) : undefined;
* });
*
* body === document.body
* // => false
* body.nodeName
* // => BODY
* body.childNodes.length;
* // => 20
*/
function cloneDeep(value, customizer, thisArg) {
customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1);
return baseClone(value, true, customizer);
}
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })();
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
var length = isObjectLike(value) ? value.length : undefined;
return (isLength(length) && objToString.call(value) == argsTag) || false;
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* (function() { return _.isArray(arguments); })();
* // => false
*/
var isArray = nativeIsArray || function(value) {
return (isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag) || false;
};
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return (value === true || value === false || isObjectLike(value) && objToString.call(value) == boolTag) || false;
}
/**
* Checks if `value` is classified as a `Date` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*
* _.isDate('Mon April 23 2012');
* // => false
*/
function isDate(value) {
return (isObjectLike(value) && objToString.call(value) == dateTag) || false;
}
/**
* Checks if `value` is a DOM element.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/
function isElement(value) {
return (value && value.nodeType === 1 && isObjectLike(value) &&
objToString.call(value).indexOf('Element') > -1) || false;
}
// Fallback for environments without DOM support.
if (!support.dom) {
isElement = function(value) {
return (value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value)) || false;
};
}
/**
* Checks if a value is empty. A value is considered empty unless it is an
* `arguments` object, array, string, or jQuery-like collection with a length
* greater than `0` or an object with own enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
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;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent. If `customizer` is provided it is invoked to compare values.
* If `customizer` returns `undefined` comparisons are handled by the method
* instead. The `customizer` is bound to `thisArg` and invoked with three
* arguments; (value, other [, index|key]).
*
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
* numbers, `Object` objects, regexes, and strings. Functions and DOM nodes
* are **not** supported. Provide a customizer function to extend support
* for comparing other values.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* object == other;
* // => false
*
* _.isEqual(object, other);
* // => true
*
* // using a customizer callback
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqual(array, other, function(value, other) {
* return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
* });
* // => true
*/
function isEqual(value, other, customizer, thisArg) {
customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3);
if (!customizer && isStrictComparable(value) && isStrictComparable(other)) {
return value === other;
}
var result = customizer ? customizer(value, other) : undefined;
return typeof result == 'undefined' ? baseIsEqual(value, other, customizer) : !!result;
}
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
return (isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag) || false;
}
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on ES `Number.isFinite`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite)
* for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(10);
* // => true
*
* _.isFinite('10');
* // => false
*
* _.isFinite(true);
* // => false
*
* _.isFinite(Object(10));
* // => false
*
* _.isFinite(Infinity);
* // => false
*/
var isFinite = nativeNumIsFinite || function(value) {
return typeof value == 'number' && nativeIsFinite(value);
};
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// Avoid a Chakra JIT bug in compatibility modes of IE 11.
// See https://github.com/jashkenas/underscore/issues/1621 for more details.
return typeof value == 'function' || false;
}
// Fallback for environments that return incorrect `typeof` operator results.
if (isFunction(/x/) || (Uint8Array && !isFunction(Uint8Array))) {
isFunction = function(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return objToString.call(value) == funcTag;
};
}
/**
* Checks if `value` is the language type of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return type == 'function' || (value && type == 'object') || false;
}
/**
* Performs a deep comparison between `object` and `source` to determine if
* `object` contains equivalent property values. If `customizer` is provided
* it is invoked to compare values. If `customizer` returns `undefined`
* comparisons are handled by the method instead. The `customizer` is bound
* to `thisArg` and invoked with three arguments; (value, other, index|key).
*
* **Note:** This method supports comparing properties of arrays, booleans,
* `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
* and DOM nodes are **not** supported. Provide a customizer function to extend
* support for comparing other values.
*
* @static
* @memberOf _
* @category Lang
* @param {Object} source The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'user': 'fred', 'age': 40 };
*
* _.isMatch(object, { 'age': 40 });
* // => true
*
* _.isMatch(object, { 'age': 36 });
* // => false
*
* // using a customizer callback
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatch(object, source, function(value, other) {
* return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
* });
* // => true
*/
function isMatch(object, source, customizer, thisArg) {
var props = keys(source),
length = props.length;
customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3);
if (!customizer && length == 1) {
var key = props[0],
value = source[key];
if (isStrictComparable(value)) {
return object != null && value === object[key] && hasOwnProperty.call(object, key);
}
}
var values = Array(length),
strictCompareFlags = Array(length);
while (length--) {
value = values[length] = source[props[length]];
strictCompareFlags[length] = isStrictComparable(value);
}
return baseIsMatch(object, props, values, strictCompareFlags, customizer);
}
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is not the same as native `isNaN` which returns `true`
* for `undefined` and other non-numeric values. See the [ES5 spec](https://es5.github.io/#x15.1.2.4)
* for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some host objects in IE.
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
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;
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
* as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isNumber(8.4);
* // => true
*
* _.isNumber(NaN);
* // => true
*
* _.isNumber('8.4');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag) || false;
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* **Note:** This method assumes objects created by the `Object` constructor
* have no inherited enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
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);
};
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
function isRegExp(value) {
return (isObjectLike(value) && objToString.call(value) == regexpTag) || false;
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag) || false;
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return (isObjectLike(value) && isLength(value.length) && typedArrayTags[objToString.call(value)]) || false;
}
/**
* Checks if `value` is `undefined`.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
/**
* Converts `value` to an array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* (function() { return _.toArray(arguments).slice(1); })(1, 2, 3);
* // => [2, 3]
*/
function toArray(value) {
var length = value ? value.length : 0;
if (!isLength(length)) {
return values(value);
}
if (!length) {
return [];
}
return arrayCopy(value);
}
/**
* Converts `value` to a plain object flattening inherited enumerable
* properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return baseCopy(value, keysIn(value));
}
/*------------------------------------------------------------------------*/
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources overwrite property assignments of previous sources.
* If `customizer` is provided it is invoked to produce the assigned values.
* The `customizer` is bound to `thisArg` and invoked with five arguments;
* (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigning values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
* // => { 'user': 'fred', 'age': 40 }
*
* // using a customizer callback
* var defaults = _.partialRight(_.assign, function(value, other) {
* return typeof value == 'undefined' ? other : value;
* });
*
* defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
var assign = createAssigner(baseAssign);
/**
* Creates an object that inherits from the given `prototype` object. If a
* `properties` object is provided its own enumerable properties are assigned
* to the created object.
*
* @static
* @memberOf _
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties, guard) {
var result = baseCreate(prototype);
if (guard && isIterateeCall(prototype, properties, guard)) {
properties = null;
}
return properties ? baseCopy(properties, result, keys(properties)) : result;
}
/**
* Assigns own enumerable properties of source object(s) to the destination
* object for all destination properties that resolve to `undefined`. Once a
* property is set, additional defaults of the same property are ignored.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
function defaults(object) {
if (object == null) {
return object;
}
var args = arrayCopy(arguments);
args.push(assignDefaults);
return assign.apply(undefined, args);
}
/**
* This method is like `_.findIndex` except that it returns the key of the
* first element `predicate` returns truthy for, instead of the element itself.
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {string|undefined} Returns the key of the matched element, else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(chr) { return chr.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // using the "_.matches" callback shorthand
* _.findKey(users, { 'age': 1 });
* // => 'pebbles'
*
* // using the "_.property" callback shorthand
* _.findKey(users, 'active');
* // => 'barney'
*/
function findKey(object, predicate, thisArg) {
predicate = getCallback(predicate, thisArg, 3);
return baseFind(object, predicate, baseForOwn, true);
}
/**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* If a property name is provided for `predicate` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `predicate` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {string|undefined} Returns the key of the matched element, else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(chr) { return chr.age < 40; });
* // => returns `pebbles` assuming `_.findKey` returns `barney`
*
* // using the "_.matches" callback shorthand
* _.findLastKey(users, { 'age': 36 });
* // => 'barney'
*
* // using the "_.property" callback shorthand
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/
function findLastKey(object, predicate, thisArg) {
predicate = getCallback(predicate, thisArg, 3);
return baseFind(object, predicate, baseForOwnRight, true);
}
/**
* Iterates over own and inherited enumerable properties of an object invoking
* `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
* with three arguments; (value, key, object). Iterator functions may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
*/
function forIn(object, iteratee, thisArg) {
if (typeof iteratee != 'function' || typeof thisArg != 'undefined') {
iteratee = bindCallback(iteratee, thisArg, 3);
}
return baseFor(object, iteratee, keysIn);
}
/**
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
*/
function forInRight(object, iteratee, thisArg) {
iteratee = bindCallback(iteratee, thisArg, 3);
return baseForRight(object, iteratee, keysIn);
}
/**
* Iterates over own enumerable properties of an object invoking `iteratee`
* for each property. The `iteratee` is bound to `thisArg` and invoked with
* three arguments; (value, key, object). Iterator functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(n, key) {
* console.log(key);
* });
* // => logs '0', '1', and 'length' (iteration order is not guaranteed)
*/
function forOwn(object, iteratee, thisArg) {
if (typeof iteratee != 'function' || typeof thisArg != 'undefined') {
iteratee = bindCallback(iteratee, thisArg, 3);
}
return baseForOwn(object, iteratee);
}
/**
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(n, key) {
* console.log(key);
* });
* // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
*/
function forOwnRight(object, iteratee, thisArg) {
iteratee = bindCallback(iteratee, thisArg, 3);
return baseForRight(object, iteratee, keys);
}
/**
* Creates an array of function property names from all enumerable properties,
* own and inherited, of `object`.
*
* @static
* @memberOf _
* @alias methods
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the new array of property names.
* @example
*
* _.functions(_);
* // => ['all', 'any', 'bind', ...]
*/
function functions(object) {
return baseFunctions(object, keysIn(object));
}
/**
* Checks if `key` exists as a direct property of `object` instead of an
* inherited property.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @param {string} key The key to check.
* @returns {boolean} Returns `true` if `key` is a direct property, else `false`.
* @example
*
* _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
* // => true
*/
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite property
* assignments of previous values unless `multiValue` is `true`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to invert.
* @param {boolean} [multiValue] Allow multiple values per key.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new inverted object.
* @example
*
* _.invert({ 'first': 'fred', 'second': 'barney' });
* // => { 'fred': 'first', 'barney': 'second' }
*
* // without `multiValue`
* _.invert({ 'first': 'fred', 'second': 'barney', 'third': 'fred' });
* // => { 'fred': 'third', 'barney': 'second' }
*
* // with `multiValue`
* _.invert({ 'first': 'fred', 'second': 'barney', 'third': 'fred' }, true);
* // => { 'fred': ['first', 'third'], 'barney': ['second'] }
*/
function invert(object, multiValue, guard) {
if (guard && isIterateeCall(object, multiValue, guard)) {
multiValue = null;
}
var index = -1,
props = keys(object),
length = props.length,
result = {};
while (++index < length) {
var key = props[index],
value = object[key];
if (multiValue) {
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}
else {
result[value] = key;
}
}
return result;
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
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) : [];
};
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
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;
}
/**
* Creates an object with the same keys as `object` and values generated by
* running each own enumerable property of `object` through `iteratee`. The
* iteratee function is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* If a property name is provided for `iteratee` the created "_.property"
* style callback returns the property value of the given element.
*
* If an object is provided for `iteratee` the created "_.matches" style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration. If a property name or object is provided it is used to
* create a "_.property" or "_.matches" style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns the new mapped object.
* @example
*
* _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(n) { return n * 3; });
* // => { 'a': 3, 'b': 6, 'c': 9 }
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* // using the "_.property" callback shorthand
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee, thisArg) {
var result = {};
iteratee = getCallback(iteratee, thisArg, 3);
baseForOwn(object, function(value, key, object) {
result[key] = iteratee(value, key, object);
});
return result;
}
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* overwrite property assignments of previous sources. If `customizer` is
* provided it is invoked to produce the merged values of the destination and
* source properties. If `customizer` returns `undefined` merging is handled
* by the method instead. The `customizer` is bound to `thisArg` and invoked
* with five arguments; (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize merging properties.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* var users = {
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
* };
*
* var ages = {
* 'data': [{ 'age': 36 }, { 'age': 40 }]
* };
*
* _.merge(users, ages);
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
*
* // using a customizer callback
* var object = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var other = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(object, other, function(a, b) {
* return _.isArray(a) ? a.concat(b) : undefined;
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
*/
var merge = createAssigner(baseMerge);
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable properties of `object` that are not omitted.
* Property names may be specified as individual arguments or as arrays of
* property names. If `predicate` is provided it is invoked for each property
* of `object` omitting the properties `predicate` returns truthy for. The
* predicate is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {Function|...(string|string[])} [predicate] The function invoked per
* iteration or property names to omit, specified as individual property
* names or arrays of property names.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'user': 'fred', 'age': 40 };
*
* _.omit(object, 'age');
* // => { 'user': 'fred' }
*
* _.omit(object, _.isNumber);
* // => { 'user': 'fred' }
*/
function omit(object, predicate, thisArg) {
if (object == null) {
return {};
}
if (typeof predicate != 'function') {
var props = arrayMap(baseFlatten(arguments, false, false, 1), String);
return pickByArray(object, baseDifference(keysIn(object), props));
}
predicate = bindCallback(predicate, thisArg, 3);
return pickByCallback(object, function(value, key, object) {
return !predicate(value, key, object);
});
}
/**
* Creates a two dimensional array of the key-value pairs for `object`,
* e.g. `[[key1, value1], [key2, value2]]`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the new array of key-value pairs.
* @example
*
* _.pairs({ 'barney': 36, 'fred': 40 });
* // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
*/
function pairs(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
var key = props[index];
result[index] = [key, object[key]];
}
return result;
}
/**
* Creates an object composed of the picked `object` properties. Property
* names may be specified as individual arguments or as arrays of property
* names. If `predicate` is provided it is invoked for each property of `object`
* picking the properties `predicate` returns truthy for. The predicate is
* bound to `thisArg` and invoked with three arguments; (value, key, object).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {Function|...(string|string[])} [predicate] The function invoked per
* iteration or property names to pick, specified as individual property
* names or arrays of property names.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'user': 'fred', 'age': 40 };
*
* _.pick(object, 'user');
* // => { 'user': 'fred' }
*
* _.pick(object, _.isString);
* // => { 'user': 'fred' }
*/
function pick(object, predicate, thisArg) {
if (object == null) {
return {};
}
return typeof predicate == 'function'
? pickByCallback(object, bindCallback(predicate, thisArg, 3))
: pickByArray(object, baseFlatten(arguments, false, false, 1));
}
/**
* Resolves the value of property `key` on `object`. If the value of `key` is
* a function it is invoked with the `this` binding of `object` and its result
* is returned, else the property value is returned. If the property value is
* `undefined` the `defaultValue` is used in its place.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {string} key The key of the property to resolve.
* @param {*} [defaultValue] The value returned if the property value
* resolves to `undefined`.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'user': 'fred', 'age': _.constant(40) };
*
* _.result(object, 'user');
* // => 'fred'
*
* _.result(object, 'age');
* // => 40
*
* _.result(object, 'status', 'busy');
* // => 'busy'
*
* _.result(object, 'status', _.constant('busy'));
* // => 'busy'
*/
function result(object, key, defaultValue) {
var value = object == null ? undefined : object[key];
if (typeof value == 'undefined') {
value = defaultValue;
}
return isFunction(value) ? value.call(object) : value;
}
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own enumerable
* properties through `iteratee`, with each invocation potentially mutating
* the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
* with four arguments; (accumulator, value, key, object). Iterator functions
* may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Array|Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* var squares = _.transform([1, 2, 3, 4, 5, 6], function(result, n) {
* n *= n;
* if (n % 2) {
* return result.push(n) < 3;
* }
* });
* // => [1, 9, 25]
*
* var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, n, key) {
* result[key] = n * 3;
* });
* // => { 'a': 3, 'b': 6, 'c': 9 }
*/
function transform(object, iteratee, accumulator, thisArg) {
var isArr = isArray(object) || isTypedArray(object);
iteratee = getCallback(iteratee, thisArg, 4);
if (accumulator == null) {
if (isArr || isObject(object)) {
var Ctor = object.constructor;
if (isArr) {
accumulator = isArray(object) ? new Ctor : [];
} else {
accumulator = baseCreate(typeof Ctor == 'function' && Ctor.prototype);
}
} else {
accumulator = {};
}
}
(isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
/**
* Creates an array of the own enumerable property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return baseValues(object, keys(object));
}
/**
* Creates an array of the own and inherited enumerable property values
* of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
*/
function valuesIn(object) {
return baseValues(object, keysIn(object));
}
/*------------------------------------------------------------------------*/
/**
* Produces a random number between `min` and `max` (inclusive). If only one
* argument is provided a number between `0` and the given number is returned.
* If `floating` is `true`, or either `min` or `max` are floats, a floating-point
* number is returned instead of an integer.
*
* @static
* @memberOf _
* @category Number
* @param {number} [min=0] The minimum possible value.
* @param {number} [max=1] The maximum possible value.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(min, max, floating) {
if (floating && isIterateeCall(min, max, floating)) {
max = floating = null;
}
var noMin = min == null,
noMax = max == null;
if (floating == null) {
if (noMax && typeof min == 'boolean') {
floating = min;
min = 1;
}
else if (typeof max == 'boolean') {
floating = max;
noMax = true;
}
}
if (noMin && noMax) {
max = 1;
noMax = false;
}
min = +min || 0;
if (noMax) {
max = min;
min = 0;
} else {
max = +max || 0;
}
if (floating || min % 1 || max % 1) {
var rand = nativeRandom();
return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
}
return baseRandom(min, max);
}
/*------------------------------------------------------------------------*/
/**
* Converts `string` to camel case.
* See [Wikipedia](https://en.wikipedia.org/wiki/CamelCase) for more details.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar');
* // => 'fooBar'
*
* _.camelCase('__foo_bar__');
* // => 'fooBar'
*/
var camelCase = createCompounder(function(result, word, index) {
word = word.toLowerCase();
return index ? (result + word.charAt(0).toUpperCase() + word.slice(1)) : word;
});
/**
* Capitalizes the first character of `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('fred');
* // => 'Fred'
*/
function capitalize(string) {
string = baseToString(string);
return string && (string.charAt(0).toUpperCase() + string.slice(1));
}
/**
* Deburrs `string` by converting latin-1 supplementary letters to basic latin letters.
* See [Wikipedia](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* for more details.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr(string) {
string = baseToString(string);
return string && string.replace(reLatin1, deburrLetter);
}
/**
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to search.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search from.
* @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = baseToString(string);
target = (target + '');
var length = string.length;
position = (typeof position == 'undefined' ? length : nativeMin(position < 0 ? 0 : (+position || 0), length)) - target.length;
return position >= 0 && string.indexOf(target, position) == position;
}
/**
* Converts the characters "&", "<", ">", '"', "'", and '`', in `string` to
* their corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional characters
* use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't require escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value.
* See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* Backticks are escaped because in Internet Explorer < 9, they can break out
* of attribute values or HTML comments. See [#102](https://html5sec.org/#102),
* [#108](https://html5sec.org/#108), and [#133](https://html5sec.org/#133) of
* the [HTML5 Security Cheatsheet](https://html5sec.org/) for more details.
*
* When working with HTML you should always quote attribute values to reduce
* XSS vectors. See [Ryan Grove's article](http://wonko.com/post/html-escaping)
* for more details.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, &amp; pebbles'
*/
function escape(string) {
// Reset `lastIndex` because in IE < 9 `String#replace` does not.
string = baseToString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
/**
* Escapes the `RegExp` special characters "\", "^", "$", ".", "|", "?", "*",
* "+", "(", ")", "[", "]", "{" and "}" in `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = baseToString(string);
return (string && reHasRegExpChars.test(string))
? string.replace(reRegExpChars, '\\$&')
: string;
}
/**
* Converts `string` to kebab case (a.k.a. spinal case).
* See [Wikipedia](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles) for
* more details.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__foo_bar__');
* // => 'foo-bar'
*/
var kebabCase = createCompounder(function(result, word, index) {
return result + (index ? '-' : '') + word.toLowerCase();
});
/**
* Pads `string` on the left and right sides if it is shorter then the given
* padding length. The `chars` string may be truncated if the number of padding
* characters can't be evenly divided by the padding length.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/
function pad(string, length, chars) {
string = baseToString(string);
length = +length;
var strLength = string.length;
if (strLength >= length || !nativeIsFinite(length)) {
return string;
}
var mid = (length - strLength) / 2,
leftLength = floor(mid),
rightLength = ceil(mid);
chars = createPad('', rightLength, chars);
return chars.slice(0, leftLength) + string + chars;
}
/**
* Pads `string` on the left side if it is shorter then the given padding
* length. The `chars` string may be truncated if the number of padding
* characters exceeds the padding length.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padLeft('abc', 6);
* // => ' abc'
*
* _.padLeft('abc', 6, '_-');
* // => '_-_abc'
*
* _.padLeft('abc', 3);
* // => 'abc'
*/
function padLeft(string, length, chars) {
string = baseToString(string);
return string && (createPad(string, length, chars) + string);
}
/**
* Pads `string` on the right side if it is shorter then the given padding
* length. The `chars` string may be truncated if the number of padding
* characters exceeds the padding length.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padRight('abc', 6);
* // => 'abc '
*
* _.padRight('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padRight('abc', 3);
* // => 'abc'
*/
function padRight(string, length, chars) {
string = baseToString(string);
return string && (string + createPad(string, length, chars));
}
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
* in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the ES5 implementation of `parseInt`.
* See the [ES5 spec](https://es5.github.io/#E) for more details.
*
* @static
* @memberOf _
* @category String
* @param {string} string The string to convert.
* @param {number} [radix] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard && isIterateeCall(string, radix, guard)) {
radix = 0;
}
return nativeParseInt(string, radix);
}
// Fallback for environments with pre-ES5 implementations.
if (nativeParseInt(whitespace + '08') != 8) {
parseInt = function(string, radix, guard) {
// Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
// Chrome fails to trim leading <BOM> whitespace characters.
// See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
string = trim(string);
return nativeParseInt(string, radix || (reHexPrefix.test(string) ? 16 : 10));
};
}
/**
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=0] The number of times to repeat the string.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
*/
function repeat(string, n) {
var result = '';
string = baseToString(string);
n = +n;
if (n < 1 || !string || !nativeIsFinite(n)) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = floor(n / 2);
string += string;
} while (n);
return result;
}
/**
* Converts `string` to snake case.
* See [Wikipedia](https://en.wikipedia.org/wiki/Snake_case) for more details.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the snake cased string.
* @example
*
* _.snakeCase('Foo Bar');
* // => 'foo_bar'
*
* _.snakeCase('--foo-bar');
* // => 'foo_bar'
*
* _.snakeCase('fooBar');
* // => 'foo_bar'
*/
var snakeCase = createCompounder(function(result, word, index) {
return result + (index ? '_' : '') + word.toLowerCase();
});
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to search.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = baseToString(string);
position = position == null ? 0 : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
return string.lastIndexOf(target, position) == position;
}
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is provided it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes sourceURLs for easier debugging.
* See the [HTML5 Rocks article on sourcemaps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for more details.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options] The options object.
* @param {RegExp} [options.escape] The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate] The "evaluate" delimiter.
* @param {Object} [options.imports] An object to import into the template as free variables.
* @param {RegExp} [options.interpolate] The "interpolate" delimiter.
* @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
* @param {string} [options.variable] The data object variable name.
* @param- {Object} [otherOptions] Enables the legacy `options` param signature.
* @returns {Function} Returns the compiled template function.
* @example
*
* // using the "interpolate" delimiter to create a compiled template
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // using the HTML "escape" delimiter to escape data property values
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b>&lt;script&gt;</b>'
*
* // using the "evaluate" delimiter to execute JavaScript and generate HTML
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // using the internal `print` function in "evaluate" delimiters
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // using the ES delimiter as an alternative to the default "interpolate" delimiter
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // using custom template delimiters
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // using backslashes to treat delimiters as plain text
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // using the `imports` option to import `jQuery` as `jq`
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // using the `sourceURL` option to specify a custom sourceURL for the template
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
*
* // using the `variable` option to ensure a with-statement isn't used in the compiled template
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* var __t, __p = '';
* __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* return __p;
* }
*
* // using the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and a stack trace
* fs.writeFileSync(path.join(cwd, 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(string, options, otherOptions) {
// Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
if (otherOptions && isIterateeCall(string, options, otherOptions)) {
options = otherOptions = null;
}
string = baseToString(string);
options = baseAssign(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
var imports = baseAssign(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
var sourceURL = '//# sourceURL=' +
('sourceURL' in options
? options.sourceURL
: ('lodash.templateSources[' + (++templateCounter) + ']')
) + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products requires returning the `match`
// string in order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar]
*/
function trim(string, chars, guard) {
var value = string;
string = baseToString(string);
if (!string) {
return string;
}
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
}
chars = baseToString(chars);
return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
}
/**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimLeft(' abc ');
* // => 'abc '
*
* _.trimLeft('-_-abc-_-', '_-');
* // => 'abc-_-'
*/
function trimLeft(string, chars, guard) {
var value = string;
string = baseToString(string);
if (!string) {
return string;
}
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
return string.slice(trimmedLeftIndex(string))
}
return string.slice(charsLeftIndex(string, baseToString(chars)));
}
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimRight(' abc ');
* // => ' abc'
*
* _.trimRight('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimRight(string, chars, guard) {
var value = string;
string = baseToString(string);
if (!string) {
return string;
}
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
return string.slice(0, trimmedRightIndex(string) + 1)
}
return string.slice(0, charsRightIndex(string, baseToString(chars)) + 1);
}
/**
* Truncates `string` if it is longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object|number} [options] The options object or maximum string length.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the truncated string.
* @example
*
* _.trunc('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.trunc('hi-diddly-ho there, neighborino', 24);
* // => 'hi-diddly-ho there, n...'
*
* _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' ' });
* // => 'hi-diddly-ho there,...'
*
* _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/ });
* //=> 'hi-diddly-ho there...'
*
* _.trunc('hi-diddly-ho there, neighborino', { 'omission': ' [...]' });
* // => 'hi-diddly-ho there, neig [...]'
*/
function trunc(string, options, guard) {
if (guard && isIterateeCall(string, options, guard)) {
options = null;
}
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (options != null) {
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? +options.length || 0 : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
} else {
length = +options || 0;
}
}
string = baseToString(string);
if (length >= string.length) {
return string;
}
var end = length - omission.length;
if (end < 1) {
return omission;
}
var result = string.slice(0, end);
if (separator == null) {
return result + omission;
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
newEnd,
substring = string.slice(0, end);
if (!separator.global) {
separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
newEnd = match.index;
}
result = result.slice(0, newEnd == null ? end : newEnd);
}
} else if (string.indexOf(separator, end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
/**
* The inverse of `_.escape`; this method converts the HTML entities
* `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their
* corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional HTML
* entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, &amp; pebbles');
* // => 'fred, barney, & pebbles'
*/
function unescape(string) {
string = baseToString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
if (guard && isIterateeCall(string, pattern, guard)) {
pattern = null;
}
string = baseToString(string);
return string.match(pattern || reWords) || [];
}
/*------------------------------------------------------------------------*/
/**
* Attempts to invoke `func`, returning either the result or the caught
* error object.
*
* @static
* @memberOf _
* @category Utility
* @param {*} func The function to attempt.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // avoid throwing errors for invalid selectors
* var elements = _.attempt(function() {
* return document.querySelectorAll(selector);
* });
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
function attempt(func) {
try {
return func();
} catch(e) {
return isError(e) ? e : Error(e);
}
}
/**
* Creates a function bound to an optional `thisArg`. If `func` is a property
* name the created callback returns the property value for a given element.
* If `func` is an object the created callback returns `true` for elements
* that contain the equivalent object properties, otherwise it returns `false`.
*
* @static
* @memberOf _
* @alias iteratee
* @category Utility
* @param {*} [func=_.identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of `func`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // wrap to create custom callback shorthands
* _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
* var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
* if (!match) {
* return callback(func, thisArg);
* }
* return function(object) {
* return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
* };
* });
*
* _.filter(users, 'age__gt36');
* // => [{ 'user': 'fred', 'age': 40 }]
*/
function callback(func, thisArg, guard) {
if (guard && isIterateeCall(func, thisArg, guard)) {
thisArg = null;
}
return baseCallback(func, thisArg);
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new function.
* @example
*
* var object = { 'user': 'fred' };
* var getter = _.constant(object);
* getter() === object;
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function which performs a deep comparison between a given object
* and `source`, returning `true` if the given object has equivalent property
* values, else `false`.
*
* @static
* @memberOf _
* @category Utility
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* var matchesAge = _.matches({ 'age': 36 });
*
* _.filter(users, matchesAge);
* // => [{ 'user': 'barney', 'age': 36 }]
*
* _.find(users, matchesAge);
* // => { 'user': 'barney', 'age': 36 }
*/
function matches(source) {
return baseMatches(source, true);
}
/**
* Adds all own enumerable function properties of a source object to the
* destination object. If `object` is a function then methods are added to
* its prototype as well.
*
* @static
* @memberOf _
* @category Utility
* @param {Function|Object} [object=this] object The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options] The options object.
* @param {boolean} [options.chain=true] Specify whether the functions added
* are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
*/
function mixin(object, source, options) {
if (options == null) {
var isObj = isObject(source),
props = isObj && keys(source),
methodNames = props && props.length && baseFunctions(source, props);
if (!(methodNames ? methodNames.length : isObj)) {
methodNames = false;
options = source;
source = object;
object = this;
}
}
if (!methodNames) {
methodNames = baseFunctions(source, keys(source));
}
var chain = true,
index = -1,
isFunc = isFunction(object),
length = methodNames.length;
if (options === false) {
chain = false;
} else if (isObject(options) && 'chain' in options) {
chain = options.chain;
}
while (++index < length) {
var methodName = methodNames[index],
func = source[methodName];
object[methodName] = func;
if (isFunc) {
object.prototype[methodName] = (function(func) {
return function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__);
(result.__actions__ = arrayCopy(this.__actions__)).push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
var args = [this.value()];
push.apply(args, arguments);
return func.apply(object, args);
};
}(func));
}
}
return object;
}
/**
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @memberOf _
* @category Utility
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
context._ = oldDash;
return this;
}
/**
* A no-operation function.
*
* @static
* @memberOf _
* @category Utility
* @example
*
* var object = { 'user': 'fred' };
* _.noop(object) === undefined;
* // => true
*/
function noop() {
// No operation performed.
}
/**
* Creates a function which returns the property value of `key` on a given object.
*
* @static
* @memberOf _
* @category Utility
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
* @example
*
* var users = [
* { 'user': 'fred' },
* { 'user': 'barney' }
* ];
*
* var getName = _.property('user');
*
* _.map(users, getName);
* // => ['fred', barney']
*
* _.pluck(_.sortBy(users, getName), 'user');
* // => ['barney', 'fred']
*/
function property(key) {
return baseProperty(key + '');
}
/**
* The inverse of `_.property`; this method creates a function which returns
* the property value of a given key on `object`.
*
* @static
* @memberOf _
* @category Utility
* @param {Object} object The object to inspect.
* @returns {Function} Returns the new function.
* @example
*
* var object = { 'user': 'fred', 'age': 40, 'active': true };
* _.map(['active', 'user'], _.propertyOf(object));
* // => [true, 'fred']
*
* var object = { 'a': 3, 'b': 1, 'c': 2 };
* _.sortBy(['a', 'b', 'c'], _.propertyOf(object));
* // => ['b', 'c', 'a']
*/
function propertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. If `start` is less than `end` a
* zero-length range is created unless a negative `step` is specified.
*
* @static
* @memberOf _
* @category Utility
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the new array of numbers.
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
function range(start, end, step) {
if (step && isIterateeCall(start, end, step)) {
end = step = null;
}
start = +start || 0;
step = step == null ? 1 : (+step || 0);
if (end == null) {
end = start;
start = 0;
} else {
end = +end || 0;
}
// Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
// See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
var index = -1,
length = nativeMax(ceil((end - start) / (step || 1)), 0),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
/**
* Invokes the iteratee function `n` times, returning an array of the results
* of each invocation. The `iteratee` is bound to `thisArg` and invoked with
* one argument; (index).
*
* @static
* @memberOf _
* @category Utility
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the array of results.
* @example
*
* var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
* // => [3, 6, 4]
*
* _.times(3, function(n) { mage.castSpell(n); });
* // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` respectively
*
* _.times(3, function(n) { this.cast(n); }, mage);
* // => also invokes `mage.castSpell(n)` three times
*/
function times(n, iteratee, thisArg) {
n = +n;
// Exit early to avoid a JSC JIT bug in Safari 8
// where `Array(0)` is treated as `Array(1)`.
if (n < 1 || !nativeIsFinite(n)) {
return [];
}
var index = -1,
result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
iteratee = bindCallback(iteratee, thisArg, 1);
while (++index < n) {
if (index < MAX_ARRAY_LENGTH) {
result[index] = iteratee(index);
} else {
iteratee(index);
}
}
return result;
}
/**
* Generates a unique ID. If `prefix` is provided the ID is appended to it.
*
* @static
* @memberOf _
* @category Utility
* @param {string} [prefix] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return baseToString(prefix) + id;
}
/*------------------------------------------------------------------------*/
// Ensure `new LodashWrapper` is an instance of `lodash`.
LodashWrapper.prototype = lodash.prototype;
// Add functions to the `Map` cache.
MapCache.prototype['delete'] = mapDelete;
MapCache.prototype.get = mapGet;
MapCache.prototype.has = mapHas;
MapCache.prototype.set = mapSet;
// Add functions to the `Set` cache.
SetCache.prototype.push = cachePush;
// Assign cache to `_.memoize`.
memoize.Cache = MapCache;
// Add functions that return wrapped values when chaining.
lodash.after = after;
lodash.ary = ary;
lodash.assign = assign;
lodash.at = at;
lodash.before = before;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.callback = callback;
lodash.chain = chain;
lodash.chunk = chunk;
lodash.compact = compact;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.curry = curry;
lodash.curryRight = curryRight;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.drop = drop;
lodash.dropRight = dropRight;
lodash.dropRightWhile = dropRightWhile;
lodash.dropWhile = dropWhile;
lodash.filter = filter;
lodash.flatten = flatten;
lodash.flattenDeep = flattenDeep;
lodash.flow = flow;
lodash.flowRight = flowRight;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.functions = functions;
lodash.groupBy = groupBy;
lodash.indexBy = indexBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.invert = invert;
lodash.invoke = invoke;
lodash.keys = keys;
lodash.keysIn = keysIn;
lodash.map = map;
lodash.mapValues = mapValues;
lodash.matches = matches;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.mixin = mixin;
lodash.negate = negate;
lodash.omit = omit;
lodash.once = once;
lodash.pairs = pairs;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.partition = partition;
lodash.pick = pick;
lodash.pluck = pluck;
lodash.property = property;
lodash.propertyOf = propertyOf;
lodash.pull = pull;
lodash.pullAt = pullAt;
lodash.range = range;
lodash.rearg = rearg;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.shuffle = shuffle;
lodash.slice = slice;
lodash.sortBy = sortBy;
lodash.sortByAll = sortByAll;
lodash.take = take;
lodash.takeRight = takeRight;
lodash.takeRightWhile = takeRightWhile;
lodash.takeWhile = takeWhile;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.thru = thru;
lodash.times = times;
lodash.toArray = toArray;
lodash.toPlainObject = toPlainObject;
lodash.transform = transform;
lodash.union = union;
lodash.uniq = uniq;
lodash.unzip = unzip;
lodash.values = values;
lodash.valuesIn = valuesIn;
lodash.where = where;
lodash.without = without;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.zip = zip;
lodash.zipObject = zipObject;
// Add aliases.
lodash.backflow = flowRight;
lodash.collect = map;
lodash.compose = flowRight;
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.extend = assign;
lodash.iteratee = callback;
lodash.methods = functions;
lodash.object = zipObject;
lodash.select = filter;
lodash.tail = rest;
lodash.unique = uniq;
// Add functions to `lodash.prototype`.
mixin(lodash, lodash);
/*------------------------------------------------------------------------*/
// Add functions that return unwrapped values when chaining.
lodash.attempt = attempt;
lodash.camelCase = camelCase;
lodash.capitalize = capitalize;
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.deburr = deburr;
lodash.endsWith = endsWith;
lodash.escape = escape;
lodash.escapeRegExp = escapeRegExp;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.findWhere = findWhere;
lodash.first = first;
lodash.has = has;
lodash.identity = identity;
lodash.includes = includes;
lodash.indexOf = indexOf;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isBoolean = isBoolean;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isError = isError;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isMatch = isMatch;
lodash.isNaN = isNaN;
lodash.isNative = isNative;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isString = isString;
lodash.isTypedArray = isTypedArray;
lodash.isUndefined = isUndefined;
lodash.kebabCase = kebabCase;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.max = max;
lodash.min = min;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.pad = pad;
lodash.padLeft = padLeft;
lodash.padRight = padRight;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.repeat = repeat;
lodash.result = result;
lodash.runInContext = runInContext;
lodash.size = size;
lodash.snakeCase = snakeCase;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.sortedLastIndex = sortedLastIndex;
lodash.startsWith = startsWith;
lodash.template = template;
lodash.trim = trim;
lodash.trimLeft = trimLeft;
lodash.trimRight = trimRight;
lodash.trunc = trunc;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
lodash.words = words;
// Add aliases.
lodash.all = every;
lodash.any = some;
lodash.contains = includes;
lodash.detect = find;
lodash.foldl = reduce;
lodash.foldr = reduceRight;
lodash.head = first;
lodash.include = includes;
lodash.inject = reduce;
mixin(lodash, (function() {
var source = {};
baseForOwn(lodash, function(func, methodName) {
if (!lodash.prototype[methodName]) {
source[methodName] = func;
}
});
return source;
}()), false);
/*------------------------------------------------------------------------*/
// Add functions capable of returning wrapped and unwrapped values when chaining.
lodash.sample = sample;
lodash.prototype.sample = function(n) {
if (!this.__chain__ && n == null) {
return sample(this.value());
}
return this.thru(function(value) {
return sample(value, n);
});
};
/*------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type string
*/
lodash.VERSION = VERSION;
// Assign default placeholders.
arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
lodash[methodName].placeholder = lodash;
});
// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
var isFilter = index == LAZY_FILTER_FLAG;
LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
var result = this.clone(),
filtered = result.filtered,
iteratees = result.iteratees || (result.iteratees = []);
result.filtered = filtered || isFilter || (index == LAZY_WHILE_FLAG && result.dir < 0);
iteratees.push({ 'iteratee': getCallback(iteratee, thisArg, 3), 'type': index });
return result;
};
});
// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop', 'take'], function(methodName, index) {
var countName = methodName + 'Count',
whileName = methodName + 'While';
LazyWrapper.prototype[methodName] = function(n) {
n = n == null ? 1 : nativeMax(+n || 0, 0);
var result = this.clone();
if (result.filtered) {
var value = result[countName];
result[countName] = index ? nativeMin(value, n) : (value + n);
} else {
var views = result.views || (result.views = []);
views.push({ 'size': n, 'type': methodName + (result.dir < 0 ? 'Right' : '') });
}
return result;
};
LazyWrapper.prototype[methodName + 'Right'] = function(n) {
return this.reverse()[methodName](n).reverse();
};
LazyWrapper.prototype[methodName + 'RightWhile'] = function(predicate, thisArg) {
return this.reverse()[whileName](predicate, thisArg).reverse();
};
});
// Add `LazyWrapper` methods for `_.first` and `_.last`.
arrayEach(['first', 'last'], function(methodName, index) {
var takeName = 'take' + (index ? 'Right': '');
LazyWrapper.prototype[methodName] = function() {
return this[takeName](1).value()[0];
};
});
// Add `LazyWrapper` methods for `_.initial` and `_.rest`.
arrayEach(['initial', 'rest'], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
return this[dropName](1);
};
});
// Add `LazyWrapper` methods for `_.pluck` and `_.where`.
arrayEach(['pluck', 'where'], function(methodName, index) {
var operationName = index ? 'filter' : 'map',
createCallback = index ? matches : property;
LazyWrapper.prototype[methodName] = function(value) {
return this[operationName](createCallback(value));
};
});
LazyWrapper.prototype.dropWhile = function(iteratee, thisArg) {
var done,
lastIndex,
isRight = this.dir < 0;
iteratee = getCallback(iteratee, thisArg, 3);
return this.filter(function(value, index, array) {
done = done && (isRight ? index < lastIndex : index > lastIndex);
lastIndex = index;
return done || (done = !iteratee(value, index, array));
});
};
LazyWrapper.prototype.reject = function(iteratee, thisArg) {
iteratee = getCallback(iteratee, thisArg, 3);
return this.filter(function(value, index, array) {
return !iteratee(value, index, array);
});
};
LazyWrapper.prototype.slice = function(start, end) {
start = start == null ? 0 : (+start || 0);
var result = start < 0 ? this.takeRight(-start) : this.drop(start);
if (typeof end != 'undefined') {
end = (+end || 0);
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
}
return result;
};
// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName],
retUnwrapped = /^(?:first|last)$/.test(methodName);
lodash.prototype[methodName] = function() {
var value = this.__wrapped__,
args = arguments,
chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isLazy = value instanceof LazyWrapper,
onlyLazy = isLazy && !isHybrid;
if (retUnwrapped && !chainAll) {
return onlyLazy
? func.call(value)
: lodashFunc.call(lodash, this.value());
}
var interceptor = function(value) {
var otherArgs = [value];
push.apply(otherArgs, args);
return lodashFunc.apply(lodash, otherArgs);
};
if (isLazy || isArray(value)) {
var wrapper = onlyLazy ? value : new LazyWrapper(this),
result = func.apply(wrapper, args);
if (!retUnwrapped && (isHybrid || result.actions)) {
var actions = result.actions || (result.actions = []);
actions.push({ 'func': thru, 'args': [interceptor], 'thisArg': lodash });
}
return new LodashWrapper(result, chainAll);
}
return this.thru(interceptor);
};
});
// Add `Array.prototype` functions to `lodash.prototype`.
arrayEach(['concat', 'join', 'pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
var func = arrayProto[methodName],
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
retUnwrapped = /^(?:join|pop|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
return func.apply(this.value(), args);
}
return this[chainName](function(value) {
return func.apply(value, args);
});
};
});
// Add functions to the lazy wrapper.
LazyWrapper.prototype.clone = lazyClone;
LazyWrapper.prototype.reverse = lazyReverse;
LazyWrapper.prototype.value = lazyValue;
// Add chaining functions to the lodash wrapper.
lodash.prototype.chain = wrapperChain;
lodash.prototype.reverse = wrapperReverse;
lodash.prototype.toString = wrapperToString;
lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
// Add function aliases to the lodash wrapper.
lodash.prototype.collect = lodash.prototype.map;
lodash.prototype.head = lodash.prototype.first;
lodash.prototype.select = lodash.prototype.filter;
lodash.prototype.tail = lodash.prototype.rest;
return lodash;
}
/*--------------------------------------------------------------------------*/
// Export lodash.
var _ = runInContext();
// Some AMD build optimizers like r.js check for condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose lodash to the global object when an AMD loader is present to avoid
// errors in cases where lodash is loaded by a script tag and not intended
// as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
// more details.
root._ = _;
// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
return _;
});
}
// Check for `exports` after `define` in case a build optimizer adds an `exports` object.
else if (freeExports && freeModule) {
// Export for Node.js or RingoJS.
if (moduleExports) {
(freeModule.exports = _)._ = _;
}
// Export for Narwhal or Rhino -require.
else {
freeExports._ = _;
}
}
else {
// Export for a browser or Rhino.
root._ = _;
}
}.call(this));
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],44:[function(require,module,exports){
;(function () { // closure for web browsers
if (typeof module === 'object' && module.exports) {
module.exports = LRUCache
} else {
// just set the global for non-node platforms.
this.LRUCache = LRUCache
}
function hOP (obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key)
}
function naiveLength () { return 1 }
function LRUCache (options) {
if (!(this instanceof LRUCache))
return new LRUCache(options)
if (typeof options === 'number')
options = { max: options }
if (!options)
options = {}
this._max = options.max
// Kind of weird to have a default max of Infinity, but oh well.
if (!this._max || !(typeof this._max === "number") || this._max <= 0 )
this._max = Infinity
this._lengthCalculator = options.length || naiveLength
if (typeof this._lengthCalculator !== "function")
this._lengthCalculator = naiveLength
this._allowStale = options.stale || false
this._maxAge = options.maxAge || null
this._dispose = options.dispose
this.reset()
}
// resize the cache when the max changes.
Object.defineProperty(LRUCache.prototype, "max",
{ set : function (mL) {
if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity
this._max = mL
if (this._length > this._max) trim(this)
}
, get : function () { return this._max }
, enumerable : true
})
// resize the cache when the lengthCalculator changes.
Object.defineProperty(LRUCache.prototype, "lengthCalculator",
{ set : function (lC) {
if (typeof lC !== "function") {
this._lengthCalculator = naiveLength
this._length = this._itemCount
for (var key in this._cache) {
this._cache[key].length = 1
}
} else {
this._lengthCalculator = lC
this._length = 0
for (var key in this._cache) {
this._cache[key].length = this._lengthCalculator(this._cache[key].value)
this._length += this._cache[key].length
}
}
if (this._length > this._max) trim(this)
}
, get : function () { return this._lengthCalculator }
, enumerable : true
})
Object.defineProperty(LRUCache.prototype, "length",
{ get : function () { return this._length }
, enumerable : true
})
Object.defineProperty(LRUCache.prototype, "itemCount",
{ get : function () { return this._itemCount }
, enumerable : true
})
LRUCache.prototype.forEach = function (fn, thisp) {
thisp = thisp || this
var i = 0;
for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
i++
var hit = this._lruList[k]
if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
del(this, hit)
if (!this._allowStale) hit = undefined
}
if (hit) {
fn.call(thisp, hit.value, hit.key, this)
}
}
}
LRUCache.prototype.keys = function () {
var keys = new Array(this._itemCount)
var i = 0
for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
var hit = this._lruList[k]
keys[i++] = hit.key
}
return keys
}
LRUCache.prototype.values = function () {
var values = new Array(this._itemCount)
var i = 0
for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
var hit = this._lruList[k]
values[i++] = hit.value
}
return values
}
LRUCache.prototype.reset = function () {
if (this._dispose && this._cache) {
for (var k in this._cache) {
this._dispose(k, this._cache[k].value)
}
}
this._cache = Object.create(null) // hash of items by key
this._lruList = Object.create(null) // list of items in order of use recency
this._mru = 0 // most recently used
this._lru = 0 // least recently used
this._length = 0 // number of items in the list
this._itemCount = 0
}
// Provided for debugging/dev purposes only. No promises whatsoever that
// this API stays stable.
LRUCache.prototype.dump = function () {
return this._cache
}
LRUCache.prototype.dumpLru = function () {
return this._lruList
}
LRUCache.prototype.set = function (key, value) {
if (hOP(this._cache, key)) {
// dispose of the old one before overwriting
if (this._dispose) this._dispose(key, this._cache[key].value)
if (this._maxAge) this._cache[key].now = Date.now()
this._cache[key].value = value
this.get(key)
return true
}
var len = this._lengthCalculator(value)
var age = this._maxAge ? Date.now() : 0
var hit = new Entry(key, value, this._mru++, len, age)
// oversized objects fall out of cache automatically.
if (hit.length > this._max) {
if (this._dispose) this._dispose(key, value)
return false
}
this._length += hit.length
this._lruList[hit.lu] = this._cache[key] = hit
this._itemCount ++
if (this._length > this._max) trim(this)
return true
}
LRUCache.prototype.has = function (key) {
if (!hOP(this._cache, key)) return false
var hit = this._cache[key]
if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
return false
}
return true
}
LRUCache.prototype.get = function (key) {
return get(this, key, true)
}
LRUCache.prototype.peek = function (key) {
return get(this, key, false)
}
LRUCache.prototype.pop = function () {
var hit = this._lruList[this._lru]
del(this, hit)
return hit || null
}
LRUCache.prototype.del = function (key) {
del(this, this._cache[key])
}
function get (self, key, doUse) {
var hit = self._cache[key]
if (hit) {
if (self._maxAge && (Date.now() - hit.now > self._maxAge)) {
del(self, hit)
if (!self._allowStale) hit = undefined
} else {
if (doUse) use(self, hit)
}
if (hit) hit = hit.value
}
return hit
}
function use (self, hit) {
shiftLU(self, hit)
hit.lu = self._mru ++
if (self._maxAge) hit.now = Date.now()
self._lruList[hit.lu] = hit
}
function trim (self) {
while (self._lru < self._mru && self._length > self._max)
del(self, self._lruList[self._lru])
}
function shiftLU (self, hit) {
delete self._lruList[ hit.lu ]
while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++
}
function del (self, hit) {
if (hit) {
if (self._dispose) self._dispose(hit.key, hit.value)
self._length -= hit.length
self._itemCount --
delete self._cache[ hit.key ]
shiftLU(self, hit)
}
}
// classy, since V8 prefers predictable objects.
function Entry (key, value, lu, length, now) {
this.key = key
this.value = value
this.lu = lu
this.length = length
this.now = now
}
})()
},{}],45:[function(require,module,exports){
'use strict';
var SingleEvent = require('geval/single');
var MultipleEvent = require('geval/multiple');
var extend = require('xtend');
/*
Pro tip: Don't require `mercury` itself.
require and depend on all these modules directly!
*/
var mercury = module.exports = {
// Entry
main: require('main-loop'),
app: app,
// Base
BaseEvent: require('value-event/base-event'),
// Input
Delegator: require('dom-delegator'),
// deprecated: use hg.handles instead.
input: input,
// deprecated: use hg.channels instead.
handles: channels,
channels: channels,
// deprecated: use hg.send instead.
event: require('value-event/event'),
send: require('value-event/event'),
// deprecated: use hg.sendValue instead.
valueEvent: require('value-event/value'),
sendValue: require('value-event/value'),
// deprecated: use hg.sendSubmit instead.
submitEvent: require('value-event/submit'),
sendSubmit: require('value-event/submit'),
// deprecated: use hg.sendChange instead.
changeEvent: require('value-event/change'),
sendChange: require('value-event/change'),
// deprecated: use hg.sendKey instead.
keyEvent: require('value-event/key'),
sendKey: require('value-event/key'),
// deprecated use hg.sendClick instead.
clickEvent: require('value-event/click'),
sendClick: require('value-event/click'),
// State
// deprecated: use hg.varhash instead.
array: require('observ-array'),
struct: require('observ-struct'),
// deprecated: use hg.struct instead.
hash: require('observ-struct'),
varhash: require('observ-varhash'),
value: require('observ'),
state: state,
// Render
diff: require('virtual-dom/vtree/diff'),
patch: require('virtual-dom/vdom/patch'),
partial: require('vdom-thunk'),
create: require('virtual-dom/vdom/create-element'),
h: require('virtual-dom/virtual-hyperscript'),
// deprecated: require svg directly instead
svg: require('virtual-dom/virtual-hyperscript/svg'),
// Utilities
// deprecated: require computed directly instead.
computed: require('observ/computed'),
// deprecated: require watch directly instead.
watch: require('observ/watch')
};
function input(names) {
if (!names) {
return SingleEvent();
}
return MultipleEvent(names);
}
function state(obj) {
var copy = extend(obj);
var $channels = copy.channels;
var $handles = copy.handles;
if ($channels) {
copy.channels = mercury.value(null);
} else if ($handles) {
copy.handles = mercury.value(null);
}
var observ = mercury.struct(copy);
if ($channels) {
observ.channels.set(mercury.channels($channels, observ));
} else if ($handles) {
observ.handles.set(mercury.channels($handles, observ));
}
return observ;
}
function channels(funcs, context) {
return Object.keys(funcs).reduce(createHandle, {});
function createHandle(acc, name) {
var handle = mercury.Delegator.allocateHandle(
funcs[name].bind(null, context));
acc[name] = handle;
return acc;
}
}
function app(elem, observ, render, opts) {
mercury.Delegator(opts);
var loop = mercury.main(observ(), render, extend({
diff: mercury.diff,
create: mercury.create,
patch: mercury.patch
}, opts));
if (elem) {
elem.appendChild(loop.target);
}
return observ(loop.update);
}
},{"dom-delegator":48,"geval/multiple":62,"geval/single":63,"main-loop":64,"observ":87,"observ-array":75,"observ-struct":82,"observ-varhash":84,"observ/computed":86,"observ/watch":88,"value-event/base-event":89,"value-event/change":90,"value-event/click":91,"value-event/event":92,"value-event/key":93,"value-event/submit":99,"value-event/value":100,"vdom-thunk":102,"virtual-dom/vdom/create-element":117,"virtual-dom/vdom/patch":120,"virtual-dom/virtual-hyperscript":125,"virtual-dom/virtual-hyperscript/svg":127,"virtual-dom/vtree/diff":138,"xtend":139}],46:[function(require,module,exports){
var DataSet = require("data-set")
module.exports = addEvent
function addEvent(target, type, handler) {
var ds = DataSet(target)
var events = ds[type]
if (!events) {
ds[type] = handler
} else if (Array.isArray(events)) {
if (events.indexOf(handler) === -1) {
events.push(handler)
}
} else if (events !== handler) {
ds[type] = [events, handler]
}
}
},{"data-set":51}],47:[function(require,module,exports){
var globalDocument = require("global/document")
var DataSet = require("data-set")
var createStore = require("weakmap-shim/create-store")
var addEvent = require("./add-event.js")
var removeEvent = require("./remove-event.js")
var ProxyEvent = require("./proxy-event.js")
var HANDLER_STORE = createStore()
module.exports = DOMDelegator
function DOMDelegator(document) {
if (!(this instanceof DOMDelegator)) {
return new DOMDelegator(document);
}
document = document || globalDocument
this.target = document.documentElement
this.events = {}
this.rawEventListeners = {}
this.globalListeners = {}
}
DOMDelegator.prototype.addEventListener = addEvent
DOMDelegator.prototype.removeEventListener = removeEvent
DOMDelegator.allocateHandle =
function allocateHandle(func) {
var handle = new Handle()
HANDLER_STORE(handle).func = func;
return handle
}
DOMDelegator.transformHandle =
function transformHandle(handle, broadcast) {
var func = HANDLER_STORE(handle).func
return this.allocateHandle(function (ev) {
broadcast(ev, func);
})
}
DOMDelegator.prototype.addGlobalEventListener =
function addGlobalEventListener(eventName, fn) {
var listeners = this.globalListeners[eventName] || [];
if (listeners.indexOf(fn) === -1) {
listeners.push(fn)
}
this.globalListeners[eventName] = listeners;
}
DOMDelegator.prototype.removeGlobalEventListener =
function removeGlobalEventListener(eventName, fn) {
var listeners = this.globalListeners[eventName] || [];
var index = listeners.indexOf(fn)
if (index !== -1) {
listeners.splice(index, 1)
}
}
DOMDelegator.prototype.listenTo = function listenTo(eventName) {
if (!(eventName in this.events)) {
this.events[eventName] = 0;
}
this.events[eventName]++;
if (this.events[eventName] !== 1) {
return
}
var listener = this.rawEventListeners[eventName]
if (!listener) {
listener = this.rawEventListeners[eventName] =
createHandler(eventName, this)
}
this.target.addEventListener(eventName, listener, true)
}
DOMDelegator.prototype.unlistenTo = function unlistenTo(eventName) {
if (!(eventName in this.events)) {
this.events[eventName] = 0;
}
if (this.events[eventName] === 0) {
throw new Error("already unlistened to event.");
}
this.events[eventName]--;
if (this.events[eventName] !== 0) {
return
}
var listener = this.rawEventListeners[eventName]
if (!listener) {
throw new Error("dom-delegator#unlistenTo: cannot " +
"unlisten to " + eventName)
}
this.target.removeEventListener(eventName, listener, true)
}
function createHandler(eventName, delegator) {
var globalListeners = delegator.globalListeners;
var delegatorTarget = delegator.target;
return handler
function handler(ev) {
var globalHandlers = globalListeners[eventName] || []
if (globalHandlers.length > 0) {
var globalEvent = new ProxyEvent(ev);
globalEvent.currentTarget = delegatorTarget;
callListeners(globalHandlers, globalEvent)
}
findAndInvokeListeners(ev.target, ev, eventName)
}
}
function findAndInvokeListeners(elem, ev, eventName) {
var listener = getListener(elem, eventName)
if (listener && listener.handlers.length > 0) {
var listenerEvent = new ProxyEvent(ev);
listenerEvent.currentTarget = listener.currentTarget
callListeners(listener.handlers, listenerEvent)
if (listenerEvent._bubbles) {
var nextTarget = listener.currentTarget.parentNode
findAndInvokeListeners(nextTarget, ev, eventName)
}
}
}
function getListener(target, type) {
// terminate recursion if parent is `null`
if (target === null) {
return null
}
var ds = DataSet(target)
// fetch list of handler fns for this event
var handler = ds[type]
var allHandler = ds.event
if (!handler && !allHandler) {
return getListener(target.parentNode, type)
}
var handlers = [].concat(handler || [], allHandler || [])
return new Listener(target, handlers)
}
function callListeners(handlers, ev) {
handlers.forEach(function (handler) {
if (typeof handler === "function") {
handler(ev)
} else if (typeof handler.handleEvent === "function") {
handler.handleEvent(ev)
} else if (handler.type === "dom-delegator-handle") {
HANDLER_STORE(handler).func(ev)
} else {
throw new Error("dom-delegator: unknown handler " +
"found: " + JSON.stringify(handlers));
}
})
}
function Listener(target, handlers) {
this.currentTarget = target
this.handlers = handlers
}
function Handle() {
this.type = "dom-delegator-handle"
}
},{"./add-event.js":46,"./proxy-event.js":59,"./remove-event.js":60,"data-set":51,"global/document":54,"weakmap-shim/create-store":57}],48:[function(require,module,exports){
var Individual = require("individual")
var cuid = require("cuid")
var globalDocument = require("global/document")
var DOMDelegator = require("./dom-delegator.js")
var versionKey = "12"
var cacheKey = "__DOM_DELEGATOR_CACHE@" + versionKey
var cacheTokenKey = "__DOM_DELEGATOR_CACHE_TOKEN@" + versionKey
var delegatorCache = Individual(cacheKey, {
delegators: {}
})
var commonEvents = [
"blur", "change", "click", "contextmenu", "dblclick",
"error","focus", "focusin", "focusout", "input", "keydown",
"keypress", "keyup", "load", "mousedown", "mouseup",
"resize", "select", "submit", "touchcancel",
"touchend", "touchstart", "unload"
]
/* Delegator is a thin wrapper around a singleton `DOMDelegator`
instance.
Only one DOMDelegator should exist because we do not want
duplicate event listeners bound to the DOM.
`Delegator` will also `listenTo()` all events unless
every caller opts out of it
*/
module.exports = Delegator
function Delegator(opts) {
opts = opts || {}
var document = opts.document || globalDocument
var cacheKey = document[cacheTokenKey]
if (!cacheKey) {
cacheKey =
document[cacheTokenKey] = cuid()
}
var delegator = delegatorCache.delegators[cacheKey]
if (!delegator) {
delegator = delegatorCache.delegators[cacheKey] =
new DOMDelegator(document)
}
if (opts.defaultEvents !== false) {
for (var i = 0; i < commonEvents.length; i++) {
delegator.listenTo(commonEvents[i])
}
}
return delegator
}
Delegator.allocateHandle = DOMDelegator.allocateHandle;
Delegator.transformHandle = DOMDelegator.transformHandle;
},{"./dom-delegator.js":47,"cuid":49,"global/document":54,"individual":55}],49:[function(require,module,exports){
/**
* cuid.js
* Collision-resistant UID generator for browsers and node.
* Sequential for fast db lookups and recency sorting.
* Safe for element IDs and server-side lookups.
*
* Extracted from CLCTR
*
* Copyright (c) Eric Elliott 2012
* MIT License
*/
/*global window, navigator, document, require, process, module */
(function (app) {
'use strict';
var namespace = 'cuid',
c = 0,
blockSize = 4,
base = 36,
discreteValues = Math.pow(base, blockSize),
pad = function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
},
randomBlock = function randomBlock() {
return pad((Math.random() *
discreteValues << 0)
.toString(base), blockSize);
},
safeCounter = function () {
c = (c < discreteValues) ? c : 0;
c++; // this is not subliminal
return c - 1;
},
api = function cuid() {
// Starting with a lowercase letter makes
// it HTML element ID friendly.
var letter = 'c', // hard-coded allows for sequential access
// timestamp
// warning: this exposes the exact date and time
// that the uid was created.
timestamp = (new Date().getTime()).toString(base),
// Prevent same-machine collisions.
counter,
// A few chars to generate distinct ids for different
// clients (so different computers are far less
// likely to generate the same id)
fingerprint = api.fingerprint(),
// Grab some more chars from Math.random()
random = randomBlock() + randomBlock();
counter = pad(safeCounter().toString(base), blockSize);
return (letter + timestamp + counter + fingerprint + random);
};
api.slug = function slug() {
var date = new Date().getTime().toString(36),
counter,
print = api.fingerprint().slice(0,1) +
api.fingerprint().slice(-1),
random = randomBlock().slice(-2);
counter = safeCounter().toString(36).slice(-4);
return date.slice(-2) +
counter + print + random;
};
api.globalCount = function globalCount() {
// We want to cache the results of this
var cache = (function calc() {
var i,
count = 0;
for (i in window) {
count++;
}
return count;
}());
api.globalCount = function () { return cache; };
return cache;
};
api.fingerprint = function browserPrint() {
return pad((navigator.mimeTypes.length +
navigator.userAgent.length).toString(36) +
api.globalCount().toString(36), 4);
};
// don't change anything from here down.
if (app.register) {
app.register(namespace, api);
} else if (typeof module !== 'undefined') {
module.exports = api;
} else {
app[namespace] = api;
}
}(this.applitude || this));
},{}],50:[function(require,module,exports){
module.exports = createHash
function createHash(elem) {
var attributes = elem.attributes
var hash = {}
if (attributes === null || attributes === undefined) {
return hash
}
for (var i = 0; i < attributes.length; i++) {
var attr = attributes[i]
if (attr.name.substr(0,5) !== "data-") {
continue
}
hash[attr.name.substr(5)] = attr.value
}
return hash
}
},{}],51:[function(require,module,exports){
var createStore = require("weakmap-shim/create-store")
var Individual = require("individual")
var createHash = require("./create-hash.js")
var hashStore = Individual("__DATA_SET_WEAKMAP@3", createStore())
module.exports = DataSet
function DataSet(elem) {
var store = hashStore(elem)
if (!store.hash) {
store.hash = createHash(elem)
}
return store.hash
}
},{"./create-hash.js":50,"individual":55,"weakmap-shim/create-store":52}],52:[function(require,module,exports){
var hiddenStore = require('./hidden-store.js');
module.exports = createStore;
function createStore() {
var key = {};
return function (obj) {
if (typeof obj !== 'object' || obj === null) {
throw new Error('Weakmap-shim: Key must be object')
}
var store = obj.valueOf(key);
return store && store.identity === key ?
store : hiddenStore(obj, key);
};
}
},{"./hidden-store.js":53}],53:[function(require,module,exports){
module.exports = hiddenStore;
function hiddenStore(obj, key) {
var store = { identity: key };
var valueOf = obj.valueOf;
Object.defineProperty(obj, "valueOf", {
value: function (value) {
return value !== key ?
valueOf.apply(this, arguments) : store;
},
writable: true
});
return store;
}
},{}],54:[function(require,module,exports){
(function (global){
var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = require('min-document');
if (typeof document !== 'undefined') {
module.exports = document;
} else {
var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
module.exports = doccy;
}
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"min-document":3}],55:[function(require,module,exports){
(function (global){
var root = typeof window !== 'undefined' ?
window : typeof global !== 'undefined' ?
global : {};
module.exports = Individual
function Individual(key, value) {
if (root[key]) {
return root[key]
}
Object.defineProperty(root, key, {
value: value
, configurable: true
})
return value
}
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],56:[function(require,module,exports){
module.exports=require(9)
},{}],57:[function(require,module,exports){
var hiddenStore = require('./hidden-store.js');
module.exports = createStore;
function createStore() {
var key = {};
return function (obj) {
if ((typeof obj !== 'object' || obj === null) &&
typeof obj !== 'function'
) {
throw new Error('Weakmap-shim: Key must be object')
}
var store = obj.valueOf(key);
return store && store.identity === key ?
store : hiddenStore(obj, key);
};
}
},{"./hidden-store.js":58}],58:[function(require,module,exports){
module.exports=require(53)
},{}],59:[function(require,module,exports){
var inherits = require("inherits")
var ALL_PROPS = [
"altKey", "bubbles", "cancelable", "ctrlKey",
"eventPhase", "metaKey", "relatedTarget", "shiftKey",
"target", "timeStamp", "type", "view", "which"
]
var KEY_PROPS = ["char", "charCode", "key", "keyCode"]
var MOUSE_PROPS = [
"button", "buttons", "clientX", "clientY", "layerX",
"layerY", "offsetX", "offsetY", "pageX", "pageY",
"screenX", "screenY", "toElement"
]
var rkeyEvent = /^key|input/
var rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/
module.exports = ProxyEvent
function ProxyEvent(ev) {
if (!(this instanceof ProxyEvent)) {
return new ProxyEvent(ev)
}
if (rkeyEvent.test(ev.type)) {
return new KeyEvent(ev)
} else if (rmouseEvent.test(ev.type)) {
return new MouseEvent(ev)
}
for (var i = 0; i < ALL_PROPS.length; i++) {
var propKey = ALL_PROPS[i]
this[propKey] = ev[propKey]
}
this._rawEvent = ev
this._bubbles = false;
}
ProxyEvent.prototype.preventDefault = function () {
this._rawEvent.preventDefault()
}
ProxyEvent.prototype.startPropagation = function () {
this._bubbles = true;
}
function MouseEvent(ev) {
for (var i = 0; i < ALL_PROPS.length; i++) {
var propKey = ALL_PROPS[i]
this[propKey] = ev[propKey]
}
for (var j = 0; j < MOUSE_PROPS.length; j++) {
var mousePropKey = MOUSE_PROPS[j]
this[mousePropKey] = ev[mousePropKey]
}
this._rawEvent = ev
}
inherits(MouseEvent, ProxyEvent)
function KeyEvent(ev) {
for (var i = 0; i < ALL_PROPS.length; i++) {
var propKey = ALL_PROPS[i]
this[propKey] = ev[propKey]
}
for (var j = 0; j < KEY_PROPS.length; j++) {
var keyPropKey = KEY_PROPS[j]
this[keyPropKey] = ev[keyPropKey]
}
this._rawEvent = ev
}
inherits(KeyEvent, ProxyEvent)
},{"inherits":56}],60:[function(require,module,exports){
var DataSet = require("data-set")
module.exports = removeEvent
function removeEvent(target, type, handler) {
var ds = DataSet(target)
var events = ds[type]
if (!events) {
return
} else if (Array.isArray(events)) {
var index = events.indexOf(handler)
if (index !== -1) {
events.splice(index, 1)
}
} else if (events === handler) {
ds[type] = null
}
}
},{"data-set":51}],61:[function(require,module,exports){
module.exports = Event
function Event() {
var listeners = []
return { broadcast: broadcast, listen: event }
function broadcast(value) {
for (var i = 0; i < listeners.length; i++) {
listeners[i](value)
}
}
function event(listener) {
listeners.push(listener)
return removeListener
function removeListener() {
var index = listeners.indexOf(listener)
if (index !== -1) {
listeners.splice(index, 1)
}
}
}
}
},{}],62:[function(require,module,exports){
var event = require("./single.js")
module.exports = multiple
function multiple(names) {
return names.reduce(function (acc, name) {
acc[name] = event()
return acc
}, {})
}
},{"./single.js":63}],63:[function(require,module,exports){
var Event = require('./event.js')
module.exports = Single
function Single() {
var tuple = Event()
return function event(value) {
if (typeof value === "function") {
return tuple.listen(value)
} else {
return tuple.broadcast(value)
}
}
}
},{"./event.js":61}],64:[function(require,module,exports){
var raf = require("raf")
var TypedError = require("error/typed")
var InvalidUpdateInRender = TypedError({
type: "main-loop.invalid.update.in-render",
message: "main-loop: Unexpected update occurred in loop.\n" +
"We are currently rendering a view, " +
"you can't change state right now.\n" +
"The diff is: {stringDiff}.\n" +
"SUGGESTED FIX: find the state mutation in your view " +
"or rendering function and remove it.\n" +
"The view should not have any side effects.\n",
diff: null,
stringDiff: null
})
module.exports = main
function main(initialState, view, opts) {
opts = opts || {}
var currentState = initialState
var create = opts.create
var diff = opts.diff
var patch = opts.patch
var redrawScheduled = false
var tree = opts.initialTree || view(currentState)
var target = opts.target || create(tree, opts)
var inRenderingTransaction = false
currentState = null
var loop = {
state: initialState,
target: target,
update: update
}
return loop
function update(state) {
if (inRenderingTransaction) {
throw InvalidUpdateInRender({
diff: state._diff,
stringDiff: JSON.stringify(state._diff)
})
}
if (currentState === null && !redrawScheduled) {
redrawScheduled = true
raf(redraw)
}
currentState = state
loop.state = state
}
function redraw() {
redrawScheduled = false
if (currentState === null) {
return
}
inRenderingTransaction = true
var newTree = view(currentState)
if (opts.createOnly) {
inRenderingTransaction = false
create(newTree, opts)
} else {
var patches = diff(tree, newTree, opts)
inRenderingTransaction = false
target = patch(target, patches, opts)
}
tree = newTree
currentState = null
}
}
},{"error/typed":67,"raf":68}],65:[function(require,module,exports){
module.exports = function(obj) {
if (typeof obj === 'string') return camelCase(obj);
return walk(obj);
};
function walk (obj) {
if (!obj || typeof obj !== 'object') return obj;
if (isDate(obj) || isRegex(obj)) return obj;
if (isArray(obj)) return map(obj, walk);
return reduce(objectKeys(obj), function (acc, key) {
var camel = camelCase(key);
acc[camel] = walk(obj[key]);
return acc;
}, {});
}
function camelCase(str) {
return str.replace(/[_.-](\w|$)/g, function (_,x) {
return x.toUpperCase();
});
}
var isArray = Array.isArray || function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
var isDate = function (obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
};
var isRegex = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
var has = Object.prototype.hasOwnProperty;
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) keys.push(key);
}
return keys;
};
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;
}
function reduce (xs, f, acc) {
if (xs.reduce) return xs.reduce(f, acc);
for (var i = 0; i < xs.length; i++) {
acc = f(acc, xs[i], i);
}
return acc;
}
},{}],66:[function(require,module,exports){
var nargs = /\{([0-9a-zA-Z]+)\}/g
var slice = Array.prototype.slice
module.exports = template
function template(string) {
var args
if (arguments.length === 2 && typeof arguments[1] === "object") {
args = arguments[1]
} else {
args = slice.call(arguments, 1)
}
if (!args || !args.hasOwnProperty) {
args = {}
}
return string.replace(nargs, function replaceArg(match, i, index) {
var result
if (string[index - 1] === "{" &&
string[index + match.length] === "}") {
return i
} else {
result = args.hasOwnProperty(i) ? args[i] : null
if (result === null || result === undefined) {
return ""
}
return result
}
})
}
},{}],67:[function(require,module,exports){
var camelize = require("camelize")
var template = require("string-template")
var extend = require("xtend/mutable")
module.exports = TypedError
function TypedError(args) {
if (!args) {
throw new Error("args is required");
}
if (!args.type) {
throw new Error("args.type is required");
}
if (!args.message) {
throw new Error("args.message is required");
}
var message = args.message
if (args.type && !args.name) {
var errorName = camelize(args.type) + "Error"
args.name = errorName[0].toUpperCase() + errorName.substr(1)
}
extend(createError, args);
createError._name = args.name;
return createError;
function createError(opts) {
var result = new Error()
Object.defineProperty(result, "type", {
value: result.type,
enumerable: true,
writable: true,
configurable: true
})
var options = extend({}, args, opts)
extend(result, options)
result.message = template(message, options)
return result
}
}
},{"camelize":65,"string-template":66,"xtend/mutable":140}],68:[function(require,module,exports){
var now = require('performance-now')
, global = typeof window === 'undefined' ? {} : window
, vendors = ['moz', 'webkit']
, suffix = 'AnimationFrame'
, raf = global['request' + suffix]
, caf = global['cancel' + suffix] || global['cancelRequest' + suffix]
, isNative = true
for(var i = 0; i < vendors.length && !raf; i++) {
raf = global[vendors[i] + 'Request' + suffix]
caf = global[vendors[i] + 'Cancel' + suffix]
|| global[vendors[i] + 'CancelRequest' + suffix]
}
// Some versions of FF have rAF but not cAF
if(!raf || !caf) {
isNative = false
var last = 0
, id = 0
, queue = []
, frameDuration = 1000 / 60
raf = function(callback) {
if(queue.length === 0) {
var _now = now()
, next = Math.max(0, frameDuration - (_now - last))
last = next + _now
setTimeout(function() {
var cp = queue.slice(0)
// Clear queue here to prevent
// callbacks from appending listeners
// to the current frame's queue
queue.length = 0
for(var i = 0; i < cp.length; i++) {
if(!cp[i].cancelled) {
try{
cp[i].callback(last)
} catch(e) {
setTimeout(function() { throw e }, 0)
}
}
}
}, Math.round(next))
}
queue.push({
handle: ++id,
callback: callback,
cancelled: false
})
return id
}
caf = function(handle) {
for(var i = 0; i < queue.length; i++) {
if(queue[i].handle === handle) {
queue[i].cancelled = true
}
}
}
}
module.exports = function(fn) {
// Wrap in a new function to prevent
// `cancel` potentially being assigned
// to the native rAF function
if(!isNative) {
return raf.call(global, fn)
}
return raf.call(global, function() {
try{
fn.apply(this, arguments)
} catch(e) {
setTimeout(function() { throw e }, 0)
}
})
}
module.exports.cancel = function() {
caf.apply(global, arguments)
}
},{"performance-now":69}],69:[function(require,module,exports){
(function (process){
// Generated by CoffeeScript 1.6.3
(function() {
var getNanoSeconds, hrtime, loadTime;
if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
module.exports = function() {
return performance.now();
};
} else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
module.exports = function() {
return (getNanoSeconds() - loadTime) / 1e6;
};
hrtime = process.hrtime;
getNanoSeconds = function() {
var hr;
hr = hrtime();
return hr[0] * 1e9 + hr[1];
};
loadTime = getNanoSeconds();
} else if (Date.now) {
module.exports = function() {
return Date.now() - loadTime;
};
loadTime = Date.now();
} else {
module.exports = function() {
return new Date().getTime() - loadTime;
};
loadTime = new Date().getTime();
}
}).call(this);
/*
//@ sourceMappingURL=performance-now.map
*/
}).call(this,require("FWaASH"))
},{"FWaASH":10}],70:[function(require,module,exports){
var setNonEnumerable = require("./lib/set-non-enumerable.js");
module.exports = addListener
function addListener(observArray, observ) {
var list = observArray._list
return observ(function (value) {
var valueList = observArray().slice()
var index = list.indexOf(observ)
// This code path should never hit. If this happens
// there's a bug in the cleanup code
if (index === -1) {
var message = "observ-array: Unremoved observ listener"
var err = new Error(message)
err.list = list
err.index = index
err.observ = observ
throw err
}
valueList.splice(index, 1, value)
setNonEnumerable(valueList, "_diff", [ [index, 1, value] ])
observArray._observSet(valueList)
})
}
},{"./lib/set-non-enumerable.js":76}],71:[function(require,module,exports){
var addListener = require('./add-listener.js')
module.exports = applyPatch
function applyPatch (valueList, args) {
var obs = this
var valueArgs = args.map(unpack)
valueList.splice.apply(valueList, valueArgs)
obs._list.splice.apply(obs._list, args)
var extraRemoveListeners = args.slice(2).map(function (observ) {
return typeof observ === "function" ?
addListener(obs, observ) :
null
})
extraRemoveListeners.unshift(args[0], args[1])
var removedListeners = obs._removeListeners.splice
.apply(obs._removeListeners, extraRemoveListeners)
removedListeners.forEach(function (removeObservListener) {
if (removeObservListener) {
removeObservListener()
}
})
return valueArgs
}
function unpack(value, index){
if (index === 0 || index === 1) {
return value
}
return typeof value === "function" ? value() : value
}
},{"./add-listener.js":70}],72:[function(require,module,exports){
var ObservArray = require("./index.js")
var slice = Array.prototype.slice
var ARRAY_METHODS = [
"concat", "slice", "every", "filter", "forEach", "indexOf",
"join", "lastIndexOf", "map", "reduce", "reduceRight",
"some", "toString", "toLocaleString"
]
var methods = ARRAY_METHODS.map(function (name) {
return [name, function () {
var res = this._list[name].apply(this._list, arguments)
if (res && Array.isArray(res)) {
res = ObservArray(res)
}
return res
}]
})
module.exports = ArrayMethods
function ArrayMethods(obs) {
obs.push = observArrayPush
obs.pop = observArrayPop
obs.shift = observArrayShift
obs.unshift = observArrayUnshift
obs.reverse = require("./array-reverse.js")
obs.sort = require("./array-sort.js")
methods.forEach(function (tuple) {
obs[tuple[0]] = tuple[1]
})
return obs
}
function observArrayPush() {
var args = slice.call(arguments)
args.unshift(this._list.length, 0)
this.splice.apply(this, args)
return this._list.length
}
function observArrayPop() {
return this.splice(this._list.length - 1, 1)[0]
}
function observArrayShift() {
return this.splice(0, 1)[0]
}
function observArrayUnshift() {
var args = slice.call(arguments)
args.unshift(0, 0)
this.splice.apply(this, args)
return this._list.length
}
function notImplemented() {
throw new Error("Pull request welcome")
}
},{"./array-reverse.js":73,"./array-sort.js":74,"./index.js":75}],73:[function(require,module,exports){
var applyPatch = require("./apply-patch.js")
var setNonEnumerable = require('./lib/set-non-enumerable.js')
module.exports = reverse
function reverse() {
var obs = this
var changes = fakeDiff(obs._list.slice().reverse())
var valueList = obs().slice().reverse()
var valueChanges = changes.map(applyPatch.bind(obs, valueList))
setNonEnumerable(valueList, "_diff", valueChanges)
obs._observSet(valueList)
return changes
}
function fakeDiff(arr) {
var _diff
var len = arr.length
if(len % 2) {
var midPoint = (len -1) / 2
var a = [0, midPoint].concat(arr.slice(0, midPoint))
var b = [midPoint +1, midPoint].concat(arr.slice(midPoint +1, len))
var _diff = [a, b]
} else {
_diff = [ [0, len].concat(arr) ]
}
return _diff
}
},{"./apply-patch.js":71,"./lib/set-non-enumerable.js":76}],74:[function(require,module,exports){
var applyPatch = require("./apply-patch.js")
var setNonEnumerable = require("./lib/set-non-enumerable.js")
module.exports = sort
function sort(compare) {
var obs = this
var list = obs._list.slice()
var unpacked = unpack(list)
var sorted = unpacked
.map(function(it) { return it.val })
.sort(compare)
var packed = repack(sorted, unpacked)
//fake diff - for perf
//adiff on 10k items === ~3200ms
//fake on 10k items === ~110ms
var changes = [ [ 0, packed.length ].concat(packed) ]
var valueChanges = changes.map(applyPatch.bind(obs, sorted))
setNonEnumerable(sorted, "_diff", valueChanges)
obs._observSet(sorted)
return changes
}
function unpack(list) {
var unpacked = []
for(var i = 0; i < list.length; i++) {
unpacked.push({
val: ("function" == typeof list[i]) ? list[i]() : list[i],
obj: list[i]
})
}
return unpacked
}
function repack(sorted, unpacked) {
var packed = []
while(sorted.length) {
var s = sorted.shift()
var indx = indexOf(s, unpacked)
if(~indx) packed.push(unpacked.splice(indx, 1)[0].obj)
}
return packed
}
function indexOf(n, h) {
for(var i = 0; i < h.length; i++) {
if(n === h[i].val) return i
}
return -1
}
},{"./apply-patch.js":71,"./lib/set-non-enumerable.js":76}],75:[function(require,module,exports){
var Observ = require("observ")
// circular dep between ArrayMethods & this file
module.exports = ObservArray
var splice = require("./splice.js")
var put = require("./put.js")
var set = require("./set.js")
var transaction = require("./transaction.js")
var ArrayMethods = require("./array-methods.js")
var addListener = require("./add-listener.js")
/* ObservArray := (Array<T>) => Observ<
Array<T> & { _diff: Array }
> & {
splice: (index: Number, amount: Number, rest...: T) =>
Array<T>,
push: (values...: T) => Number,
filter: (lambda: Function, thisValue: Any) => Array<T>,
indexOf: (item: T, fromIndex: Number) => Number
}
Fix to make it more like ObservHash.
I.e. you write observables into it.
reading methods take plain JS objects to read
and the value of the array is always an array of plain
objsect.
The observ array instance itself would have indexed
properties that are the observables
*/
function ObservArray(initialList) {
// list is the internal mutable list observ instances that
// all methods on `obs` dispatch to.
var list = initialList
var initialState = []
// copy state out of initialList into initialState
list.forEach(function (observ, index) {
initialState[index] = typeof observ === "function" ?
observ() : observ
})
var obs = Observ(initialState)
obs.splice = splice
// override set and store original for later use
obs._observSet = obs.set
obs.set = set
obs.get = get
obs.getLength = getLength
obs.put = put
obs.transaction = transaction
// you better not mutate this list directly
// this is the list of observs instances
obs._list = list
var removeListeners = list.map(function (observ) {
return typeof observ === "function" ?
addListener(obs, observ) :
null
});
// this is a list of removal functions that must be called
// when observ instances are removed from `obs.list`
// not calling this means we do not GC our observ change
// listeners. Which causes rage bugs
obs._removeListeners = removeListeners
obs._type = "observ-array"
obs._version = "3"
return ArrayMethods(obs, list)
}
function get(index) {
return this._list[index]
}
function getLength() {
return this._list.length
}
},{"./add-listener.js":70,"./array-methods.js":72,"./put.js":78,"./set.js":79,"./splice.js":80,"./transaction.js":81,"observ":87}],76:[function(require,module,exports){
module.exports = setNonEnumerable;
function setNonEnumerable(object, key, value) {
Object.defineProperty(object, key, {
value: value,
writable: true,
configurable: true,
enumerable: false
});
}
},{}],77:[function(require,module,exports){
function head (a) {
return a[0]
}
function last (a) {
return a[a.length - 1]
}
function tail(a) {
return a.slice(1)
}
function retreat (e) {
return e.pop()
}
function hasLength (e) {
return e.length
}
function any(ary, test) {
for(var i=0;i<ary.length;i++)
if(test(ary[i]))
return true
return false
}
function score (a) {
return a.reduce(function (s, a) {
return s + a.length + a[1] + 1
}, 0)
}
function best (a, b) {
return score(a) <= score(b) ? a : b
}
var _rules // set at the bottom
// note, naive implementation. will break on circular objects.
function _equal(a, b) {
if(a && !b) return false
if(Array.isArray(a))
if(a.length != b.length) return false
if(a && 'object' == typeof a) {
for(var i in a)
if(!_equal(a[i], b[i])) return false
for(var i in b)
if(!_equal(a[i], b[i])) return false
return true
}
return a == b
}
function getArgs(args) {
return args.length == 1 ? args[0] : [].slice.call(args)
}
// return the index of the element not like the others, or -1
function oddElement(ary, cmp) {
var c
function guess(a) {
var odd = -1
c = 0
for (var i = a; i < ary.length; i ++) {
if(!cmp(ary[a], ary[i])) {
odd = i, c++
}
}
return c > 1 ? -1 : odd
}
//assume that it is the first element.
var g = guess(0)
if(-1 != g) return g
//0 was the odd one, then all the other elements are equal
//else there more than one different element
guess(1)
return c == 0 ? 0 : -1
}
var exports = module.exports = function (deps, exports) {
var equal = (deps && deps.equal) || _equal
exports = exports || {}
exports.lcs =
function lcs() {
var cache = {}
var args = getArgs(arguments)
var a = args[0], b = args[1]
function key (a,b){
return a.length + ':' + b.length
}
//find length that matches at the head
if(args.length > 2) {
//if called with multiple sequences
//recurse, since lcs(a, b, c, d) == lcs(lcs(a,b), lcs(c,d))
args.push(lcs(args.shift(), args.shift()))
return lcs(args)
}
//this would be improved by truncating input first
//and not returning an lcs as an intermediate step.
//untill that is a performance problem.
var start = 0, end = 0
for(var i = 0; i < a.length && i < b.length
&& equal(a[i], b[i])
; i ++
)
start = i + 1
if(a.length === start)
return a.slice()
for(var i = 0; i < a.length - start && i < b.length - start
&& equal(a[a.length - 1 - i], b[b.length - 1 - i])
; i ++
)
end = i
function recurse (a, b) {
if(!a.length || !b.length) return []
//avoid exponential time by caching the results
if(cache[key(a, b)]) return cache[key(a, b)]
if(equal(a[0], b[0]))
return [head(a)].concat(recurse(tail(a), tail(b)))
else {
var _a = recurse(tail(a), b)
var _b = recurse(a, tail(b))
return cache[key(a,b)] = _a.length > _b.length ? _a : _b
}
}
var middleA = a.slice(start, a.length - end)
var middleB = b.slice(start, b.length - end)
return (
a.slice(0, start).concat(
recurse(middleA, middleB)
).concat(a.slice(a.length - end))
)
}
// given n sequences, calc the lcs, and then chunk strings into stable and unstable sections.
// unstable chunks are passed to build
exports.chunk =
function (q, build) {
var q = q.map(function (e) { return e.slice() })
var lcs = exports.lcs.apply(null, q)
var all = [lcs].concat(q)
function matchLcs (e) {
if(e.length && !lcs.length || !e.length && lcs.length)
return false //incase the last item is null
return equal(last(e), last(lcs)) || ((e.length + lcs.length) === 0)
}
while(any(q, hasLength)) {
//if each element is at the lcs then this chunk is stable.
while(q.every(matchLcs) && q.every(hasLength))
all.forEach(retreat)
//collect the changes in each array upto the next match with the lcs
var c = false
var unstable = q.map(function (e) {
var change = []
while(!matchLcs(e)) {
change.unshift(retreat(e))
c = true
}
return change
})
if(c) build(q[0].length, unstable)
}
}
//calculate a diff this is only updates
exports.optimisticDiff =
function (a, b) {
var M = Math.max(a.length, b.length)
var m = Math.min(a.length, b.length)
var patch = []
for(var i = 0; i < M; i++)
if(a[i] !== b[i]) {
var cur = [i,0], deletes = 0
while(a[i] !== b[i] && i < m) {
cur[1] = ++deletes
cur.push(b[i++])
}
//the rest are deletes or inserts
if(i >= m) {
//the rest are deletes
if(a.length > b.length)
cur[1] += a.length - b.length
//the rest are inserts
else if(a.length < b.length)
cur = cur.concat(b.slice(a.length))
}
patch.push(cur)
}
return patch
}
exports.diff =
function (a, b) {
var optimistic = exports.optimisticDiff(a, b)
var changes = []
exports.chunk([a, b], function (index, unstable) {
var del = unstable.shift().length
var insert = unstable.shift()
changes.push([index, del].concat(insert))
})
return best(optimistic, changes)
}
exports.patch = function (a, changes, mutate) {
if(mutate !== true) a = a.slice(a)//copy a
changes.forEach(function (change) {
[].splice.apply(a, change)
})
return a
}
// http://en.wikipedia.org/wiki/Concestor
// me, concestor, you...
exports.merge = function () {
var args = getArgs(arguments)
var patch = exports.diff3(args)
return exports.patch(args[0], patch)
}
exports.diff3 = function () {
var args = getArgs(arguments)
var r = []
exports.chunk(args, function (index, unstable) {
var mine = unstable[0]
var insert = resolve(unstable)
if(equal(mine, insert)) return
r.push([index, mine.length].concat(insert))
})
return r
}
exports.oddOneOut =
function oddOneOut (changes) {
changes = changes.slice()
//put the concestor first
changes.unshift(changes.splice(1,1)[0])
var i = oddElement(changes, equal)
if(i == 0) // concestor was different, 'false conflict'
return changes[1]
if (~i)
return changes[i]
}
exports.insertMergeOverDelete =
//i've implemented this as a seperate rule,
//because I had second thoughts about this.
function insertMergeOverDelete (changes) {
changes = changes.slice()
changes.splice(1,1)// remove concestor
//if there is only one non empty change thats okay.
//else full confilct
for (var i = 0, nonempty; i < changes.length; i++)
if(changes[i].length)
if(!nonempty) nonempty = changes[i]
else return // full conflict
return nonempty
}
var rules = (deps && deps.rules) || [exports.oddOneOut, exports.insertMergeOverDelete]
function resolve (changes) {
var l = rules.length
for (var i in rules) { // first
var c = rules[i] && rules[i](changes)
if(c) return c
}
changes.splice(1,1) // remove concestor
//returning the conflicts as an object is a really bad idea,
// because == will not detect they are the same. and conflicts build.
// better to use
// '<<<<<<<<<<<<<'
// of course, i wrote this before i started on snob, so i didn't know that then.
/*var conflict = ['>>>>>>>>>>>>>>>>']
while(changes.length)
conflict = conflict.concat(changes.shift()).concat('============')
conflict.pop()
conflict.push ('<<<<<<<<<<<<<<<')
changes.unshift ('>>>>>>>>>>>>>>>')
return conflict*/
//nah, better is just to use an equal can handle objects
return {'?': changes}
}
return exports
}
exports(null, exports)
},{}],78:[function(require,module,exports){
var addListener = require("./add-listener.js")
var setNonEnumerable = require("./lib/set-non-enumerable.js");
module.exports = put
// `obs.put` is a mutable implementation of `array[index] = value`
// that mutates both `list` and the internal `valueList` that
// is the current value of `obs` itself
function put(index, value) {
var obs = this
var valueList = obs().slice()
var originalLength = valueList.length
valueList[index] = typeof value === "function" ? value() : value
obs._list[index] = value
// remove past value listener if was observ
var removeListener = obs._removeListeners[index]
if (removeListener){
removeListener()
}
// add listener to value if observ
obs._removeListeners[index] = typeof value === "function" ?
addListener(obs, value) :
null
// fake splice diff
var valueArgs = index < originalLength ?
[index, 1, valueList[index]] :
[index, 0, valueList[index]]
setNonEnumerable(valueList, "_diff", [valueArgs])
obs._observSet(valueList)
return value
}
},{"./add-listener.js":70,"./lib/set-non-enumerable.js":76}],79:[function(require,module,exports){
var applyPatch = require("./apply-patch.js")
var setNonEnumerable = require("./lib/set-non-enumerable.js")
var adiff = require("adiff")
module.exports = set
function set(rawList) {
if (!Array.isArray(rawList)) rawList = []
var obs = this
var changes = adiff.diff(obs._list, rawList)
var valueList = obs().slice()
var valueChanges = changes.map(applyPatch.bind(obs, valueList))
setNonEnumerable(valueList, "_diff", valueChanges)
obs._observSet(valueList)
return changes
}
},{"./apply-patch.js":71,"./lib/set-non-enumerable.js":76,"adiff":77}],80:[function(require,module,exports){
var slice = Array.prototype.slice
var addListener = require("./add-listener.js")
var setNonEnumerable = require("./lib/set-non-enumerable.js");
module.exports = splice
// `obs.splice` is a mutable implementation of `splice()`
// that mutates both `list` and the internal `valueList` that
// is the current value of `obs` itself
function splice(index, amount) {
var obs = this
var args = slice.call(arguments, 0)
var valueList = obs().slice()
// generate a list of args to mutate the internal
// list of only obs
var valueArgs = args.map(function (value, index) {
if (index === 0 || index === 1) {
return value
}
// must unpack observables that we are adding
return typeof value === "function" ? value() : value
})
valueList.splice.apply(valueList, valueArgs)
// we remove the observs that we remove
var removed = obs._list.splice.apply(obs._list, args)
var extraRemoveListeners = args.slice(2).map(function (observ) {
return typeof observ === "function" ?
addListener(obs, observ) :
null
})
extraRemoveListeners.unshift(args[0], args[1])
var removedListeners = obs._removeListeners.splice
.apply(obs._removeListeners, extraRemoveListeners)
removedListeners.forEach(function (removeObservListener) {
if (removeObservListener) {
removeObservListener()
}
})
setNonEnumerable(valueList, "_diff", [valueArgs])
obs._observSet(valueList)
return removed
}
},{"./add-listener.js":70,"./lib/set-non-enumerable.js":76}],81:[function(require,module,exports){
module.exports = transaction
function transaction (func) {
var obs = this
var rawList = obs._list.slice()
if (func(rawList) !== false){ // allow cancel
return obs.set(rawList)
}
}
},{}],82:[function(require,module,exports){
var Observ = require("observ")
var extend = require("xtend")
var blackList = ["name", "_diff", "_type", "_version"]
var blackListReasons = {
"name": "Clashes with `Function.prototype.name`.\n",
"_diff": "_diff is reserved key of observ-struct.\n",
"_type": "_type is reserved key of observ-struct.\n",
"_version": "_version is reserved key of observ-struct.\n"
}
var NO_TRANSACTION = {}
function setNonEnumerable(object, key, value) {
Object.defineProperty(object, key, {
value: value,
writable: true,
configurable: true,
enumerable: false
})
}
/* ObservStruct := (Object<String, Observ<T>>) =>
Object<String, Observ<T>> &
Observ<Object<String, T> & {
_diff: Object<String, Any>
}>
*/
module.exports = ObservStruct
function ObservStruct(struct) {
var keys = Object.keys(struct)
var initialState = {}
var currentTransaction = NO_TRANSACTION
var nestedTransaction = NO_TRANSACTION
keys.forEach(function (key) {
if (blackList.indexOf(key) !== -1) {
throw new Error("cannot create an observ-struct " +
"with a key named '" + key + "'.\n" +
blackListReasons[key]);
}
var observ = struct[key]
initialState[key] = typeof observ === "function" ?
observ() : observ
})
var obs = Observ(initialState)
keys.forEach(function (key) {
var observ = struct[key]
obs[key] = observ
if (typeof observ === "function") {
observ(function (value) {
if (nestedTransaction === value) {
return
}
var state = extend(obs())
state[key] = value
var diff = {}
diff[key] = value && value._diff ?
value._diff : value
setNonEnumerable(state, "_diff", diff)
currentTransaction = state
obs.set(state)
currentTransaction = NO_TRANSACTION
})
}
})
var _set = obs.set
obs.set = function trackDiff(value) {
if (currentTransaction === value) {
return _set(value)
}
var newState = extend(value)
setNonEnumerable(newState, "_diff", value)
_set(newState)
}
obs(function (newState) {
if (currentTransaction === newState) {
return
}
keys.forEach(function (key) {
var observ = struct[key]
var newObservValue = newState[key]
if (typeof observ === "function" &&
observ() !== newObservValue
) {
nestedTransaction = newObservValue
observ.set(newState[key])
nestedTransaction = NO_TRANSACTION
}
})
})
obs._type = "observ-struct"
obs._version = "5"
return obs
}
},{"observ":87,"xtend":83}],83:[function(require,module,exports){
module.exports = extend
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key]
}
}
}
return target
}
},{}],84:[function(require,module,exports){
var Observ = require('observ')
var extend = require('xtend')
var NO_TRANSACTION = {}
module.exports = ObservVarhash
function ObservVarhash (hash, createValue) {
createValue = createValue || function (obj) { return obj }
var initialState = {}
var currentTransaction = NO_TRANSACTION
var nestedTransaction = NO_TRANSACTION
var obs = Observ(initialState)
setNonEnumerable(obs, '_removeListeners', {})
setNonEnumerable(obs, 'get', get.bind(obs))
setNonEnumerable(obs, 'put', put.bind(obs))
setNonEnumerable(obs, 'delete', del.bind(obs))
for (var key in hash) {
obs[key] = isFn(hash[key]) ? hash[key] : createValue(hash[key], key)
if (isFn(obs[key])) {
obs._removeListeners[key] = obs[key](watch(obs, key))
}
}
var _set = obs.set
obs.set = function trackDiff (value) {
if (currentTransaction === value) {
return _set(value)
}
var newState = extend(value)
setNonEnumerable(newState, '_diff', value)
_set(newState)
}
setNonEnumerable(obs, 'set', obs.set)
var newState = {}
for (key in hash) {
var observ = obs[key]
checkKey(key)
newState[key] = isFn(observ) ? observ() : observ
}
obs.set(newState)
obs(function (newState) {
if (currentTransaction === newState) {
return
}
for (var key in hash) {
var observ = hash[key]
var newObservValue = newState[key]
if (isFn(observ) && observ() !== newState[key]) {
nestedTransaction = newObservValue
observ.set(newState[key])
nestedTransaction = NO_TRANSACTION
}
}
})
function put (key, val) {
checkKey(key)
if (val === undefined) {
throw new Error('cannot varhash.put(key, undefined).')
}
var observ = isFn(val) ? val : createValue(val, key)
var state = extend(this())
state[key] = isFn(observ) ? observ() : observ
if (isFn(this._removeListeners[key])) {
this._removeListeners[key]()
}
this._removeListeners[key] = isFn(observ)
? observ(watch(this, key)) : null
setNonEnumerable(state, '_diff', diff(key, state[key]))
this[key] = observ
currentTransaction = state
_set(state)
currentTransaction = NO_TRANSACTION
return this
}
function del (key) {
var state = extend(this())
if (isFn(this._removeListeners[key])) {
this._removeListeners[key]()
}
delete this._removeListeners[key]
delete state[key]
delete this[key]
setNonEnumerable(state, '_diff', diff(key, undefined))
_set(state)
return this
}
return obs
// processing
function watch (obs, key) {
return function (value) {
if (nestedTransaction === value) {
return
}
var state = extend(obs())
state[key] = value
setNonEnumerable(state, '_diff', diff(key, value))
currentTransaction = state
obs.set(state)
currentTransaction = NO_TRANSACTION
}
}
}
// access and mutate
function get (key) {
return this[key]
}
function diff (key, value) {
var obj = {}
obj[key] = value && value._diff ? value._diff : value
return obj
}
function isFn (obj) {
return typeof obj === 'function'
}
function setNonEnumerable (object, key, value) {
Object.defineProperty(object, key, {
value: value,
writable: true,
configurable: true,
enumerable: false
})
}
// errors
var blacklist = {
name: 'Clashes with `Function.prototype.name`.',
get: 'get is a reserved key of observ-varhash method',
put: 'put is a reserved key of observ-varhash method',
'delete': 'delete is a reserved key of observ-varhash method',
_diff: '_diff is a reserved key of observ-varhash method',
_removeListeners: '_removeListeners is a reserved key of observ-varhash'
}
function checkKey (key) {
if (!blacklist[key]) return
throw new Error(
'cannot create an observ-varhash with key `' + key + '`. ' + blacklist[key]
)
}
},{"observ":87,"xtend":85}],85:[function(require,module,exports){
module.exports=require(83)
},{}],86:[function(require,module,exports){
var Observable = require("./index.js")
module.exports = computed
function computed(observables, lambda) {
var values = observables.map(function (o) {
return o()
})
var result = Observable(lambda.apply(null, values))
observables.forEach(function (o, index) {
o(function (newValue) {
values[index] = newValue
result.set(lambda.apply(null, values))
})
})
return result
}
},{"./index.js":87}],87:[function(require,module,exports){
module.exports = Observable
function Observable(value) {
var listeners = []
value = value === undefined ? null : value
observable.set = function (v) {
value = v
listeners.forEach(function (f) {
f(v)
})
}
return observable
function observable(listener) {
if (!listener) {
return value
}
listeners.push(listener)
return function remove() {
listeners.splice(listeners.indexOf(listener), 1)
}
}
}
},{}],88:[function(require,module,exports){
module.exports = watch
function watch(observable, listener) {
var remove = observable(listener)
listener(observable())
return remove
}
},{}],89:[function(require,module,exports){
var Delegator = require('dom-delegator')
module.exports = BaseEvent
function BaseEvent(lambda) {
return EventHandler;
function EventHandler(fn, data, opts) {
var handler = {
fn: fn,
data: data || {},
opts: opts || {},
handleEvent: handleEvent
}
if (fn && fn.type === 'dom-delegator-handle') {
return Delegator.transformHandle(fn,
handleLambda.bind(handler))
}
return handler;
}
function handleLambda(ev, broadcast) {
if (this.opts.startPropagation && ev.startPropagation) {
ev.startPropagation();
}
return lambda.call(this, ev, broadcast)
}
function handleEvent(ev) {
var self = this
if (self.opts.startPropagation && ev.startPropagation) {
ev.startPropagation()
}
lambda.call(self, ev, broadcast)
function broadcast(value) {
if (typeof self.fn === 'function') {
self.fn(value)
} else {
self.fn.write(value)
}
}
}
}
},{"dom-delegator":48}],90:[function(require,module,exports){
var extend = require('xtend')
var getFormData = require('form-data-set/element')
var BaseEvent = require('./base-event.js')
var VALID_CHANGE = ['checkbox', 'file', 'select-multiple', 'select-one'];
var VALID_INPUT = ['color', 'date', 'datetime', 'datetime-local', 'email',
'month', 'number', 'password', 'range', 'search', 'tel', 'text', 'time',
'url', 'week'];
module.exports = BaseEvent(changeLambda);
function changeLambda(ev, broadcast) {
var target = ev.target
var isValid =
(ev.type === 'input' && VALID_INPUT.indexOf(target.type) !== -1) ||
(ev.type === 'change' && VALID_CHANGE.indexOf(target.type) !== -1);
if (!isValid) {
if (ev.startPropagation) {
ev.startPropagation()
}
return
}
var value = getFormData(ev.currentTarget)
var data = extend(value, this.data)
broadcast(data)
}
},{"./base-event.js":89,"form-data-set/element":95,"xtend":98}],91:[function(require,module,exports){
var BaseEvent = require('./base-event.js');
module.exports = BaseEvent(clickLambda);
function clickLambda(ev, broadcast) {
var opts = this.opts;
if (!opts.ctrl && ev.ctrlKey) {
return;
}
if (!opts.meta && ev.metaKey) {
return;
}
if (!opts.rightClick && ev.which === 2) {
return;
}
if (this.opts.preventDefault && ev.preventDefault) {
ev.preventDefault();
}
broadcast(this.data);
}
},{"./base-event.js":89}],92:[function(require,module,exports){
var BaseEvent = require('./base-event.js');
module.exports = BaseEvent(eventLambda);
function eventLambda(ev, broadcast) {
broadcast(this.data);
}
},{"./base-event.js":89}],93:[function(require,module,exports){
var BaseEvent = require('./base-event.js');
module.exports = BaseEvent(keyLambda);
function keyLambda(ev, broadcast) {
var key = this.opts.key;
if (ev.keyCode === key) {
broadcast(this.data);
}
}
},{"./base-event.js":89}],94:[function(require,module,exports){
var slice = Array.prototype.slice
module.exports = iterativelyWalk
function iterativelyWalk(nodes, cb) {
if (!('length' in nodes)) {
nodes = [nodes]
}
nodes = slice.call(nodes)
while(nodes.length) {
var node = nodes.shift(),
ret = cb(node)
if (ret) {
return ret
}
if (node.childNodes && node.childNodes.length) {
nodes = slice.call(node.childNodes).concat(nodes)
}
}
}
},{}],95:[function(require,module,exports){
var walk = require('dom-walk')
var FormData = require('./index.js')
module.exports = getFormData
function buildElems(rootElem) {
var hash = {}
if (rootElem.name) {
hash[rootElem.name] = rootElem
}
walk(rootElem, function (child) {
if (child.name) {
hash[child.name] = child
}
})
return hash
}
function getFormData(rootElem) {
var elements = buildElems(rootElem)
return FormData(elements)
}
},{"./index.js":96,"dom-walk":94}],96:[function(require,module,exports){
/*jshint maxcomplexity: 10*/
module.exports = FormData
//TODO: Massive spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#constructing-form-data-set
function FormData(elements) {
return Object.keys(elements).reduce(function (acc, key) {
var elem = elements[key]
acc[key] = valueOfElement(elem)
return acc
}, {})
}
function valueOfElement(elem) {
if (typeof elem === "function") {
return elem()
} else if (containsRadio(elem)) {
var elems = toList(elem)
var checked = elems.filter(function (elem) {
return elem.checked
})[0] || null
return checked ? checked.value : null
} else if (Array.isArray(elem)) {
return elem.map(valueOfElement).filter(filterNull)
} else if (elem.tagName === undefined && elem.nodeType === undefined) {
return FormData(elem)
} else if (elem.tagName === "INPUT" && isChecked(elem)) {
if (elem.hasAttribute("value")) {
return elem.checked ? elem.value : null
} else {
return elem.checked
}
} else if (elem.tagName === "INPUT") {
return elem.value
} else if (elem.tagName === "TEXTAREA") {
return elem.value
} else if (elem.tagName === "SELECT") {
return elem.value
}
}
function isChecked(elem) {
return elem.type === "checkbox" || elem.type === "radio"
}
function containsRadio(value) {
if (value.tagName || value.nodeType) {
return false
}
var elems = toList(value)
return elems.some(function (elem) {
return elem.tagName === "INPUT" && elem.type === "radio"
})
}
function toList(value) {
if (Array.isArray(value)) {
return value
}
return Object.keys(value).map(prop, value)
}
function prop(x) {
return this[x]
}
function filterNull(val) {
return val !== null
}
},{}],97:[function(require,module,exports){
module.exports = hasKeys
function hasKeys(source) {
return source !== null &&
(typeof source === "object" ||
typeof source === "function")
}
},{}],98:[function(require,module,exports){
var hasKeys = require("./has-keys")
module.exports = extend
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
if (!hasKeys(source)) {
continue
}
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key]
}
}
}
return target
}
},{"./has-keys":97}],99:[function(require,module,exports){
var extend = require('xtend')
var getFormData = require('form-data-set/element')
var BaseEvent = require('./base-event.js');
var ENTER = 13
module.exports = BaseEvent(submitLambda);
function submitLambda(ev, broadcast) {
var target = ev.target
var isValid =
(ev.type === 'submit' && target.tagName === 'FORM') ||
(ev.type === 'click' && target.tagName === 'BUTTON') ||
(ev.type === 'click' && target.type === 'submit') ||
(
(target.type === 'text') &&
(ev.keyCode === ENTER && ev.type === 'keydown')
)
if (!isValid) {
if (ev.startPropagation) {
ev.startPropagation()
}
return
}
var value = getFormData(ev.currentTarget)
var data = extend(value, this.data)
if (ev.preventDefault) {
ev.preventDefault();
}
broadcast(data);
}
},{"./base-event.js":89,"form-data-set/element":95,"xtend":98}],100:[function(require,module,exports){
var extend = require('xtend')
var getFormData = require('form-data-set/element')
var BaseEvent = require('./base-event.js');
module.exports = BaseEvent(valueLambda);
function valueLambda(ev, broadcast) {
var value = getFormData(ev.currentTarget)
var data = extend(value, this.data)
broadcast(data);
}
},{"./base-event.js":89,"form-data-set/element":95,"xtend":98}],101:[function(require,module,exports){
function Thunk(fn, args, key, eqArgs) {
this.fn = fn;
this.args = args;
this.key = key;
this.eqArgs = eqArgs;
}
Thunk.prototype.type = 'Thunk';
Thunk.prototype.render = render;
module.exports = Thunk;
function shouldUpdate(current, previous) {
if (!current || !previous || current.fn !== previous.fn) {
return true;
}
var cargs = current.args;
var pargs = previous.args;
return !current.eqArgs(cargs, pargs);
}
function render(previous) {
if (shouldUpdate(this, previous)) {
return this.fn.apply(null, this.args);
} else {
return previous.vnode;
}
}
},{}],102:[function(require,module,exports){
var Partial = require('./partial');
module.exports = Partial();
},{"./partial":103}],103:[function(require,module,exports){
var shallowEq = require('./shallow-eq');
var Thunk = require('./immutable-thunk');
module.exports = createPartial;
function createPartial(eq) {
return function partial(fn) {
var args = copyOver(arguments, 1);
var firstArg = args[0];
var key;
var eqArgs = eq || shallowEq;
if (typeof firstArg === 'object' && firstArg !== null) {
if ('key' in firstArg) {
key = firstArg.key;
} else if ('id' in firstArg) {
key = firstArg.id;
}
}
return new Thunk(fn, args, key, eqArgs);
};
}
function copyOver(list, offset) {
var newList = [];
for (var i = list.length - 1; i >= offset; i--) {
newList[i - offset] = list[i];
}
return newList;
}
},{"./immutable-thunk":101,"./shallow-eq":104}],104:[function(require,module,exports){
module.exports = shallowEq;
function shallowEq(currentArgs, previousArgs) {
if (currentArgs.length === 0 && previousArgs.length === 0) {
return true;
}
if (currentArgs.length !== previousArgs.length) {
return false;
}
var len = currentArgs.length;
for (var i = 0; i < len; i++) {
if (currentArgs[i] !== previousArgs[i]) {
return false;
}
}
return true;
}
},{}],105:[function(require,module,exports){
module.exports=require(50)
},{}],106:[function(require,module,exports){
module.exports=require(51)
},{"./create-hash.js":105,"individual":107,"weakmap-shim/create-store":108}],107:[function(require,module,exports){
module.exports=require(55)
},{}],108:[function(require,module,exports){
module.exports=require(52)
},{"./hidden-store.js":109}],109:[function(require,module,exports){
module.exports=require(53)
},{}],110:[function(require,module,exports){
module.exports=require(65)
},{}],111:[function(require,module,exports){
module.exports=require(66)
},{}],112:[function(require,module,exports){
module.exports=require(67)
},{"camelize":110,"string-template":111,"xtend/mutable":140}],113:[function(require,module,exports){
module.exports=require(54)
},{"min-document":3}],114:[function(require,module,exports){
"use strict";
module.exports = function isObject(x) {
return typeof x === "object" && x !== null;
};
},{}],115:[function(require,module,exports){
var nativeIsArray = Array.isArray
var toString = Object.prototype.toString
module.exports = nativeIsArray || isArray
function isArray(obj) {
return toString.call(obj) === "[object Array]"
}
},{}],116:[function(require,module,exports){
var isObject = require("is-object")
var isHook = require("../vnode/is-vhook.js")
module.exports = applyProperties
function applyProperties(node, props, previous) {
for (var propName in props) {
var propValue = props[propName]
if (propValue === undefined) {
removeProperty(node, props, previous, propName);
} else if (isHook(propValue)) {
propValue.hook(node,
propName,
previous ? previous[propName] : undefined)
} else {
if (isObject(propValue)) {
patchObject(node, props, previous, propName, propValue);
} else if (propValue !== undefined) {
node[propName] = propValue
}
}
}
}
function removeProperty(node, props, previous, propName) {
if (previous) {
var previousValue = previous[propName]
if (!isHook(previousValue)) {
if (propName === "attributes") {
for (var attrName in previousValue) {
node.removeAttribute(attrName)
}
} else if (propName === "style") {
for (var i in previousValue) {
node.style[i] = ""
}
} else if (typeof previousValue === "string") {
node[propName] = ""
} else {
node[propName] = null
}
} else if (previousValue.unhook) {
previousValue.unhook(node, propName)
}
}
}
function patchObject(node, props, previous, propName, propValue) {
var previousValue = previous ? previous[propName] : undefined
// Set attributes
if (propName === "attributes") {
for (var attrName in propValue) {
var attrValue = propValue[attrName]
if (attrValue === undefined) {
node.removeAttribute(attrName)
} else {
node.setAttribute(attrName, attrValue)
}
}
return
}
if(previousValue && isObject(previousValue) &&
getPrototype(previousValue) !== getPrototype(propValue)) {
node[propName] = propValue
return
}
if (!isObject(node[propName])) {
node[propName] = {}
}
var replacer = propName === "style" ? "" : undefined
for (var k in propValue) {
var value = propValue[k]
node[propName][k] = (value === undefined) ? replacer : value
}
}
function getPrototype(value) {
if (Object.getPrototypeOf) {
return Object.getPrototypeOf(value)
} else if (value.__proto__) {
return value.__proto__
} else if (value.constructor) {
return value.constructor.prototype
}
}
},{"../vnode/is-vhook.js":130,"is-object":114}],117:[function(require,module,exports){
var document = require("global/document")
var applyProperties = require("./apply-properties")
var isVNode = require("../vnode/is-vnode.js")
var isVText = require("../vnode/is-vtext.js")
var isWidget = require("../vnode/is-widget.js")
var handleThunk = require("../vnode/handle-thunk.js")
module.exports = createElement
function createElement(vnode, opts) {
var doc = opts ? opts.document || document : document
var warn = opts ? opts.warn : null
vnode = handleThunk(vnode).a
if (isWidget(vnode)) {
return vnode.init()
} else if (isVText(vnode)) {
return doc.createTextNode(vnode.text)
} else if (!isVNode(vnode)) {
if (warn) {
warn("Item is not a valid virtual dom node", vnode)
}
return null
}
var node = (vnode.namespace === null) ?
doc.createElement(vnode.tagName) :
doc.createElementNS(vnode.namespace, vnode.tagName)
var props = vnode.properties
applyProperties(node, props)
var children = vnode.children
for (var i = 0; i < children.length; i++) {
var childNode = createElement(children[i], opts)
if (childNode) {
node.appendChild(childNode)
}
}
return node
}
},{"../vnode/handle-thunk.js":128,"../vnode/is-vnode.js":131,"../vnode/is-vtext.js":132,"../vnode/is-widget.js":133,"./apply-properties":116,"global/document":113}],118:[function(require,module,exports){
// Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
// We don't want to read all of the DOM nodes in the tree so we use
// the in-order tree indexing to eliminate recursion down certain branches.
// We only recurse into a DOM node if we know that it contains a child of
// interest.
var noChild = {}
module.exports = domIndex
function domIndex(rootNode, tree, indices, nodes) {
if (!indices || indices.length === 0) {
return {}
} else {
indices.sort(ascending)
return recurse(rootNode, tree, indices, nodes, 0)
}
}
function recurse(rootNode, tree, indices, nodes, rootIndex) {
nodes = nodes || {}
if (rootNode) {
if (indexInRange(indices, rootIndex, rootIndex)) {
nodes[rootIndex] = rootNode
}
var vChildren = tree.children
if (vChildren) {
var childNodes = rootNode.childNodes
for (var i = 0; i < tree.children.length; i++) {
rootIndex += 1
var vChild = vChildren[i] || noChild
var nextIndex = rootIndex + (vChild.count || 0)
// skip recursion down the tree if there are no nodes down here
if (indexInRange(indices, rootIndex, nextIndex)) {
recurse(childNodes[i], vChild, indices, nodes, rootIndex)
}
rootIndex = nextIndex
}
}
}
return nodes
}
// Binary search for an index in the interval [left, right]
function indexInRange(indices, left, right) {
if (indices.length === 0) {
return false
}
var minIndex = 0
var maxIndex = indices.length - 1
var currentIndex
var currentItem
while (minIndex <= maxIndex) {
currentIndex = ((maxIndex + minIndex) / 2) >> 0
currentItem = indices[currentIndex]
if (minIndex === maxIndex) {
return currentItem >= left && currentItem <= right
} else if (currentItem < left) {
minIndex = currentIndex + 1
} else if (currentItem > right) {
maxIndex = currentIndex - 1
} else {
return true
}
}
return false;
}
function ascending(a, b) {
return a > b ? 1 : -1
}
},{}],119:[function(require,module,exports){
var applyProperties = require("./apply-properties")
var isWidget = require("../vnode/is-widget.js")
var VPatch = require("../vnode/vpatch.js")
var render = require("./create-element")
var updateWidget = require("./update-widget")
module.exports = applyPatch
function applyPatch(vpatch, domNode, renderOptions) {
var type = vpatch.type
var vNode = vpatch.vNode
var patch = vpatch.patch
switch (type) {
case VPatch.REMOVE:
return removeNode(domNode, vNode)
case VPatch.INSERT:
return insertNode(domNode, patch, renderOptions)
case VPatch.VTEXT:
return stringPatch(domNode, vNode, patch, renderOptions)
case VPatch.WIDGET:
return widgetPatch(domNode, vNode, patch, renderOptions)
case VPatch.VNODE:
return vNodePatch(domNode, vNode, patch, renderOptions)
case VPatch.ORDER:
reorderChildren(domNode, patch)
return domNode
case VPatch.PROPS:
applyProperties(domNode, patch, vNode.properties)
return domNode
case VPatch.THUNK:
return replaceRoot(domNode,
renderOptions.patch(domNode, patch, renderOptions))
default:
return domNode
}
}
function removeNode(domNode, vNode) {
var parentNode = domNode.parentNode
if (parentNode) {
parentNode.removeChild(domNode)
}
destroyWidget(domNode, vNode);
return null
}
function insertNode(parentNode, vNode, renderOptions) {
var newNode = render(vNode, renderOptions)
if (parentNode) {
parentNode.appendChild(newNode)
}
return parentNode
}
function stringPatch(domNode, leftVNode, vText, renderOptions) {
var newNode
if (domNode.nodeType === 3) {
domNode.replaceData(0, domNode.length, vText.text)
newNode = domNode
} else {
var parentNode = domNode.parentNode
newNode = render(vText, renderOptions)
if (parentNode) {
parentNode.replaceChild(newNode, domNode)
}
}
return newNode
}
function widgetPatch(domNode, leftVNode, widget, renderOptions) {
var updating = updateWidget(leftVNode, widget)
var newNode
if (updating) {
newNode = widget.update(leftVNode, domNode) || domNode
} else {
newNode = render(widget, renderOptions)
}
var parentNode = domNode.parentNode
if (parentNode && newNode !== domNode) {
parentNode.replaceChild(newNode, domNode)
}
if (!updating) {
destroyWidget(domNode, leftVNode)
}
return newNode
}
function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
var parentNode = domNode.parentNode
var newNode = render(vNode, renderOptions)
if (parentNode) {
parentNode.replaceChild(newNode, domNode)
}
return newNode
}
function destroyWidget(domNode, w) {
if (typeof w.destroy === "function" && isWidget(w)) {
w.destroy(domNode)
}
}
function reorderChildren(domNode, bIndex) {
var children = []
var childNodes = domNode.childNodes
var len = childNodes.length
var i
var reverseIndex = bIndex.reverse
for (i = 0; i < len; i++) {
children.push(domNode.childNodes[i])
}
var insertOffset = 0
var move
var node
var insertNode
for (i = 0; i < len; i++) {
move = bIndex[i]
if (move !== undefined && move !== i) {
// the element currently at this index will be moved later so increase the insert offset
if (reverseIndex[i] > i) {
insertOffset++
}
node = children[move]
insertNode = childNodes[i + insertOffset] || null
if (node !== insertNode) {
domNode.insertBefore(node, insertNode)
}
// the moved element came from the front of the array so reduce the insert offset
if (move < i) {
insertOffset--
}
}
// element at this index is scheduled to be removed so increase insert offset
if (i in bIndex.removes) {
insertOffset++
}
}
}
function replaceRoot(oldRoot, newRoot) {
if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
console.log(oldRoot)
oldRoot.parentNode.replaceChild(newRoot, oldRoot)
}
return newRoot;
}
},{"../vnode/is-widget.js":133,"../vnode/vpatch.js":136,"./apply-properties":116,"./create-element":117,"./update-widget":121}],120:[function(require,module,exports){
var document = require("global/document")
var isArray = require("x-is-array")
var domIndex = require("./dom-index")
var patchOp = require("./patch-op")
module.exports = patch
function patch(rootNode, patches) {
return patchRecursive(rootNode, patches)
}
function patchRecursive(rootNode, patches, renderOptions) {
var indices = patchIndices(patches)
if (indices.length === 0) {
return rootNode
}
var index = domIndex(rootNode, patches.a, indices)
var ownerDocument = rootNode.ownerDocument
if (!renderOptions) {
renderOptions = { patch: patchRecursive }
if (ownerDocument !== document) {
renderOptions.document = ownerDocument
}
}
for (var i = 0; i < indices.length; i++) {
var nodeIndex = indices[i]
rootNode = applyPatch(rootNode,
index[nodeIndex],
patches[nodeIndex],
renderOptions)
}
return rootNode
}
function applyPatch(rootNode, domNode, patchList, renderOptions) {
if (!domNode) {
return rootNode
}
var newNode
if (isArray(patchList)) {
for (var i = 0; i < patchList.length; i++) {
newNode = patchOp(patchList[i], domNode, renderOptions)
if (domNode === rootNode) {
rootNode = newNode
}
}
} else {
newNode = patchOp(patchList, domNode, renderOptions)
if (domNode === rootNode) {
rootNode = newNode
}
}
return rootNode
}
function patchIndices(patches) {
var indices = []
for (var key in patches) {
if (key !== "a") {
indices.push(Number(key))
}
}
return indices
}
},{"./dom-index":118,"./patch-op":119,"global/document":113,"x-is-array":115}],121:[function(require,module,exports){
var isWidget = require("../vnode/is-widget.js")
module.exports = updateWidget
function updateWidget(a, b) {
if (isWidget(a) && isWidget(b)) {
if ("name" in a && "name" in b) {
return a.id === b.id
} else {
return a.init === b.init
}
}
return false
}
},{"../vnode/is-widget.js":133}],122:[function(require,module,exports){
var DataSet = require("data-set")
module.exports = DataSetHook;
function DataSetHook(value) {
if (!(this instanceof DataSetHook)) {
return new DataSetHook(value);
}
this.value = value;
}
DataSetHook.prototype.hook = function (node, propertyName) {
var ds = DataSet(node)
var propName = propertyName.substr(5)
ds[propName] = this.value;
};
},{"data-set":106}],123:[function(require,module,exports){
var DataSet = require("data-set")
module.exports = DataSetHook;
function DataSetHook(value) {
if (!(this instanceof DataSetHook)) {
return new DataSetHook(value);
}
this.value = value;
}
DataSetHook.prototype.hook = function (node, propertyName) {
var ds = DataSet(node)
var propName = propertyName.substr(3)
ds[propName] = this.value;
};
DataSetHook.prototype.unhook = function(node, propertyName) {
var ds = DataSet(node);
var propName = propertyName.substr(3);
ds[propName] = undefined;
}
},{"data-set":106}],124:[function(require,module,exports){
module.exports = SoftSetHook;
function SoftSetHook(value) {
if (!(this instanceof SoftSetHook)) {
return new SoftSetHook(value);
}
this.value = value;
}
SoftSetHook.prototype.hook = function (node, propertyName) {
if (node[propertyName] !== this.value) {
node[propertyName] = this.value;
}
};
},{}],125:[function(require,module,exports){
var TypedError = require("error/typed")
var VNode = require("../vnode/vnode.js")
var VText = require("../vnode/vtext.js")
var isVNode = require("../vnode/is-vnode")
var isVText = require("../vnode/is-vtext")
var isWidget = require("../vnode/is-widget")
var isHook = require("../vnode/is-vhook")
var isVThunk = require("../vnode/is-thunk")
var parseTag = require("./parse-tag.js")
var softSetHook = require("./hooks/soft-set-hook.js")
var dataSetHook = require("./hooks/data-set-hook.js")
var evHook = require("./hooks/ev-hook.js")
var UnexpectedVirtualElement = TypedError({
type: "virtual-hyperscript.unexpected.virtual-element",
message: "Unexpected virtual child passed to h().\n" +
"Expected a VNode / Vthunk / VWidget / string but:\n" +
"got a {foreignObjectStr}.\n" +
"The parent vnode is {parentVnodeStr}.\n" +
"Suggested fix: change your `h(..., [ ... ])` callsite.",
foreignObjectStr: null,
parentVnodeStr: null,
foreignObject: null,
parentVnode: null
})
module.exports = h
function h(tagName, properties, children) {
var childNodes = []
var tag, props, key, namespace
if (!children && isChildren(properties)) {
children = properties
props = {}
}
props = props || properties || {}
tag = parseTag(tagName, props)
// support keys
if ("key" in props) {
key = props.key
props.key = undefined
}
// support namespace
if ("namespace" in props) {
namespace = props.namespace
props.namespace = undefined
}
// fix cursor bug
if (tag === "input" &&
"value" in props &&
props.value !== undefined &&
!isHook(props.value)
) {
props.value = softSetHook(props.value)
}
var keys = Object.keys(props)
var propName, value
for (var j = 0; j < keys.length; j++) {
propName = keys[j]
value = props[propName]
if (isHook(value)) {
continue
}
// add data-foo support
if (propName.substr(0, 5) === "data-") {
props[propName] = dataSetHook(value)
}
// add ev-foo support
if (propName.substr(0, 3) === "ev-") {
props[propName] = evHook(value)
}
}
if (children !== undefined && children !== null) {
addChild(children, childNodes, tag, props)
}
var node = new VNode(tag, props, childNodes, key, namespace)
return node
}
function addChild(c, childNodes, tag, props) {
if (typeof c === "string") {
childNodes.push(new VText(c))
} else if (isChild(c)) {
childNodes.push(c)
} else if (Array.isArray(c)) {
for (var i = 0; i < c.length; i++) {
addChild(c[i], childNodes, tag, props)
}
} else if (c === null || c === undefined) {
return
} else {
throw UnexpectedVirtualElement({
foreignObjectStr: JSON.stringify(c),
foreignObject: c,
parentVnodeStr: JSON.stringify({
tagName: tag,
properties: props
}),
parentVnode: {
tagName: tag,
properties: props
}
})
}
}
function isChild(x) {
return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x)
}
function isChildren(x) {
return typeof x === "string" || Array.isArray(x) || isChild(x)
}
},{"../vnode/is-thunk":129,"../vnode/is-vhook":130,"../vnode/is-vnode":131,"../vnode/is-vtext":132,"../vnode/is-widget":133,"../vnode/vnode.js":135,"../vnode/vtext.js":137,"./hooks/data-set-hook.js":122,"./hooks/ev-hook.js":123,"./hooks/soft-set-hook.js":124,"./parse-tag.js":126,"error/typed":112}],126:[function(require,module,exports){
var classIdSplit = /([\.#]?[a-zA-Z0-9_:-]+)/
var notClassId = /^\.|#/
module.exports = parseTag
function parseTag(tag, props) {
if (!tag) {
return "div"
}
var noId = !("id" in props)
var tagParts = tag.split(classIdSplit)
var tagName = null
if (notClassId.test(tagParts[1])) {
tagName = "div"
}
var classes, part, type, i
for (i = 0; i < tagParts.length; i++) {
part = tagParts[i]
if (!part) {
continue
}
type = part.charAt(0)
if (!tagName) {
tagName = part
} else if (type === ".") {
classes = classes || []
classes.push(part.substring(1, part.length))
} else if (type === "#" && noId) {
props.id = part.substring(1, part.length)
}
}
if (classes) {
if (props.className) {
classes.push(props.className)
}
props.className = classes.join(" ")
}
return tagName ? tagName.toLowerCase() : "div"
}
},{}],127:[function(require,module,exports){
var h = require("./index.js")
// http://www.w3.org/TR/SVGTiny12/attributeTable.html
var svgAttributes = {
"about": true,
"accent-height": true,
"accumulate": true,
"additive": true,
"alphabetic": true,
"arabic-form": true,
"ascent": true,
"attributeName": true,
"attributeType": true,
"bandwidth": true,
"baseProfile": true,
"bbox": true,
"begin": true,
"by": true,
"calcMode": true,
"cap-height": true,
"class": true,
"content": true,
"contentScriptType": true,
"cx": true,
"cy": true,
"d": true,
"datatype": true,
"defaultAction": true,
"descent": true,
"dur": true,
"editable": true,
"end": true,
"ev:event": true,
"event": true,
"externalResourcesRequired": true,
"fill": true,
"focusHighlight": true,
"focusable": true,
"font-family": true,
"font-stretch": true,
"font-style": true,
"font-variant": true,
"font-weight": true,
"from": true,
"g1": true,
"g2": true,
"glyph-name": true,
"gradientUnits": true,
"handler": true,
"hanging": true,
"height": true,
"horiz-adv-x": true,
"horiz-origin-x": true,
"id": true,
"ideographic": true,
"initialVisibility": true,
"k": true,
"keyPoints": true,
"keySplines": true,
"keyTimes": true,
"lang": true,
"mathematical": true,
"max": true,
"mediaCharacterEncoding": true,
"mediaContentEncodings": true,
"mediaSize": true,
"mediaTime": true,
"min": true,
"nav-down": true,
"nav-down-left": true,
"nav-down-right": true,
"nav-left": true,
"nav-next": true,
"nav-prev": true,
"nav-right": true,
"nav-up": true,
"nav-up-left": true,
"nav-up-right": true,
"observer": true,
"offset": true,
"origin": true,
"overlay": true,
"overline-position": true,
"overline-thickness": true,
"panose-1": true,
"path": true,
"pathLength": true,
"phase": true,
"playbackOrder": true,
"points": true,
"preserveAspectRatio": true,
"propagate": true,
"property": true,
"r": true,
"rel": true,
"repeatCount": true,
"repeatDur": true,
"requiredExtensions": true,
"requiredFeatures": true,
"requiredFonts": true,
"requiredFormats": true,
"resource": true,
"restart": true,
"rev": true,
"role": true,
"rotate": true,
"rx": true,
"ry": true,
"slope": true,
"snapshotTime": true,
"stemh": true,
"stemv": true,
"strikethrough-position": true,
"strikethrough-thickness": true,
"syncBehavior": true,
"syncBehaviorDefault": true,
"syncMaster": true,
"syncTolerance": true,
"syncToleranceDefault": true,
"systemLanguage": true,
"target": true,
"timelineBegin": true,
"to": true,
"transform": true,
"transformBehavior": true,
"type": true,
"typeof": true,
"u1": true,
"u2": true,
"underline-position": true,
"underline-thickness": true,
"unicode": true,
"unicode-range": true,
"units-per-em": true,
"values": true,
"version": true,
"viewBox": true,
"width": true,
"widths": true,
"x": true,
"x-height": true,
"x1": true,
"x2": true,
"xlink:actuate": true,
"xlink:arcrole": true,
"xlink:href": true,
"xlink:role": true,
"xlink:show": true,
"xlink:title": true,
"xlink:type": true,
"xml:base": true,
"xml:id": true,
"xml:lang": true,
"xml:space": true,
"y": true,
"y1": true,
"y2": true,
"zoomAndPan": true
}
var SVG_NAMESPACE = "http://www.w3.org/2000/svg"
module.exports = svg
function svg(tagName, properties, children) {
if (!children && isChildren(properties)) {
children = properties
properties = {}
}
properties = properties || {}
// set namespace for svg
properties.namespace = SVG_NAMESPACE
var attributes = properties.attributes || (properties.attributes = {})
for (var key in properties) {
if (!properties.hasOwnProperty(key)) {
continue
}
if (svgAttributes[key] !== true) {
continue
}
var value = properties[key]
if (typeof value !== "string" &&
typeof value !== "number" &&
typeof value !== "boolean"
) {
continue
}
attributes[key] = value
}
return h(tagName, properties, children)
}
function isChildren(x) {
return typeof x === "string" || Array.isArray(x)
}
},{"./index.js":125}],128:[function(require,module,exports){
var isVNode = require("./is-vnode")
var isVText = require("./is-vtext")
var isWidget = require("./is-widget")
var isThunk = require("./is-thunk")
module.exports = handleThunk
function handleThunk(a, b) {
var renderedA = a
var renderedB = b
if (isThunk(b)) {
renderedB = renderThunk(b, a)
}
if (isThunk(a)) {
renderedA = renderThunk(a, null)
}
return {
a: renderedA,
b: renderedB
}
}
function renderThunk(thunk, previous) {
var renderedThunk = thunk.vnode
if (!renderedThunk) {
renderedThunk = thunk.vnode = thunk.render(previous)
}
if (!(isVNode(renderedThunk) ||
isVText(renderedThunk) ||
isWidget(renderedThunk))) {
throw new Error("thunk did not return a valid node");
}
return renderedThunk
}
},{"./is-thunk":129,"./is-vnode":131,"./is-vtext":132,"./is-widget":133}],129:[function(require,module,exports){
module.exports = isThunk
function isThunk(t) {
return t && t.type === "Thunk"
}
},{}],130:[function(require,module,exports){
module.exports = isHook
function isHook(hook) {
return hook && typeof hook.hook === "function" &&
!hook.hasOwnProperty("hook")
}
},{}],131:[function(require,module,exports){
var version = require("./version")
module.exports = isVirtualNode
function isVirtualNode(x) {
return x && x.type === "VirtualNode" && x.version === version
}
},{"./version":134}],132:[function(require,module,exports){
var version = require("./version")
module.exports = isVirtualText
function isVirtualText(x) {
return x && x.type === "VirtualText" && x.version === version
}
},{"./version":134}],133:[function(require,module,exports){
module.exports = isWidget
function isWidget(w) {
return w && w.type === "Widget"
}
},{}],134:[function(require,module,exports){
module.exports = "1"
},{}],135:[function(require,module,exports){
var version = require("./version")
var isVNode = require("./is-vnode")
var isWidget = require("./is-widget")
var isThunk = require("./is-thunk")
var isVHook = require("./is-vhook")
module.exports = VirtualNode
var noProperties = {}
var noChildren = []
function VirtualNode(tagName, properties, children, key, namespace) {
this.tagName = tagName
this.properties = properties || noProperties
this.children = children || noChildren
this.key = key != null ? String(key) : undefined
this.namespace = (typeof namespace === "string") ? namespace : null
var count = (children && children.length) || 0
var descendants = 0
var hasWidgets = false
var hasThunks = false
var descendantHooks = false
var hooks
for (var propName in properties) {
if (properties.hasOwnProperty(propName)) {
var property = properties[propName]
if (isVHook(property) && property.unhook) {
if (!hooks) {
hooks = {}
}
hooks[propName] = property
}
}
}
for (var i = 0; i < count; i++) {
var child = children[i]
if (isVNode(child)) {
descendants += child.count || 0
if (!hasWidgets && child.hasWidgets) {
hasWidgets = true
}
if (!hasThunks && child.hasThunks) {
hasThunks = true
}
if (!descendantHooks && (child.hooks || child.descendantHooks)) {
descendantHooks = true
}
} else if (!hasWidgets && isWidget(child)) {
if (typeof child.destroy === "function") {
hasWidgets = true
}
} else if (!hasThunks && isThunk(child)) {
hasThunks = true;
}
}
this.count = count + descendants
this.hasWidgets = hasWidgets
this.hasThunks = hasThunks
this.hooks = hooks
this.descendantHooks = descendantHooks
}
VirtualNode.prototype.version = version
VirtualNode.prototype.type = "VirtualNode"
},{"./is-thunk":129,"./is-vhook":130,"./is-vnode":131,"./is-widget":133,"./version":134}],136:[function(require,module,exports){
var version = require("./version")
VirtualPatch.NONE = 0
VirtualPatch.VTEXT = 1
VirtualPatch.VNODE = 2
VirtualPatch.WIDGET = 3
VirtualPatch.PROPS = 4
VirtualPatch.ORDER = 5
VirtualPatch.INSERT = 6
VirtualPatch.REMOVE = 7
VirtualPatch.THUNK = 8
module.exports = VirtualPatch
function VirtualPatch(type, vNode, patch) {
this.type = Number(type)
this.vNode = vNode
this.patch = patch
}
VirtualPatch.prototype.version = version
VirtualPatch.prototype.type = "VirtualPatch"
},{"./version":134}],137:[function(require,module,exports){
var version = require("./version")
module.exports = VirtualText
function VirtualText(text) {
this.text = String(text)
}
VirtualText.prototype.version = version
VirtualText.prototype.type = "VirtualText"
},{"./version":134}],138:[function(require,module,exports){
var isArray = require("x-is-array")
var isObject = require("is-object")
var VPatch = require("../vnode/vpatch")
var isVNode = require("../vnode/is-vnode")
var isVText = require("../vnode/is-vtext")
var isWidget = require("../vnode/is-widget")
var isThunk = require("../vnode/is-thunk")
var isHook = require("../vnode/is-vhook")
var handleThunk = require("../vnode/handle-thunk")
module.exports = diff
function diff(a, b) {
var patch = { a: a }
walk(a, b, patch, 0)
return patch
}
function walk(a, b, patch, index) {
if (a === b) {
return
}
var apply = patch[index]
var applyClear = false
if (isThunk(a) || isThunk(b)) {
thunks(a, b, patch, index)
} else if (b == null) {
// If a is a widget we will add a remove patch for it
// Otherwise any child widgets/hooks must be destroyed.
// This prevents adding two remove patches for a widget.
if (!isWidget(a)) {
clearState(a, patch, index)
apply = patch[index]
}
apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
} else if (isVNode(b)) {
if (isVNode(a)) {
if (a.tagName === b.tagName &&
a.namespace === b.namespace &&
a.key === b.key) {
var propsPatch = diffProps(a.properties, b.properties)
if (propsPatch) {
apply = appendPatch(apply,
new VPatch(VPatch.PROPS, a, propsPatch))
}
apply = diffChildren(a, b, patch, apply, index)
} else {
apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
applyClear = true
}
} else {
apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
applyClear = true
}
} else if (isVText(b)) {
if (!isVText(a)) {
applyClear = true
} else if (a.text !== b.text) {
apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
}
} else if (isWidget(b)) {
if (!isWidget(a)) {
applyClear = true;
}
apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
}
if (apply) {
patch[index] = apply
}
if (applyClear) {
clearState(a, patch, index)
}
}
function diffProps(a, b) {
var diff
for (var aKey in a) {
if (!(aKey in b)) {
diff = diff || {}
diff[aKey] = undefined
}
var aValue = a[aKey]
var bValue = b[aKey]
if (aValue === bValue) {
continue
} else if (isObject(aValue) && isObject(bValue)) {
if (getPrototype(bValue) !== getPrototype(aValue)) {
diff = diff || {}
diff[aKey] = bValue
} else if (isHook(bValue)) {
diff = diff || {}
diff[aKey] = bValue
} else {
var objectDiff = diffProps(aValue, bValue)
if (objectDiff) {
diff = diff || {}
diff[aKey] = objectDiff
}
}
} else {
diff = diff || {}
diff[aKey] = bValue
}
}
for (var bKey in b) {
if (!(bKey in a)) {
diff = diff || {}
diff[bKey] = b[bKey]
}
}
return diff
}
function getPrototype(value) {
if (Object.getPrototypeOf) {
return Object.getPrototypeOf(value)
} else if (value.__proto__) {
return value.__proto__
} else if (value.constructor) {
return value.constructor.prototype
}
}
function diffChildren(a, b, patch, apply, index) {
var aChildren = a.children
var bChildren = reorder(aChildren, b.children)
var aLen = aChildren.length
var bLen = bChildren.length
var len = aLen > bLen ? aLen : bLen
for (var i = 0; i < len; i++) {
var leftNode = aChildren[i]
var rightNode = bChildren[i]
index += 1
if (!leftNode) {
if (rightNode) {
// Excess nodes in b need to be added
apply = appendPatch(apply,
new VPatch(VPatch.INSERT, null, rightNode))
}
} else {
walk(leftNode, rightNode, patch, index)
}
if (isVNode(leftNode) && leftNode.count) {
index += leftNode.count
}
}
if (bChildren.moves) {
// Reorder nodes last
apply = appendPatch(apply, new VPatch(VPatch.ORDER, a, bChildren.moves))
}
return apply
}
function clearState(vNode, patch, index) {
// TODO: Make this a single walk, not two
unhook(vNode, patch, index)
destroyWidgets(vNode, patch, index)
}
// Patch records for all destroyed widgets must be added because we need
// a DOM node reference for the destroy function
function destroyWidgets(vNode, patch, index) {
if (isWidget(vNode)) {
if (typeof vNode.destroy === "function") {
patch[index] = appendPatch(
patch[index],
new VPatch(VPatch.REMOVE, vNode, null)
)
}
} else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
var children = vNode.children
var len = children.length
for (var i = 0; i < len; i++) {
var child = children[i]
index += 1
destroyWidgets(child, patch, index)
if (isVNode(child) && child.count) {
index += child.count
}
}
} else if (isThunk(vNode)) {
thunks(vNode, null, patch, index)
}
}
// Create a sub-patch for thunks
function thunks(a, b, patch, index) {
var nodes = handleThunk(a, b);
var thunkPatch = diff(nodes.a, nodes.b)
if (hasPatches(thunkPatch)) {
patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
}
}
function hasPatches(patch) {
for (var index in patch) {
if (index !== "a") {
return true;
}
}
return false;
}
// Execute hooks when two nodes are identical
function unhook(vNode, patch, index) {
if (isVNode(vNode)) {
if (vNode.hooks) {
patch[index] = appendPatch(
patch[index],
new VPatch(
VPatch.PROPS,
vNode,
undefinedKeys(vNode.hooks)
)
)
}
if (vNode.descendantHooks || vNode.hasThunks) {
var children = vNode.children
var len = children.length
for (var i = 0; i < len; i++) {
var child = children[i]
index += 1
unhook(child, patch, index)
if (isVNode(child) && child.count) {
index += child.count
}
}
}
} else if (isThunk(vNode)) {
thunks(vNode, null, patch, index)
}
}
function undefinedKeys(obj) {
var result = {}
for (var key in obj) {
result[key] = undefined
}
return result
}
// List diff, naive left to right reordering
function reorder(aChildren, bChildren) {
var bKeys = keyIndex(bChildren)
if (!bKeys) {
return bChildren
}
var aKeys = keyIndex(aChildren)
if (!aKeys) {
return bChildren
}
var bMatch = {}, aMatch = {}
for (var aKey in bKeys) {
bMatch[bKeys[aKey]] = aKeys[aKey]
}
for (var bKey in aKeys) {
aMatch[aKeys[bKey]] = bKeys[bKey]
}
var aLen = aChildren.length
var bLen = bChildren.length
var len = aLen > bLen ? aLen : bLen
var shuffle = []
var freeIndex = 0
var i = 0
var moveIndex = 0
var moves = {}
var removes = moves.removes = {}
var reverse = moves.reverse = {}
var hasMoves = false
while (freeIndex < len) {
var move = aMatch[i]
if (move !== undefined) {
shuffle[i] = bChildren[move]
if (move !== moveIndex) {
moves[move] = moveIndex
reverse[moveIndex] = move
hasMoves = true
}
moveIndex++
} else if (i in aMatch) {
shuffle[i] = undefined
removes[i] = moveIndex++
hasMoves = true
} else {
while (bMatch[freeIndex] !== undefined) {
freeIndex++
}
if (freeIndex < len) {
var freeChild = bChildren[freeIndex]
if (freeChild) {
shuffle[i] = freeChild
if (freeIndex !== moveIndex) {
hasMoves = true
moves[freeIndex] = moveIndex
reverse[moveIndex] = freeIndex
}
moveIndex++
}
freeIndex++
}
}
i++
}
if (hasMoves) {
shuffle.moves = moves
}
return shuffle
}
function keyIndex(children) {
var i, keys
for (i = 0; i < children.length; i++) {
var child = children[i]
if (child.key !== undefined) {
keys = keys || {}
keys[child.key] = i
}
}
return keys
}
function appendPatch(apply, patch) {
if (apply) {
if (isArray(apply)) {
apply.push(patch)
} else {
apply = [apply, patch]
}
return apply
} else {
return patch
}
}
},{"../vnode/handle-thunk":128,"../vnode/is-thunk":129,"../vnode/is-vhook":130,"../vnode/is-vnode":131,"../vnode/is-vtext":132,"../vnode/is-widget":133,"../vnode/vpatch":136,"is-object":114,"x-is-array":115}],139:[function(require,module,exports){
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}
},{}],140:[function(require,module,exports){
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}
},{}],141:[function(require,module,exports){
(function (global){
!function(e){if("object"==typeof exports)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.routes=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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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 localRoutes = [];
/**
* Convert path to route object
*
* A string or RegExp should be passed,
* will return { re, src, keys} obj
*
* @param {String / RegExp} path
* @return {Object}
*/
var Route = function(path){
//using 'new' is optional
var src, re, keys = [];
if(path instanceof RegExp){
re = path;
src = path.toString();
}else{
re = pathToRegExp(path, keys);
src = path;
}
return {
re: re,
src: path.toString(),
keys: keys
}
};
/**
* Normalize the given path string,
* returning a regular expression.
*
* An empty array should be passed,
* which will contain the placeholder
* key names. For example "/user/:id" will
* then contain ["id"].
*
* @param {String} path
* @param {Array} keys
* @return {RegExp}
*/
var pathToRegExp = function (path, keys) {
path = path
.concat('/?')
.replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?|\*/g, function(_, slash, format, key, capture, optional){
if (_ === "*"){
keys.push(undefined);
return _;
}
keys.push(key);
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + (capture || '([^/]+?)') + ')'
+ (optional || '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', 'i');
};
/**
* Attempt to match the given request to
* one of the routes. When successful
* a {fn, params, splats} obj is returned
*
* @param {Array} routes
* @param {String} uri
* @return {Object}
*/
var match = function (routes, uri, startAt) {
var captures, i = startAt || 0;
for (var len = routes.length; i < len; ++i) {
var route = routes[i],
re = route.re,
keys = route.keys,
splats = [],
params = {};
if (captures = uri.match(re)) {
for (var j = 1, len = captures.length; j < len; ++j) {
var key = keys[j-1],
val = typeof captures[j] === 'string'
? unescape(captures[j])
: captures[j];
if (key) {
params[key] = val;
} else {
splats.push(val);
}
}
return {
params: params,
splats: splats,
route: route.src,
next: i + 1
};
}
}
};
/**
* Default "normal" router constructor.
* accepts path, fn tuples via addRoute
* returns {fn, params, splats, route}
* via match
*
* @return {Object}
*/
var Router = function(){
//using 'new' is optional
return {
routes: [],
routeMap : {},
addRoute: function(path, fn){
if (!path) throw new Error(' route requires a path');
if (!fn) throw new Error(' route ' + path.toString() + ' requires a callback');
var route = Route(path);
route.fn = fn;
this.routes.push(route);
this.routeMap[path] = fn;
},
match: function(pathname, startAt){
var route = match(this.routes, pathname, startAt);
if(route){
route.fn = this.routeMap[route.route];
route.next = this.match.bind(this, pathname, route.next)
}
return route;
}
}
};
Router.Route = Route
Router.pathToRegExp = pathToRegExp
Router.match = match
// back compat
Router.Router = Router
module.exports = Router
},{}]},{},[1])
(1)
});
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],142:[function(require,module,exports){
(function (global){
var rng;
if (global.crypto && crypto.getRandomValues) {
// WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
// Moderately fast, high quality
var _rnds8 = new Uint8Array(16);
rng = function whatwgRNG() {
crypto.getRandomValues(_rnds8);
return _rnds8;
};
}
if (!rng) {
// Math.random()-based (RNG)
//
// If all else fails, use Math.random(). It's fast, but is of unspecified
// quality.
var _rnds = new Array(16);
rng = function() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
_rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return _rnds;
};
}
module.exports = rng;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],143:[function(require,module,exports){
// uuid.js
//
// Copyright (c) 2010-2012 Robert Kieffer
// MIT License - http://opensource.org/licenses/mit-license.php
// Unique ID creation requires a high quality random # generator. We feature
// detect to determine the best RNG source, normalizing to a function that
// returns 128-bits of randomness, since that's what's usually required
var _rng = require('./rng');
// Maps for number <-> hex string conversion
var _byteToHex = [];
var _hexToByte = {};
for (var i = 0; i < 256; i++) {
_byteToHex[i] = (i + 0x100).toString(16).substr(1);
_hexToByte[_byteToHex[i]] = i;
}
// **`parse()` - Parse a UUID into it's component bytes**
function parse(s, buf, offset) {
var i = (buf && offset) || 0, ii = 0;
buf = buf || [];
s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
if (ii < 16) { // Don't overflow!
buf[i + ii++] = _hexToByte[oct];
}
});
// Zero out remaining bytes if string was short
while (ii < 16) {
buf[i + ii++] = 0;
}
return buf;
}
// **`unparse()` - Convert UUID byte array (ala parse()) into a string**
function unparse(buf, offset) {
var i = offset || 0, bth = _byteToHex;
return bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]];
}
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
// random #'s we need to init node and clockseq
var _seedBytes = _rng();
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
var _nodeId = [
_seedBytes[0] | 0x01,
_seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
];
// Per 4.2.2, randomize (14 bit) clockseq
var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
// Previous uuid creation time
var _lastMSecs = 0, _lastNSecs = 0;
// See https://github.com/broofa/node-uuid for API details
function v1(options, buf, offset) {
var i = buf && offset || 0;
var b = buf || [];
options = options || {};
var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
// UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
// Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
// Time since last uuid creation (in msecs)
var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
// Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
}
// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
}
// Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000;
// `time_low`
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff;
// `time_mid`
var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff;
// `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff;
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80;
// `clock_seq_low`
b[i++] = clockseq & 0xff;
// `node`
var node = options.node || _nodeId;
for (var n = 0; n < 6; n++) {
b[i + n] = node[n];
}
return buf ? buf : unparse(b);
}
// **`v4()` - Generate random UUID**
// See https://github.com/broofa/node-uuid for API details
function v4(options, buf, offset) {
// Deprecated - 'format' argument, as supported in v1.2
var i = buf && offset || 0;
if (typeof(options) == 'string') {
buf = options == 'binary' ? new Array(16) : null;
options = null;
}
options = options || {};
var rnds = options.random || (options.rng || _rng)();
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
// Copy bytes to buffer, if provided
if (buf) {
for (var ii = 0; ii < 16; ii++) {
buf[i + ii] = rnds[ii];
}
}
return buf || unparse(rnds);
}
// Export public API
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
uuid.parse = parse;
uuid.unparse = unparse;
module.exports = uuid;
},{"./rng":142}],144:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var uuid = require('uuid');
var mercury = require('mercury');
var addDelegatedEvents = require('./lib/mercury/add-delegated-events');
var onboarding = require('./onboarding');
var router = require('./router');
var registerItemPlugins = require('./item-plugins/register-plugins');
var debug = require('./components/debug');
var browse = require('./components/browse');
var error = require('./components/error');
var help = require('./components/help');
var viewport = require('./components/viewport');
var views = require('./components/browse/views');
var userAccount = require('./components/user-account');
var namespaceService = require('./services/namespace/service');
var stateService = require('./services/state/service');
var errorRoute = require('./routes/error');
var browseRoute = require('./routes/browse');
var log = require('./lib/log')('app');
var browseComponent = browse();
var errorComponent = error();
var debugComponent = debug();
var helpComponent = help();
var viewportComponent = viewport();
var userAccountComponent = userAccount();
// Top level state
var state = mercury.struct({
/*
* Navigation related states
*/
navigation: mercury.struct({
/*
* Identifier for the currently displayed page.
* Mutable via route handlers
* @type {string}
*/
pageKey: mercury.value('')
}),
/*
* Vanadium Namespace Browsing related state
*/
browse: browseComponent.state,
/*
* Vanadium Namespace Help related state
*/
help: helpComponent.state,
/*
* State of the viewport component
*/
viewport: viewportComponent.state,
/*
* Boolean indicating that app has been initialized.
* Used to show/hide splash screen.
* @type {boolean}
*/
initialized: mercury.value(false),
/*
* State of the error component
*/
error: errorComponent.state,
/*
* State for user account component
*/
userAccount: userAccountComponent.state,
/*
* Internal debugging state
*/
debug: debugComponent.state,
/*
* Boolean indicating whether we are in demo mode.
* In demo mode, a sample-world is created and user is redirected to it as
* the starting namespace.
* @type {boolean}
*/
demo: mercury.value(false),
});
// To level events
var events = mercury.input([
/*
* Navigation related events
*/
'navigation',
/*
* Vanadium Namespace Browsing related events
*/
'browse',
/*
* Vanadium Namespace Help related events
*/
'help',
/*
* Events of the viewport component
*/
'viewport'
]);
events.navigation = mercury.input([
/*
* Indicates a navigation request to a resource
* Data of form:
* {
* path: 'path/to/resource'
* }
* is expected as data for the event
*/
'navigate',
/*
* Event indicating a request to reload the current namespace
* The current namespace will be passed as data into the handlers.
*/
'reload'
]);
events.browse = browseComponent.events;
events.help = helpComponent.events;
events.viewport = viewportComponent.events;
// Wire Events
wireEvents();
// Register the plugins
registerItemPlugins();
// Load the user's saved state, followed by other dependencies.
loadUserState().then(function() {
// Start the router which will register the application routes
router(state, events);
// Initialize Vanadium
initVanadium();
});
// Debugging related exports
exportDebugging();
// Render the app
var render = function(state) {
return viewport.render(state, events);
};
mercury.app(document.body, state, render);
// Add additional events that mercury's delegator should listenTo.
addDelegatedEvents(['core-overlay-open-completed',
'down', 'up', 'tap', 'openchange', 'activate', 'delete-item'
]);
function wireEvents() {
// TODO(aghassemi): Make these events global.
// Hook up external browse events.
events.browse.error(onError);
events.browse.toast(onToast);
events.navigation.reload(onReload);
// Hook up external help events.
events.help.navigate = events.navigation.navigate;
events.help.error(onError);
}
/*
* Reload the views for the current namespace
*/
function onReload() {
var namespace = state.browse.namespace();
log.debug('reloading', namespace);
// clear the service cache
namespaceService.clearCache(namespace);
// tell views to clear their caches
views.clearCache(state.browse.views, namespace);
// navigate to the namespace again
// TODO(aghassemi) Ideally we only reset the selected item if the old one
// no longer is in the view, but that's a bit tricky and depends on
// https://github.com/vanadium/browser/issues/81
state.browse.selectedItemName.set(namespace);
events.navigation.navigate({
path: browseRoute.createUrl(state.browse(), {
namespace: namespace
})
});
}
/*
* Given an error, navigate to the error page and display that error.
*/
function onError(err) {
var msg = err.toString();
if (err.message) {
msg = err.message;
}
state.error.message.set(msg);
events.navigation.navigate({
path: errorRoute.createUrl(),
skipHistoryPush: true
});
}
/*
* Given a toast object, let the viewport render it.
* Toasts are given a unique key to ensure Mercury draws 1 toast per event.
*/
function onToast(toast) {
toast.key = uuid.v4();
state.viewport.toasts.push(toast);
}
/*
* Export some debugging methods at global level
*/
function exportDebugging() {
window.log = require('./lib/log');
window.enableContinuousRendering =
debug.enableContinuousRendering.bind(null, state.debug);
}
/*
* Load any of the user's application state.
* Note: This promise will always resolve.
*/
function loadUserState() {
var loads = [];
// Set the initial namespace for the user. This guarantees that regardless
// of starting route, that the user continues where they last left off.
loads.push(stateService.loadNamespace().then(function(namespace) {
state.browse.namespace.set(namespace);
}));
// Fetch the most recently used side panel width.
loads.push(stateService.loadSidePanelWidth().then(function(width) {
state.browse.sidePanelWidth.set(width);
}));
// Fetch the most recently used browse view type.
loads.push(stateService.loadBrowseViewType().then(function(view) {
state.browse.views.viewType.set(view);
}));
return Promise.all(loads).catch(function() {});
}
/*
* Initialized vanadium and sets appropriate messages on the splash screen
*/
function initVanadium() {
viewport.setSplashMessage('Initializing Vanadium...');
namespaceService.getEmailAddress().then(function(email) {
// Onboarding Hook for new users (async). Currently does not block.
onboarding(email, state);
if (state.demo()) {
return intializeDemo();
} else {
return initialized();
}
/*
* Called when Vanadium initialization is complete
*/
function initialized() {
viewport.setSplashMessage('Initialized');
state.initialized.set(true);
}
/*
* Initialized the demo mode
*/
function intializeDemo() {
// TODO(alexfandrianto): With JS deprecated, we may want to delete the old
// demo code. Instead, demo services should be launched by cmdline or Go.
initialized();
/*viewport.setSplashMessage('Initializing Sample World Demo...');
var sampleWorldDirectory = '';
return sampleWorld.getRootedName().then(function(name) {
sampleWorldDirectory = name;
return sampleWorld.create(sampleWorldDirectory);
}).then(function() {
initialized();
// Navigate to the home directory
events.navigation.navigate({
path: browseRoute.createUrl(state.browse, {
namespace: sampleWorldDirectory,
viewType: 'tree'
})
});
});*/
}
}).catch(function(err) {
var isError = true;
viewport.setSplashMessage(err.toString(), isError);
log.error(err);
});
}
},{"./components/browse":150,"./components/browse/views":181,"./components/debug":189,"./components/error":193,"./components/help":202,"./components/user-account":209,"./components/viewport":211,"./item-plugins/register-plugins":212,"./lib/log":223,"./lib/mercury/add-delegated-events":224,"./onboarding":234,"./router":235,"./routes/browse":237,"./routes/error":239,"./services/namespace/service":248,"./services/state/service":252,"mercury":45,"uuid":143}],145:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var ItemCardList = require('../item-card-list/index');
var bookmarksService = require('../../../services/bookmarks/service');
var log = require('../../../lib/log')('components:browse:bookmarks');
module.exports = create;
module.exports.render = render;
module.exports.load = load;
/*
* Bookmark view
*/
function create() {
var state = mercury.varhash({
/*
* List of user-specified bookmark items to display
* @see services/namespace/item
* @type {Array<namespaceitem>}
*/
bookmarkItems: mercury.array([])
});
return {
state: state
};
}
/*
* Renders the bookmark view
*/
function render(state, browseState, browseEvents, navEvents) {
return ItemCardList.render(
state.bookmarkItems,
browseState,
browseEvents,
navEvents, {
title: 'Bookmarks',
emptyText: 'No bookmarks.',
showShortName: false,
hoverActionInfo: {
icon: 'clear',
description: 'Remove bookmark',
action: function(objectName) {
browseEvents.selectedItemDetails.bookmark(
{
name: objectName,
bookmark: false
}
);
}
}
}
);
}
/*
* Does the initialization and loading of the data necessary to display the
* bookmarks.
* Called and used by the parent browse view to initialize the view on
* request.
* Returns a promise that will be resolved when loading is finished. Promise
* is used by the parent browse view to display a loading progressbar.
*/
function load(state) {
return new Promise(function(resolve, reject) {
bookmarksService.getAll()
.then(function bookmarksReceived(items) {
state.put('bookmarkItems', items);
items.events.once('end', resolve);
}).catch(function(err) {
log.error(err);
reject();
});
});
}
},{"../../../lib/log":223,"../../../services/bookmarks/service":244,"../item-card-list/index":152,"mercury":45}],146:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var Bookmarks = require('./bookmarks/index.js');
var Recommendations = require('./recommendations/index.js');
var Views = require('./views/index.js');
var namespaceService = require('../../services/namespace/service');
var extendDefaults = require('../../lib/extend-defaults');
var log = require('../../lib/log')('components:browse:browse-namespace');
module.exports = browseNamespace;
// We keep track of previous namespace root that was browsed to so we can
// know when navigating to a different namespace happens.
var previousNamespaceRoot;
/*
* Default event handler for the browseNamespace event.
* Updates the necessary states when browseNamespace is triggered
* Data is of the form
* {
* namespace: '/vanadium/name/space',
* globQuery: '*',
* }
*/
function browseNamespace(browseState, browseEvents, data) {
var defaults = {
namespace: '',
globQuery: '',
subPage: 'views',
viewType: 'tree'
};
data = extendDefaults(defaults, data);
if (!Views.trySetViewType(browseState.views, data.viewType)) {
error404('Invalid view type: ' + data.viewType);
return;
}
browseState.namespace.set(data.namespace);
browseState.globQuery.set(data.globQuery);
browseState.subPage.set(data.subPage);
var namespace = browseState.namespace();
var globQuery = browseState.globQuery() || '*';
var subPage = browseState.subPage();
// When navigating to a different root, reset the currently selected item
var root = namespaceService.util.parseName(namespace)[0];
if (previousNamespaceRoot !== root) {
browseState.selectedItemName.set(namespace);
}
previousNamespaceRoot = root;
browseState.isFinishedLoadingItems.set(false);
switch (subPage) {
case 'views':
Views.load(browseState.views, namespace, globQuery)
.then(loadingFinished)
.catch(onError.bind(null, 'items'));
break;
case 'bookmarks':
Bookmarks.load(browseState.bookmarks)
.then(loadingFinished)
.catch(onError.bind(null, 'bookmarks'));
break;
case 'recommendations':
Recommendations.load(browseState.recommendations)
.then(loadingFinished)
.catch(onError.bind(null, 'recommendations'));
break;
default:
browseState.subPage.set(defaults.subPage);
error404('Invalid page: ' + browseState.subPage());
return;
}
function onError(subject, err) {
var message = 'Could not load ' + subject;
browseEvents.toast({
text: message,
type: 'error'
});
log.error(message, err);
loadingFinished();
}
function error404(errMessage) {
log.error(errMessage);
//TODO(aghassemi) Needs to be 404 error when we have support for 404
browseEvents.error(new Error(errMessage));
}
function loadingFinished() {
browseState.isFinishedLoadingItems.set(true);
}
// Update the right side
browseEvents.selectedItemDetails.displayItemDetails({
name: browseState.selectedItemName()
});
}
},{"../../lib/extend-defaults":219,"../../lib/log":223,"../../services/namespace/service":248,"./bookmarks/index.js":145,"./recommendations/index.js":179,"./views/index.js":181}],147:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var log = require('../../lib/log')('components:browse:browse-children');
var namespaceService = require('../../services/namespace/service');
module.exports = getNamespaceSuggestions;
/*
* Default event handler for the getNamespaceSuggestions event.
* Updates the necessary states when getNamespaceSuggestions is triggered.
* Only does this if the browseState's namespacePrefix has changed.
* Namespace is the target namespace whose children are to be retrieved.
*/
function getNamespaceSuggestions(browseState, namespace) {
// Get children of the chosen prefix.
// When there is a trailing slash, treat the namespace as the prefix.
var prefix;
var len = namespace.length;
var lastSlashIndex = namespace.lastIndexOf('/');
if (len > 1 && lastSlashIndex === len - 1) {
prefix = namespace.substring(0, lastSlashIndex);
} else {
prefix = namespaceService.util.stripBasename(namespace);
}
if (prefix === browseState.namespacePrefix()) {
return; // The children are already based on the correct glob.
}
// Update the state prefix and clear out the children.
browseState.namespacePrefix.set(prefix);
emptyOutItems();
// Do not search if selecting a namespace root.
if (prefix === '' && namespace[0] === '/') {
return;
}
// Glob the children using this prefix.
namespaceService.getChildren(prefix).then(function received(items) {
browseState.put('namespaceSuggestions', items);
}).catch(function(err) {
log.warn('Could not glob', prefix, err);
});
function emptyOutItems() {
browseState.put('namespaceSuggestions', []);
}
}
},{"../../lib/log":223,"../../services/namespace/service":248}],148:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = getServiceIcon;
/*
* Given an item returns an structure with the name of the corresponding
* core-icon and a title for the icon to use for rendering.
*/
function getServiceIcon(item) {
var icon;
var title;
if (item.hasMountPoint && item.hasServer) {
icon = 'vanadium:both';
title = 'MountPoint & Service';
} else if (item.hasServer) {
icon = 'vanadium:service';
title = 'Service';
} else if (item.hasMountPoint) {
icon = 'vanadium:mountpoint';
title = 'MountPoint';
} else {
icon = 'error';
title = 'Inaccessible';
}
return {
icon: icon,
title: title
};
}
},{}],149:[function(require,module,exports){
module.exports = ":root{}:root{}.layout-horizontal{display:flex;flex-direction:row;}.flex-1{flex:1;}.flex-2{flex:2;}.flex-3{flex:3;}.flex-4{flex:4;}.flex-5{flex:5;}.browse-toolbar{background-color:#FAFAFA;box-shadow:none;height:50px;}.browse-toolbar div.browse-toolbar-layout{flex-basis:100%;height:35px;}.browse-details-sidebar::shadow #dropShadow{display:none;z-index:-1;}.browse-details-sidebar::shadow #mainContainer{background-color:#FAFAFA;border-left:solid 1px rgba(0, 0, 0, 0.12);min-width:250px;}.browse-main-wrapper paper-progress{position:absolute;opacity:0.6;}.browse-main-wrapper core-tooltip{position:absolute;top:0;}.browse-main-wrapper h2{font-size:1.4em;color:#0097A7;padding:0.75em;padding-bottom:0.2em;text-decoration:none;}.browse-main-panel::shadow #mainContainer{overflow-x:auto;}.progress-tooltip{width:100%;}.breadcrumbs-wrapper{overflow-x:auto;overflow-y:hidden;flex:1;margin:0 0 2px 0;padding-bottom:1px;height:39px;}.breadcrumbs{margin:0px;padding:0px;margin-top:4px;list-style:none;white-space:nowrap;}.breadcrumb-item{font-size:0.7em;font-weight:bold;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block;}.breadcrumb-item a{display:inline-block;color:rgba(0, 0, 0, 0.87);}.breadcrumb-item-prefix a{color:rgba(0, 0, 0, 0.54);}.breadcrumb-item a:hover,.breadcrumbs li a:focus{color:#00838F;}.breadcrumb-item:before{content:'/';padding:0 0.2em;display:inline-block;color:rgba(0, 0, 0, 0.54);}.breadcrumb-item.relative-name:first-child:before{display:none;}.namespace-box{background:#FAFAFA;font-size:0.7em;padding:0 0.5em;margin-left:1.25em !important;margin-right:3em !important;border-radius:1px;}.namespace-box /deep/ input{color:inherit;}.namespace-box core-tooltip.icontooltip{margin-top:0.2em;align-self:center;}.namespace-box core-tooltip.nstooltip{width:100%;margin-bottom:0.5em;}.icon-group{white-space:nowrap;}.vertical-ruler{display:inline-block;width:1px;background-color:rgba(0, 0, 0, 0.12);margin:0 0.2em;}.icon-group paper-icon-button{vertical-align:middle;color:rgba(0, 0, 0, 0.54);padding:0.2em;margin:0 0.2em;}.icon-group paper-icon-button::shadow #ripple{color:#00838F;}.search-box{white-space:nowrap;width:8em;margin-left:0.2em;}.search-box core-tooltip{width:100%;}.search-box .icon,.namespace-box .icon{color:rgba(0, 0, 0, 0.54);margin-right:0.5em;}.search-box .icon{margin-top:4px;}.search-box .input{font-size:0.7em;}.search-box .clear-search{margin-left:-25px;}.search-box paper-input::shadow /deep/ input{width:calc(100% - 25px);}.service-type-icon{transform:scale(0.7);padding-right:0.75em;}.header-content{flex:1;}paper-autocomplete{width:100%;}paper-autocomplete::shadow #suggest-box{background-color:#FAFAFA;}paper-autocomplete::shadow #suggest-box{border:solid 1px rgba(0, 0, 0, 0.12);box-shadow:0 2px 10px 0 rgba(0, 0, 0, 0.2);}paper-autocomplete.autocomplete paper-item.highlighted,paper-autocomplete.autocomplete paper-item:hover{background-color:#FF6E40;}paper-autocomplete.autocomplete paper-item{color:rgba(0, 0, 0, 0.87);}paper-icon-button.selected,paper-icon-button.selected:focus,paper-icon-button.selected:hover{background-color:#00838F;color:#ffffff;box-shadow:0 2px 10px 0 rgba(0, 0, 0, 0.2);border-radius:999px;}.side-panel-toggle{position:absolute;z-index:2;left:-18px;top:28px;transform:scale(0.6);background-color:#ffffff;color:#00838F;}.resize-handle{position:fixed;z-index:1;left:-3px;width:5px;height:100000px;cursor:ew-resize;}.side-panel-toggle.collapsed{left:-24px;}"
},{}],150:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var PropertyValueEvent = require('../../lib/mercury/property-value-event');
var exists = require('../../lib/exists');
var namespaceService = require('../../services/namespace/service');
var smartService = require('../../services/smart/service');
var stateService = require('../../services/state/service');
var browseRoute = require('../../routes/browse');
var bookmarksRoute = require('../../routes/bookmarks');
var recommendationsRoute = require('../../routes/recommendations');
var ItemDetails = require('./item-details/index');
var Views = require('./views/index');
var Bookmarks = require('./bookmarks/index');
var Recommendations = require('./recommendations/index');
var browseNamespace = require('./browse-namespace');
var getNamespaceSuggestions = require('./get-namespace-suggestions');
var log = require('../../lib/log')('components:browse');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
module.exports.renderHeader = renderHeader;
// While there could be any number of children at the current namespace, only
// show up to 5 suggestions at a time. Rely on the filter to find the rest.
var NAMESPACE_AUTOCOMPLETE_MAX_ITEMS = 5;
/*
* Browse component provides user interfaces for browsing the Vanadium namespace
*/
function create() {
loadLearners();
var selectedItemDetails = new ItemDetails();
var bookmarks = new Bookmarks();
var recommendations = new Recommendations();
var views = new Views();
var state = mercury.varhash({
/*
* Vanadium namespace being displayed and queried
* Note: This value is persisted between namespace browser sessions.
* @type {string}
*/
namespace: mercury.value(''),
/*
* Glob query applied to the Vanadium namespace
* @type {string}
*/
globQuery: mercury.value(''),
/*
* List of direct descendants of the namespace input prefix.
* Used to make suggestions when interacting with the namespace input.
* TODO(alexfandrianto): Currently uses obj.mountedName to access the name
* of the descendant instead of storing the name directly. Works around
* namespaceService's glob, which updates its returned result over time.
* @type {Array<Object>}
*/
namespaceSuggestions: mercury.array([]),
/*
* The namespace input prefix is the last namespace value that triggered
* a glob for direct descendants. Initially, it is null. Upon update of the
* namespace input prefix, new children will be globbed.
* @type {string | null}
*/
namespacePrefix: mercury.value(null),
/*
* State of the bookmarks component
*/
bookmarks: bookmarks.state,
/*
* State of the recommendation component
*/
recommendations: recommendations.state,
/*
* State of the views component
*/
views: views.state,
/*
* State of the selected item-details component
*/
selectedItemDetails: selectedItemDetails.state,
/*
* Name of currently selected item
*/
selectedItemName: mercury.value(''),
/*
* Whether loading items has finished.
* @type {Boolean}
*/
isFinishedLoadingItems: mercury.value(false),
/*
* Specifies what sub page is currently displayed.
* One of: views, bookmarks, recommendations
*/
subPage: mercury.value('views'),
/*
* Whether the side panel is collapsed or expanded
* @type {Boolean}
*/
sidePanelCollapsed: mercury.value(false),
/*
* Width of the side panel
* Note: This value is persisted between namespace browser sessions.
* @type {String}
*/
sidePanelWidth: mercury.value('50%')
});
var events = mercury.input([
/*
* Indicates a request to browse the Vanadium namespace
* Data of form:
* {
* namespace: '/namespace-root:8881/name/space',
* globQuery: '*',
* }
* is expected as data for the event
*/
'browseNamespace',
/*
* View components events.
*/
'views',
/*
* Indicates a request to obtain the direct descendants of the given name.
*/
'getNamespaceSuggestions',
/*
* Selects an item.
* Data of form:
* {
* name: 'object/name'
* }
*/
'selectItem',
/*
* Events for the ItemDetails component
*/
'selectedItemDetails',
/*
* Displays an error
* Data of should be an Error object.
*/
'error',
/*
* Displays a toast
* Data of form:
* {
text: 'Saved',
type: 'error',
action: function undo(){ // },
actionText: 'UNDO'
* }
*/
'toast',
/*
* Event for toggling the expand/collapse state of the sidebar details panel
*/
'toggleSidePanel',
/*
* Drag to resize the side details panel
*/
'slideSidePanel'
]);
wireUpEvents(state, events);
events.selectedItemDetails = selectedItemDetails.events;
events.views = views.events;
selectedItemDetails.events.toast = events.toast;
return {
state: state,
events: events
};
}
/*
* Loads the learners into the smart service upon creation of this component.
* TODO(aghassemi), TODO(alexfandrianto) Move this into service layers, similar
* to how `learner-shortcut` is now loaded in the recommendations service.
*/
function loadLearners() {
smartService.loadOrCreate(
'learner-method-input',
smartService.constants.LEARNER_METHOD_INPUT, {
minThreshold: 0.2,
maxValues: -1
}
).catch(function(err) {
log.error(err);
});
smartService.loadOrCreate(
'learner-method-invocation',
smartService.constants.LEARNER_METHOD_INVOCATION, {
minThreshold: 0.25,
maxValues: 1
}
).catch(function(err) {
log.error(err);
});
}
/*
* Renders the top bar, where the user can specify a namespace root.
*/
function renderHeader(browseState, browseEvents, navEvents) {
return h('div.header-content', [
renderNamespaceBox(browseState, browseEvents, navEvents)
]);
}
function renderSidePanelToggle(browseState, browseEvents) {
var cssClass = '.core-header.side-panel-toggle';
if (browseState.sidePanelCollapsed) {
cssClass += '.collapsed';
}
return h('paper-fab' + cssClass, {
attributes: {
'mini': true,
'title': browseState.sidePanelCollapsed ?
'Show side panel' : 'Hide side panel',
'icon': browseState.sidePanelCollapsed ?
'chevron-left' : 'chevron-right',
},
'ev-click': mercury.event(browseEvents.toggleSidePanel, {
collapsed: !browseState.sidePanelCollapsed
})
});
}
/*
* Renders the main body.
* A toolbar is rendered on top of the mainView and sideView showing the current
* position in the namespace as well as a globquery searchbox.
* The mainView contains the shortcuts and names at this point in the namespace.
* The sideView displays the detail information of the selected name.
*/
function render(browseState, browseEvents, navEvents) {
insertCss(css);
var expandCollapse = renderSidePanelToggle(browseState, browseEvents);
var sideView = [
expandCollapse,
ItemDetails.render(
browseState.selectedItemDetails,
browseEvents.selectedItemDetails,
browseState,
navEvents
)
];
var mainView;
switch (browseState.subPage) {
case 'views':
mainView = Views.render(browseState.views, browseEvents.views,
browseState, browseEvents, navEvents);
break;
case 'bookmarks':
mainView = Bookmarks.render(browseState.bookmarks,
browseState, browseEvents, navEvents);
break;
case 'recommendations':
mainView = Recommendations.render(browseState.recommendations,
browseState, browseEvents, navEvents);
break;
default:
log.error('Unsupported subPage ' + browseState.subPage);
}
// add progressbar and wrap in a container
var progressbar;
if (!browseState.isFinishedLoadingItems) {
progressbar = h('core-tooltip.progress-tooltip', {
attributes: {
'label': 'Loading items...',
'position': 'bottom'
}
}, h('paper-progress.delayed', {
attributes: {
'indeterminate': true,
'aria-label': 'Loading items'
}
}));
}
mainView = h('div.browse-main-wrapper', [
progressbar,
mainView
]);
var view = [
h('core-toolbar.browse-toolbar.core-narrow', [
renderToolbar(browseState, navEvents)
]),
h('core-drawer-panel', {
attributes: {
'id': 'sidebarDrawer',
'rightDrawer': true,
'drawerWidth': browseState.sidePanelCollapsed ?
'0%' : browseState.sidePanelWidth,
'responsiveWidth': '0px'
}
}, [
h('core-header-panel.browse-main-panel', {
attributes: {
'main': true
}
}, [
mainView
]),
h('core-header-panel.browse-details-sidebar', {
attributes: {
'drawer': true
}
}, [
h('div.resize-handle', {
'ev-mousedown': function(e) {
browseEvents.slideSidePanel({
rawEvent: e,
collapsed: browseState.sidePanelCollapsed
});
}
}),
sideView
])
])
];
return h('core-drawer-panel', {
attributes: {
'drawerWidth': '0px'
}
}, [
h('core-header-panel', {
attributes: {
'main': true
}
}, [
view
])
]);
}
/*
* Renders the addressbar for entering namespace
*/
function renderNamespaceBox(browseState, browseEvents, navEvents) {
// Trigger an actual navigation event when value of the inputs change
var changeEvent = new PropertyValueEvent(function(val) {
var namespace = browseState.namespace;
if (exists(val)) {
namespace = val;
}
navEvents.navigate({
path: browseRoute.createUrl(browseState, {
namespace: namespace
})
});
}, 'value', true);
// Change the namespace suggestions if the user types into the namespace box.
// Ideally, this would be the input event handler. See inputEvent below.
var trueInputEvent = new PropertyValueEvent(function(val) {
browseEvents.getNamespaceSuggestions(val);
}, 'value', false);
// TODO(alexfandrianto): A workaround for Mercury/Polymer. The
// paper-autocomplete's input value updates after Mercury captures the event.
// If we defer handling the event, then the input has time to update itself to
// the correct, new value.
var inputEvent = function(ev) {
setTimeout(trueInputEvent.handleEvent.bind(trueInputEvent, ev), 0);
};
// The focus event also retrieves namespace suggestions.
var focusEvent = inputEvent;
var children = browseState.namespaceSuggestions.map(
function renderChildItem(child) {
return h('paper-item', child.mountedName);
}
);
return h('div.namespace-box',
h('div', {
attributes: {
'layout': 'true',
'horizontal': 'true'
}
}, [
h('core-tooltip.icontooltip', {
attributes: {
'label': 'Reload'
},
'position': 'bottom'
},
h('paper-icon-button.icon', {
attributes: {
'icon': 'refresh',
'label': 'Reload'
},
'ev-click': mercury.send(navEvents.reload)
})
),
h('core-tooltip.nstooltip', {
attributes: {
'label': 'Enter a name to browse, e.g. house/living-room'
},
'position': 'bottom'
},
h('paper-autocomplete.autocomplete', {
attributes: {
'name': 'namespace',
'value': browseState.namespace,
'delimiter': '/',
'flex': 'true',
'spellcheck': 'false',
'maxItems': NAMESPACE_AUTOCOMPLETE_MAX_ITEMS
},
'ev-focus': focusEvent,
'ev-input': inputEvent,
'ev-change': changeEvent
}, children)
)
])
);
}
function createActionIcon(tooltip, icon, href, isSelected) {
var view = h('core-tooltip', {
'label': tooltip,
'position': 'bottom'
},
h('a', {
attributes: {
'href': href
}
}, h('paper-icon-button.icon' + (isSelected ? '.selected' : ''), {
attributes: {
'icon': icon
}
}))
);
return view;
}
/*
* Renders the view switchers for different views and bookmarks, recommendations
*/
function renderToolbar(browseState, navEvents) {
var selectedActionKey = browseState.subPage;
if (browseState.subPage === 'views') {
selectedActionKey = browseState.views.viewType;
}
var switchGroup = h('div.icon-group', [
createActionIcon('Tree view', 'list',
browseRoute.createUrl(browseState, {
viewType: 'tree'
}), selectedActionKey === 'tree'
),
createActionIcon('Radial view', 'image:filter-tilt-shift',
browseRoute.createUrl(browseState, {
viewType: 'visualize'
}), selectedActionKey === 'visualize'
),
createActionIcon('Grid view', 'apps',
browseRoute.createUrl(browseState, {
viewType: 'grid'
}), selectedActionKey === 'grid'
)
]);
var breadcrumbs = renderBreadcrumbs(browseState, navEvents);
var ruler = h('div.vertical-ruler');
var bookmarkGroup = h('div.icon-group', [
createActionIcon('Bookmarks', 'bookmark-outline',
bookmarksRoute.createUrl(),
selectedActionKey === 'bookmarks'
),
createActionIcon('Recent', 'schedule',
recommendationsRoute.createUrl(),
selectedActionKey === 'recommendations')
]);
var searchGroup = renderSearch(browseState, navEvents);
var view = h('div.browse-toolbar-layout', {
attributes: {
'layout': 'true',
'horizontal': 'true'
}
}, [
switchGroup,
ruler,
breadcrumbs,
ruler,
bookmarkGroup,
ruler,
searchGroup
]);
return view;
}
/*
* Renders the globquery searchbox, used to filter the globbed names.
*/
function renderSearch(browseState, navEvents) {
// Trigger an actual navigation event when value of the inputs change
var changeEvent = new PropertyValueEvent(function(val) {
navEvents.navigate({
path: browseRoute.createUrl(browseState, {
globQuery: val,
// TODO(aghassemi): We only support grid view for search, we could
// potentially support other views such as tree too but it's tricky.
viewType: 'grid'
})
});
}, 'value', true);
var clearSearch;
if (browseState.globQuery) {
clearSearch = h('paper-icon-button.icon.clear-search', {
attributes: {
'icon': 'clear',
'label': 'Clear search'
},
'ev-click': mercury.event(navEvents.navigate, {
path: browseRoute.createUrl(browseState)
})
});
}
return h('div.search-box',
h('core-tooltip.tooltip', {
attributes: {
'label': 'Enter Glob query for searching, e.g., */*/a*'
},
'position': 'bottom'
},
h('div', {
attributes: {
'layout': 'true',
'horizontal': 'true'
}
}, [
h('core-icon.icon', {
attributes: {
'icon': 'search'
}
}),
h('paper-input.input', {
attributes: {
'flex': 'true',
'spellcheck': 'false',
'label': 'Glob Search'
},
'name': 'globQuery',
'value': browseState.globQuery,
'ev-change': changeEvent
}),
clearSearch
])
)
);
}
/*
* Renders the current name being browsed, split into parts.
* Starts at the top of the name and goes all the way to the selected item.
* Each name part is a link to a parent.
*/
function renderBreadcrumbs(browseState, navEvents) {
var name = browseState.selectedItemName || browseState.namespace;
var isRooted = namespaceService.util.isRooted(name);
var namespaceParts = namespaceService.util.parseName(name);
var parentParts = namespaceService.util.parseName(browseState.namespace);
var breadCrumbs = [];
if (!isRooted) {
// Add a relative root (empty namespace)
var rootUrl = browseRoute.createUrl(browseState, {
namespace: ''
});
breadCrumbs.push(h('li.breadcrumb-item.relative-name' +
(parentParts.length ? '.breadcrumb-item-prefix' : ''), [
//TODO(aghassemi) refactor link generation code
h('a', {
'href': rootUrl,
'ev-click': mercury.event(navEvents.navigate, {
path: rootUrl
})
}, '<Home>')
]));
}
parentParts.pop(); // remove last part (current view root)
for (var i = 0; i < namespaceParts.length; i++) {
var namePart = namespaceParts[i].trim();
var fullName = (isRooted ? '/' : '') +
namespaceService.util.join(namespaceParts.slice(0, i + 1));
var url = browseRoute.createUrl(browseState, {
namespace: fullName
});
var isPartOfParent = parentParts.indexOf(namePart) > -1;
var cssClass = 'breadcrumb-item';
if (isPartOfParent) {
cssClass += '.breadcrumb-item-prefix';
}
var listItem = h('li.' + cssClass, [
h('a', {
'href': url,
'ev-click': mercury.event(navEvents.navigate, {
path: url
})
}, namePart)
]);
breadCrumbs.push(listItem);
}
var bc = h('ul.breadcrumbs', breadCrumbs);
return h('div.breadcrumbs-wrapper', bc);
}
// Wire up events that we know how to handle
function wireUpEvents(state, events) {
events.browseNamespace(browseNamespace.bind(null, state, events));
events.getNamespaceSuggestions(getNamespaceSuggestions.bind(null, state));
events.selectItem(function(data) {
state.selectedItemName.set(data.name);
events.selectedItemDetails.displayItemDetails(data);
});
events.toggleSidePanel(function(data) { // hide side panel
state.sidePanelCollapsed.set(data.collapsed);
var drawer = document.querySelector('#sidebarDrawer');
if (!drawer) {
return;
}
//Fire a window resize event when animation ends so components can adjust
//based on the new view port size
// TODO(aghassemi): specific to webkit
drawer.addEventListener('webkitTransitionEnd', fireResizeEvent);
});
events.slideSidePanel(function(data) { // resize side panel
// ignore if not primary button, or if side panel is collapsed
if (data.rawEvent.button !== 0 || data.collapsed) {
return;
}
var dragX = data.rawEvent.clientX; // initial position of drag target
var drawer = document.querySelector('#sidebarDrawer');
var oldP = +drawer.getAttribute('drawerWidth').replace('%', '');
var oldW = drawer.offsetWidth; // width of both panels in pixels
drawer.querySelector('::shadow core-selector').
classList.remove('transition');
window.addEventListener('mousemove', slideMove);
window.addEventListener('mouseup', slideEnd);
function slideMove(e) { // move
var dx = e.clientX - dragX;
var newP = Math.min(Math.max(oldP - (dx * 100 / oldW), 10), 90);
drawer.setAttribute('drawerWidth', newP.toFixed(2) + '%');
e.preventDefault(); // avoid selecting text
}
function slideEnd(e) { // release
window.removeEventListener('mouseup', slideEnd);
window.removeEventListener('mousemove', slideMove);
drawer.querySelector('::shadow core-selector').
classList.add('transition');
var drawerWidth = drawer.getAttribute('drawerWidth');
// async call to persist the drawer width
stateService.saveSidePanelWidth(drawerWidth);
state.sidePanelWidth.set(drawerWidth);
state.sidePanelCollapsed.set(false);
fireResizeEvent(null);
} // end slideEnd
}); // end events.slideSidePanel
function fireResizeEvent(e) { // resize on end animation
var evt = document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(evt);
if (e !== null) { // not if called by slideEnd
// TODO(aghassemi): specific to webkit
document.querySelector('#sidebarDrawer').
removeEventListener('webkitTransitionEnd', fireResizeEvent);
}
}
}
},{"../../lib/exists":218,"../../lib/log":223,"../../lib/mercury/property-value-event":228,"../../routes/bookmarks":236,"../../routes/browse":237,"../../routes/recommendations":242,"../../services/namespace/service":248,"../../services/smart/service":251,"../../services/state/service":252,"./bookmarks/index":145,"./browse-namespace":146,"./get-namespace-suggestions":147,"./index.css":149,"./item-details/index":160,"./recommendations/index":179,"./views/index":181,"insert-css":37,"mercury":45}],151:[function(require,module,exports){
module.exports = ":root{}.items-container{display:flex;flex-direction:row;flex-wrap:wrap;border-bottom:solid 1px rgba(0, 0, 0, 0.12);padding-bottom:0.5em;}.items-container:last-child{border-bottom:none;}"
},{}],152:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var ItemCard = require('./item-card/index');
var css = require('./index.css');
var h = mercury.h;
module.exports.render = render;
/*
* Renders a list of namespace items as cards in a list.
* @param opts.title {string} Title for the list. e.g "Bookmarks"
* @param opts.emptyText {string} Text to render when items is empty.
* e.g No Bookmarks found.
* @param items {Array<namespaceitem>} @see services/namespace/item
*/
function render(items, browseState, browseEvents, navEvents, opts) {
insertCss(css);
var view;
if (browseState.isFinishedLoadingItems && items.length === 0) {
view = h('div.empty', h('span', opts.emptyText));
} else {
view = items.map(function(item) {
return ItemCard.render(item, browseState, browseEvents, navEvents,
opts.showShortName, opts.hoverActionInfo);
});
}
var heading = h('h2', opts.title);
return [heading, h('div.items-container', view)];
}
},{"./index.css":151,"./item-card/index":154,"insert-css":37,"mercury":45}],153:[function(require,module,exports){
module.exports = ":root{}:root{}.item.card{box-sizing:border-box;background-color:#ffffff;display:flex;flex-shrink:1;flex-grow:1;height:2.5em;min-width:15em;width:30%;margin:0.375em 0.75em;border-radius:3px;position:relative;box-shadow:0 2px 10px 0 rgba(0, 0, 0, 0.2);border:solid 1px rgba(0, 0, 0, 0.12);}.item .label,.item .drill{display:flex;flex-direction:row;align-items:center;padding:0.5em;}.item .label{text-decoration:none;flex:1;overflow:hidden;white-space:nowrap;}.item .drill{width:1.5em;background-color:#FAFAFA;border-left:solid 1px rgba(0, 0, 0, 0.12);}.item.selected .drill{background-color:#FF6E40;}.item.card .action-icon{align-self:center;padding-right:0.5em;}.item.selected.card .action-icon{color:#ffffff;}.item.selected.card{background-color:#FF6E40;color:#ffffff;}.item.selected.card .drill{border-color:rgba(0, 0, 0, 0.26);}.item.card a:hover,.item.card .action-bar:hover paper-fab::shadow #icon{opacity:0.7;}.item.card .action-bar{position:absolute;top:-10px;right:-10px;visibility:hidden;transition:visibility 0s;}.item.card .action-bar paper-fab{height:20px;width:20px;padding:3px;background:#00838F;}.item.card .action-bar paper-fab::shadow #icon{height:14px;width:14px;color:#ffffff;}.item.card:hover .action-bar,.item.selected.card .action-bar,.item.card:focus .action-bar{visibility:visible;transition-delay:0.5s;}"
},{}],154:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var getServiceIcon = require('../../get-service-icon');
var browseRoute = require('../../../../routes/browse');
var css = require('./index.css');
var h = mercury.h;
module.exports.render = render;
/*
* Renders a namespace item in a card view.
* @param item {namespaceitem} @see services/namespace/item
*/
function render(item, browseState, browseEvents, navEvents, showShortName,
hoverActionInfo) {
insertCss(css);
var selected = (browseState.selectedItemName === item.objectName);
var url = browseRoute.createUrl(browseState, {
namespace: item.objectName
});
// Prepare the drill if this item happens to be globbable.
var expandAction = null;
if (!item.isLeaf) {
expandAction = h('a.drill', {
'href': url,
'ev-click': mercury.event(navEvents.navigate, {
path: url
})
}, h('core-icon.action-icon', {
attributes: {
'icon': 'chevron-right'
}
}));
}
// Prepare tooltip and service icon information for the item.
var itemTooltip = item.objectName;
var iconCssClass = '.service-type-icon';
var iconAttributes = {};
var iconInfo = getServiceIcon(item);
iconAttributes.attributes = {
title: iconInfo.title,
icon: iconInfo.icon
};
// Construct the service icon.
var iconNode = h('core-icon' + iconCssClass, iconAttributes);
// Put the item card's pieces together.
var itemClassNames = 'item.card' + (selected ? '.selected' : '');
var cardLabel = (showShortName ? item.mountedName : item.objectName) ||
'<Home>';
var hoverAction;
if (hoverActionInfo) {
hoverAction = renderHoverAction(item.objectName, hoverActionInfo);
}
return h('div.' + itemClassNames, {
'title': itemTooltip
}, [
h('a.label', {
'href': 'javascript:;',
'ev-click': mercury.event(
browseEvents.selectItem, {
name: item.objectName
})
}, [
iconNode,
h('span.right-justify', cardLabel)
]),
expandAction,
hoverAction
]);
}
/*
* The hover action must have an icon and an event handler.
*/
function renderHoverAction(objectName, hoverAction) {
return h('div.action-bar', h('paper-fab', {
attributes: {
'aria-label': hoverAction.description,
'title': hoverAction.description,
'icon': hoverAction.icon,
'mini': true
},
'ev-click': hoverAction.action.bind(null, objectName)
}));
}
},{"../../../../routes/browse":237,"../../get-service-icon":148,"./index.css":153,"insert-css":37,"mercury":45}],155:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var bookmarksService = require('../../../services/bookmarks/service');
var log = require('../../../lib/log')(
'components:browse:item-details:bookmark');
module.exports = bookmark;
function bookmark(state, events, data) {
var wasBookmarked = state.isBookmarked();
// If this is the current item, set the bookmark flag.
if (state.itemName() === data.name) {
state.isBookmarked.set(data.bookmark);
}
bookmarksService.bookmark(data.name, data.bookmark).then(function() {
var toastText = 'Bookmark ' +
(data.bookmark ? 'added' : 'removed') +
' for ' + data.name;
var undoAction = bookmark.bind(null, state, events, {
name: data.name,
bookmark: !data.bookmark
});
events.toast({
text: toastText,
action: undoAction,
actionText: 'UNDO'
});
}).catch(function(err) {
var errText = 'Failed to ' +
(data.bookmark ? 'add ' : 'remove') +
'bookmark for ' + data.name;
log.error(errText, err);
// If the name is selected on error, reset state back to what it used to be.
if (state.itemName() === data.name) {
state.isBookmarked.set(wasBookmarked);
}
events.toast({
text: errText,
type: 'error'
});
});
}
},{"../../../lib/log":223,"../../../services/bookmarks/service":244}],156:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var ServerDetails = require('./server-details');
var MountPointDetails = require('./mount-point-details');
var namespaceService = require('../../../services/namespace/service');
var smartService = require('../../../services/smart/service');
var bookmarkService = require('../../../services/bookmarks/service');
var pluginRegistry = require('../../../item-plugins/registry');
var log = require('../../../lib/log')(
'components:browse:item-details:display-item-details'
);
module.exports = displayItemDetails;
// Holds name of the last requested name.
var lastRequestedName;
/*
* Displays the details section for an item which includes <1,n> tabs
* for server details and/or mount point details and/or plugins
* and actions such as bookmaking
*/
function displayItemDetails(state, events, data) {
var name = data.name;
lastRequestedName = name;
state.put('plugins', mercury.array([]));
state.put('error', null);
state.put('item', null);
state.selectedTabKey.set(null);
state.itemName.set(name);
state.isBookmarked.set(false);
// Whether we have finished loading yet.
var isLoaded = false;
// How long to wait before showing loading if things have not loaded yet
var SHOW_LOADING_THRESHOLD = 250;
setTimeout(function maybeShowLoadingIndicator() {
if (isLoaded || !isCurrentlySelected()) {
return;
}
state.put('showLoadingIndicator', true);
}, SHOW_LOADING_THRESHOLD);
loadBookmark().catch(function(err) {
log.error('Could not load bookmark status for', name, err);
});
return namespaceService.getNamespaceItem(name).then(loadDetails).
catch(function(err) {
log.error('Error while loading ', name, err);
if (!isCurrentlySelected()) {
return;
}
events.toast({
text: 'Error while loading ' + name,
type: 'error'
});
state.put('error', err);
setIsLoaded();
});
function loadDetails(itemObs) {
/*
* Since async call, by the time we are here, a different name
* might be selected.
* We don't want out of order results override everything!
*/
if (!isCurrentlySelected()) {
return;
}
state.put('item', itemObs);
if (itemObs().hasServer) {
ServerDetails.displayServerDetails(state.serverDetails,
events.serverDetails, {
itemObs: itemObs
});
}
if (itemObs().hasMountPoint) {
MountPointDetails.displayMountPointDetails(state.mountPointDetails,
events.mountPointDetails, {
itemObs: itemObs
});
}
return loadPlugins(itemObs()).then(function() {
// Log the name to the smart service as a potential shortcut, since it was
// successfully visited.
smartService.update('learner-shortcut', {
name: name
}).catch(function(err) {
log.error('Error while updating shortcut learner', err);
});
// Indicate we finished loading
setIsLoaded();
});
}
function loadBookmark() {
// Asynchronously load the bookmark. It should be quite fast.
return bookmarkService.isBookmarked(name).then(function(isBookmarked) {
// Protect this call; this must be the selected item.
if (!isCurrentlySelected()) {
return;
}
state.isBookmarked.set(isBookmarked);
});
}
function loadPlugins(item) {
if (!item.hasServer) {
return Promise.resolve();
}
return namespaceService.getSignature(name).then(function(sig) {
// Protect this call; this must be the selected item.
if (!isCurrentlySelected() || !sig) {
return;
}
// Load plugins
var plugins = pluginRegistry.matches(name, sig);
state.put('plugins', plugins);
}).catch(function(err) {
log.warn('Could not load any plugins because could not load signature',
name, err);
});
}
/*
* Indicates the current request has finished loading
*/
function setIsLoaded() {
isLoaded = true;
state.put('showLoadingIndicator', false);
}
/*
* Returns whether we are still the currently selected item or not
*/
function isCurrentlySelected() {
return (name === lastRequestedName);
}
}
},{"../../../item-plugins/registry":213,"../../../lib/log":223,"../../../services/bookmarks/service":244,"../../../services/namespace/service":248,"../../../services/smart/service":251,"./mount-point-details":165,"./server-details":171,"mercury":45}],157:[function(require,module,exports){
module.exports = ":root{}:root{}.field{font-size:0.9em;margin-bottom:0.75em;}.field.collapsed{border-bottom:solid 1px rgba(0, 0, 0, 0.12);}.field .header h4{margin:0;color:rgba(0, 0, 0, 0.54);flex:1;}.field .header{display:flex;flex-direction:row;word-break:break-word;}.field .content{white-space:normal;word-break:break-word;}"
},{}],158:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
function create() {}
/*
* Renders a single field item
*/
function render(label, content, options) {
insertCss(css);
options = options || {};
var hlabel = h('h4', label);
var hinfo = h('span');
if (options.labelTooltip) {
// If there is a tooltip, create an info icon with that tooltip.
hinfo = h('core-tooltip.tooltip.field-tooltip', {
attributes: {
'label': options.labelTooltip
},
'position': 'left'
}, h('core-icon.icon.info', {
attributes: {
'icon': 'info'
}
}));
}
content = h('div', {
key: label,
}, content);
if (options.contentTooltip) {
// If there is a tooltip, wrap the content in it.
content = h('core-tooltip.tooltip.field-tooltip', {
attributes: {
'label': options.contentTooltip
},
'position': 'right'
}, content);
}
var expander = h('span');
if (options.collapsed !== undefined) {
expander = h('core-icon.icon', {
attributes: {
'icon': options.collapsed ? 'chevron-right' : 'expand-more'
},
'ev-click': options.callback
});
}
return h('div.field' + (options.collapsed === true ? '.collapsed' : ''), [
h('div.header', [
hlabel,
hinfo,
expander
]),
h('div.content', content)
]);
}
},{"./index.css":157,"insert-css":37,"mercury":45}],159:[function(require,module,exports){
module.exports = ":root{}:root{}:root{}:root{}.item.card{box-sizing:border-box;background-color:#ffffff;display:flex;flex-shrink:1;flex-grow:1;height:2.5em;min-width:15em;width:30%;margin:0.375em 0.75em;border-radius:3px;position:relative;box-shadow:0 2px 10px 0 rgba(0, 0, 0, 0.2);border:solid 1px rgba(0, 0, 0, 0.12);}.item .label,.item .drill{display:flex;flex-direction:row;align-items:center;padding:0.5em;}.item .label{text-decoration:none;flex:1;overflow:hidden;white-space:nowrap;}.item .drill{width:1.5em;background-color:#FAFAFA;border-left:solid 1px rgba(0, 0, 0, 0.12);}.item.selected .drill{background-color:#FF6E40;}.item.card .action-icon{align-self:center;padding-right:0.5em;}.item.selected.card .action-icon{color:#ffffff;}.item.selected.card{background-color:#FF6E40;color:#ffffff;}.item.selected.card .drill{border-color:rgba(0, 0, 0, 0.26);}.item.card a:hover,.item.card .action-bar:hover paper-fab::shadow #icon{opacity:0.7;}.item.card .action-bar{position:absolute;top:-10px;right:-10px;visibility:hidden;transition:visibility 0s;}.item.card .action-bar paper-fab{height:20px;width:20px;padding:3px;background:#00838F;}.item.card .action-bar paper-fab::shadow #icon{height:14px;width:14px;color:#ffffff;}.item.card:hover .action-bar,.item.selected.card .action-bar,.item.card:focus .action-bar{visibility:visible;transition-delay:0.5s;}paper-icon-button.bookmarked{color:#FF6E40;}.tab-icon{width:1.2em;height:1.2em;margin-right:0.7em;}.item-actions{margin:0 -0.5em;display:inline-block;position:absolute;left:0.5em;top:0px;padding:0.5em;}.sidebar-header .name-title{display:inline-block;padding:0.75em 75px;overflow:hidden;white-space:nowrap;}.sidebar-header{box-shadow:0px 3px 2px rgba(0, 0, 0, 0.2);text-align:center;background-color:#00838F;border-bottom:solid 1px rgba(0, 0, 0, 0.12);}.sidebar-header .name-title,.sidebar-header paper-icon-button{color:#ffffff;}.padded-error-box{padding:1em;}.method-input{display:inline-block;vertical-align:top;width:16em;}.tooltip.field-tooltip::shadow .core-tooltip,.tooltip.method-tooltip::shadow .core-tooltip{line-height:0.9em;white-space:pre-wrap;font-size:0.7em;}.tooltip.field-tooltip::shadow .core-tooltip{width:24em;}.tooltip.field-tooltip::shadow .core-tooltip{width:36em;}.method-input .label{align-items:center;overflow:hidden;}.method-input paper-autocomplete{width:100%;}.method-input .drill.star{border-left:none;border-right:solid 1px rgba(0, 0, 0, 0.12);}.method-input-expanded{margin-bottom:1em;padding:0.5em;}.method-input-item{box-sizing:border-box;padding:0.5em;}.method-output table,.method-output th{border-bottom:solid 1px rgba(0, 0, 0, 0.12);}.method-output th:nth-of-type(2),.method-output td:nth-of-type(2) pre{white-space:nowrap;}.method-output th,.method-output td{text-align:left;padding:0.2em;}.method-output pre,.field pre{white-space:pre-wrap;}.method-input .item.card.invocation{margin-top:0em;margin-bottom:0em;height:2em;margin-top:0.2em;}.method-input .item.card.invocation .label{font-size:0.9em;}core-icon.info{color:#00838F;}core-icon.error{color:#D32F2F;}core-icon.starred{color:#FF6E40;}"
},{}],160:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var PolymerEvent = require('../../../lib/mercury/polymer-event');
var displayItemDetails = require('./display-item-details');
var browseRoute = require('../../../routes/browse');
var bookmark = require('./bookmark');
var PluginWidgetAdapter = require('./plugin-widget-adapter');
var ErrorBox = require('../../error/error-box');
var ServerDetails = require('./server-details');
var MountPointDetails = require('./mount-point-details');
var namespaceUtil = require('../../../services/namespace/service').util;
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
/*
* ItemDetails component provides user interfaces for displaying details for
* a browse item such is its type, signature, etc.
*/
function create() {
var serverDetailsComponent = new ServerDetails();
var mountPointDetailsComponent = new MountPointDetails();
var state = mercury.varhash({
/*
* objectName for the item we are showing details of.
* We keep this in addition to item.objectName since item object may not be
* present (when in the middle of loading or when failed to load).
* Keeping itemName separate allows us to render a header with add/remove
* bookmark actions even when item is loading or has failed to load.
* @type {string}
*/
itemName: mercury.value(''),
/*
* namespace item to display details for.
* @see services/namespace/item
* @type {namespaceitem}
*/
item: mercury.value(null),
/*
* Which tab to display. Key is a unique string e.g. ('details' or <plugin>)
* @type {string}
*/
selectedTabKey: mercury.value(null),
/*
* List of item plugins supported for this item
* @type {itemplugin}
* @see {item-plugins/plugin.js.doc}
*/
plugins: mercury.array([]),
/*
* Any fatal error while getting the item.
* Note: will be displayed to user.
* @type Error
*/
error: mercury.value(null),
/*
* State for the serverDetails component
* @type {mercury.struct}
*/
serverDetails: serverDetailsComponent.state,
/*
* State for the mountPointDetails component
* @type {mercury.struct}
*/
mountPointDetails: mountPointDetailsComponent.state,
/*
* Whether the items is bookmarked or not
* @type {boolean}
*/
isBookmarked: mercury.value(false)
});
var events = mercury.input([
'bookmark',
'displayItemDetails',
'tabSelected',
'toast',
'serverDetails',
'mountPointDetails'
]);
events.serverDetails = serverDetailsComponent.events;
events.mountPointDetails = mountPointDetailsComponent.events;
wireUpEvents(state, events);
return {
state: state,
events: events
};
}
var DETAILS_TAB_KEY = 'details';
var MOUNTPOINT_TAB_KEY = 'mountpoint';
/*
* Render the actions and tabs.
*/
function render(state, events, browseState, navEvents) {
insertCss(css);
var content = [];
// The header is always rendered and contains actions and name of the item.
var headerContent = renderHeaderContent(state, events, browseState,
navEvents);
content.push(headerContent);
if (state.item) {
var tabTitles = renderTabTitles(state, events);
var selectedTabContent =
renderSelectedTabContent(state, events, browseState, navEvents);
var tabs = [h('paper-tabs.tabs', {
attributes: {
'valueattr': 'tabkey',
'selected': getSelectedTabKey(state),
'noink': true
}
}, tabTitles),
selectedTabContent
];
content.push(tabs);
}
// Show any errors from getting the item
if (state.error) {
var errorTitle = 'Unable to resolve ' + state.itemName;
content.push(
h('div.padded-error-box',
ErrorBox.render(errorTitle, state.error.toString())
)
);
}
return content;
}
/*
* Renders the header which includes actions and name field.
* Header is always displayed, even during loading time or when we fail
* to load details for an item.
* Note: we should be able to render header without loading signature. Any
* information about the item other than name and whether it is bookmarked.
*/
function renderHeaderContent(state, events, browseState, navEvents) {
var actions = renderActions(state, events, browseState, navEvents);
var name = namespaceUtil.basename(state.itemName) || '<Home>';
var headerItems = h('div.sidebar-header', [
actions,
h('div.name-title', name)
]);
return headerItems;
}
/*
* Renders an action bar on top of the tabs.
*/
function renderActions(state, events, browseState, navEvents) {
// Collect a list of actions.
var actions = [];
// Bookmark action (Add or remove a bookmark)
var isBookmarked = state.isBookmarked;
var bookmarkIcon = 'bookmark' + (!isBookmarked ? '-outline' : '');
var bookmarkTitle = (isBookmarked ? 'Remove Bookmark ' : 'Add Bookmark');
var bookmarkAction = h('core-tooltip', {
attributes: {
'label': bookmarkTitle,
'position': 'right'
}
},
h('paper-icon-button' + (isBookmarked ? '.bookmarked' : ''), {
attributes: {
'icon': bookmarkIcon,
'alt': bookmarkTitle
},
'ev-click': mercury.event(events.bookmark, {
bookmark: !isBookmarked,
name: state.itemName
})
})
);
actions.push(bookmarkAction);
// Browse-up action (Navigate to the namespace's parent)
// This action only appears if the namespace's parent is not empty.
var parent = namespaceUtil.stripBasename(browseState.namespace);
var noParent = (parent === '' && (browseState.namespace[0] === '/' ||
browseState.namespace === ''));
if (!noParent) {
var browseUpUrl = browseRoute.createUrl(browseState, {
namespace: parent
});
var parentName = parent || '<Home>';
var browseUpTitle = 'Browse up to ' + parentName;
var browseUpAction = h('core-tooltip', {
attributes: {
'label': browseUpTitle,
'position': 'right'
}
},
h('a', {
'href': browseUpUrl,
'ev-click': mercury.event(navEvents.navigate, {
path: browseUpUrl
})
}, h('paper-icon-button', {
attributes: {
'icon': 'undo',
'alt': browseUpTitle
}
}))
);
actions.push(browseUpAction);
}
// Browse action (Navigate into this item)
// This action only appears if this item is not a leaf and distinct from the
// current namespace.
var isLeaf = state.item ? state.item.isLeaf : false;
if (browseState.namespace !== state.itemName && !isLeaf) {
var browseUrl = browseRoute.createUrl(browseState, {
namespace: state.itemName
});
var itemName = state.itemName || '<Home>';
var browseTitle = 'Browse into ' + itemName;
var browseAction = h('core-tooltip', {
attributes: {
'label': browseTitle,
'position': 'right'
}
},
h('a', {
'href': browseUrl,
'ev-click': mercury.event(navEvents.navigate, {
path: browseUrl
})
}, h('paper-icon-button', {
attributes: {
'icon': 'launch',
'alt': browseTitle
}
}))
);
actions.push(browseAction);
}
return h('div.icon-group.item-actions', actions);
}
/*
* Renders the tab titles such as details and tabs for support plugins
* It uses the plugins id as the tab key for the core-selector component.
*/
function renderTabTitles(state, events) {
var allTabs = [];
// Server details tab
if (state.item && state.item.hasServer) {
allTabs.push(
renderTabTitle(state, events, DETAILS_TAB_KEY,
'vanadium:service', 'Service')
);
}
// Mount point tab
if (state.item && state.item.hasMountPoint) {
allTabs.push(
renderTabTitle(state, events, MOUNTPOINT_TAB_KEY,
'vanadium:mountpoint', 'MountPoint')
);
}
// Plugin tabs
var pluginTabs = state.plugins.map(function(p) {
var pluginTabKey = p.id;
var pluginIcon = p.icon || 'help';
return renderTabTitle(state, events, pluginTabKey, pluginIcon, p.title);
});
return allTabs.concat(pluginTabs);
}
/*
* Renders the selected tab content.
*/
function renderSelectedTabContent(state, events, browseState, navEvents) {
var selectedTabKey = getSelectedTabKey(state);
var view;
switch (selectedTabKey) {
case DETAILS_TAB_KEY:
view = ServerDetails.render(state.serverDetails, events.serverDetails,
browseState, navEvents);
return renderTabContent(view);
case MOUNTPOINT_TAB_KEY:
view = MountPointDetails.render(state.mountPointDetails,
events.mountPointDetails, browseState, navEvents);
return renderTabContent(view);
default:
// potentially a plugin tab
var plugin = state.plugins.filter(function(p) {
return p.id === selectedTabKey;
})[0];
if (plugin) {
view = new PluginWidgetAdapter(state.itemName, plugin);
return renderTabContent(view);
} else {
throw 'Unknown tab key: ' + selectedTabKey;
}
}
}
/*
* Render tab title given a title string and tab key
*/
function renderTabTitle(state, events, tabKey, icon, title) {
return h('paper-tab.tab', {
attributes: {
'tabkey': tabKey
},
'ev-click': new PolymerEvent(function(data) {
events.tabSelected({
tabKey: tabKey
});
})
}, [
h('core-icon.tab-icon', {
attributes: {
'icon': icon,
'alt': '' // because we have the title beside it
}
}), title
]);
}
/*
* Render tab content given the tabContent by wrapping it in a container
*/
function renderTabContent(tabContent) {
return h('div.tab-content', tabContent);
}
/*
* Returns the currently selected tab key
*/
function getSelectedTabKey(state) {
var selectedTabKey = state.selectedTabKey;
if (!selectedTabKey) {
if (!state.item.hasServer) {
selectedTabKey = MOUNTPOINT_TAB_KEY;
} else {
selectedTabKey = DETAILS_TAB_KEY;
}
}
return selectedTabKey;
}
// Wire up events that we know how to handle
function wireUpEvents(state, events) {
events.serverDetails.toast = function(data) {
events.toast(data);
};
events.mountPointDetails.toast = function(data) {
events.toast(data);
};
events.bookmark(bookmark.bind(null, state, events));
events.displayItemDetails(displayItemDetails.bind(null, state, events));
events.tabSelected(function(data) {
state.selectedTabKey.set(data.tabKey);
});
}
},{"../../../lib/mercury/polymer-event":227,"../../../routes/browse":237,"../../../services/namespace/service":248,"../../error/error-box":191,"./bookmark":155,"./display-item-details":156,"./index.css":159,"./mount-point-details":165,"./plugin-widget-adapter":167,"./server-details":171,"insert-css":37,"mercury":45}],161:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var _ = require('lodash');
var uuid = require('uuid');
var makeRPC = require('./make-rpc.js');
var arraySet = require('../../../../lib/array-set');
var setMercuryArray = require('../../../../lib/mercury/set-mercury-array');
var PropertyValueEvent =
require('../../../../lib/mercury/property-value-event');
var store = require('../../../../lib/store');
var smartService = require('../../../../services/smart/service');
var getMethodData =
require('../../../../services/namespace/interface-util').getMethodData;
var hashInterface =
require('../../../../services/namespace/interface-util').hashInterface;
var log = require('../../../../lib/log')(
'components:browse:item-details:method-form');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
// While an unlimited # of items are predicted per input, it's a bad idea to
// show them all. Limit to 4 at a time, and rely on filtering to find the rest.
var METHOD_INPUT_MAX_ITEMS = 4;
/*
* Create the base state and events necessary to render a method form.
* Call the displayMethodForm event to fill this state with more data.
*/
function create() {
var state = mercury.varhash({
/*
* Item name to target RPCs against.
* @type {string}
*/
itemName: mercury.value(''),
/*
* The item's interface.
* @type {interface}
*/
interface: mercury.value(null),
/*
* Method name for this method form
* @type {string}
*/
methodName: mercury.value(''),
/*
* Argument values that can be used to invoke the methodName RPC.
* @type {Array<string>}
*/
args: mercury.array([]),
/*
* Set of starred invocations saved by the user. There is no size limit.
* An array is used to preserve order.
* Each value in this array is a JSON-encoded array of argument values.
* This only contains keys of starred items; unstarred ones are removed.
* @type {Array<string>}
*/
starred: mercury.array([]),
/*
* Limited list of invocations recommended to the user.
* Each invocation is a JSON-encoded array of argument values.
* Order affects rendering priority; some may never be rendered.
* @type {Array<string>}
*/
recommended: mercury.array([]),
/*
* The autocomplete suggestions for each of this method's inputs.
* @type {Array<string>}
*/
inputSuggestions: mercury.array([]),
/*
* Whether the method form is in its expanded state or not.
* @type {boolean}
*/
expanded: mercury.value(false)
});
var events = mercury.input([
'displayMethodForm', // the main event used to prepare the form data
'methodStart', // notify parent element of RPC start
'methodEnd', // notify parent element of RPC end result
'runAction', // run the RPC with given arguments
'expandAction', // show/hide method arguments
'starAction', // star/unstar a method invocation
'removeRecommendation', // remove and reload recommended invocations
'removeInputSuggestion', // remove and reload input suggestions
'toast'
]);
wireUpEvents(state, events);
return {
state: state,
events: events
};
}
/*
* Event handler that sets and prepares data into this form component.
* data needs to include "itemName", "interface", and "methodName".
*/
function displayMethodForm(state, events, data) {
// Set the given data into the state and prepare the method form.
state.itemName.set(data.itemName);
state.interface.set(data.interface);
state.methodName.set(data.methodName);
initializeInputArguments(state);
// Prepare the remaining state asynchronously.
refreshInputSuggestions(state).catch(function(err) {
log.error('Could not get input suggestions for', data.methodName, err);
});
loadStarredInvocations(state).catch(function(err) {
events.toast({
text: 'Could not load stars for ' + data.methodName,
type: 'error'
});
log.error('Could not load stars for', data.methodName, err);
});
refreshRecommendations(state).catch(function(err) {
log.error('Could not get recommended invocations for',
data.methodName, err);
});
}
/*
* Clear the mercury values related to the input arguments.
*/
function initializeInputArguments(state) {
var param = getMethodData(state.interface(), state.methodName());
var startingArgs = [];
if (param.inArgs) {
startingArgs = _.range(param.inArgs.length).map(function() {
return ''; // Initialize array with empty string values using lodash.
});
}
setMercuryArray(state.args, startingArgs);
}
/*
* Returns a promise that refreshes the suggestions to the input arguments.
*/
function refreshInputSuggestions(state) {
var param = getMethodData(state.interface(), state.methodName());
var input = {
interface: state.interface(),
methodName: state.methodName(),
};
var inArgList = param.inArgs || [];
return Promise.all(
// For each argname, predict which inputs should be suggested.
inArgList.map(function(inArg, i) {
return smartService.predict(
'learner-method-input',
_.assign({argName: inArg.name}, input)
).then(function(inputSuggestion) {
state.inputSuggestions.put(i, inputSuggestion);
});
})
);
}
/*
* Returns a promise that loads starred invocations into the state.
*/
function loadStarredInvocations(state) {
return store.getValue(constructStarredInvocationKey(state)).then(
function(result) {
var invocations = result || [];
state.put('starred', mercury.array(invocations));
}
).catch(function(err) {
log.error('Unable to load starred invocations from store', err);
return Promise.reject(err);
});
}
/*
* Returns a promise that update the store with the invocations from the state.
*/
function saveStarredInvocations(state) {
return store.setValue(
constructStarredInvocationKey(state),
state.starred()
).catch(function(err) {
log.error('Unable to save starred invocations', err);
return Promise.reject(err);
});
}
/*
* Given an observed state, produce the storage key.
* The keys are of the form STARS|item|interface|method.
* The corresponding value is an array of invocations.
*/
var starsPrefix = 'STARS';
function constructStarredInvocationKey(state) {
var parts = [
starsPrefix,
state.itemName(),
hashInterface(state.interface()),
state.methodName()
];
return parts.join('|');
}
/*
* Returns a promise that refreshes the recommended values in the state.
*/
function refreshRecommendations(state) {
var input = {
interface: state.interface(),
methodName: state.methodName(),
};
return smartService.predict('learner-method-invocation', input).then(
function(recommendations) {
setMercuryArray(state.recommended, recommendations);
}
);
}
/*
* Wire up the events for the method form mercury component.
* Note: Some events are left for the parent component to hook up.
*/
function wireUpEvents(state, events) {
events.displayMethodForm(displayMethodForm.bind(null, state, events));
// The run action triggers a start event, RPC call, and end event.
events.runAction(function(data) {
// This random value allows us to uniquely identify this RPC.
var randomID = uuid.v4();
events.methodStart({
runID: randomID
});
// Toast that the RPC is being run.
events.toast({
text: 'Running ' + getMethodSignature(state(), data.args)
});
// Make the RPC, tracking when the method is in-progress or complete.
makeRPC(data).then(function success(result) {
events.methodEnd({
runID: randomID,
args: data.args,
result: result
});
}, function failure(error) {
events.methodEnd({
runID: randomID,
error: error
});
}).catch(function(err) {
log.error('Error handling makeRPC', err);
});
});
events.expandAction(function() {
state.expanded.set(!state.expanded());
});
events.starAction(function(data) {
// Load the user's stars (in case there were other changes).
loadStarredInvocations(state).then(function() {
// If there is no argsStr given, compute it now.
var argsStr = data.argsStr || JSON.stringify(state.args());
// Depending on the star boolean, add/remove a star for the given args.
arraySet.set(state.starred, argsStr, data.star);
// Save the user's star decision.
return saveStarredInvocations(state);
}).catch(function(err) {
events.toast({
text: 'Error while starring',
type: 'error'
});
log.error('Error while starring invocation', err);
});
});
// This event removes the specified recommendation.
// Afterwards, the recommendations are refreshed.
events.removeRecommendation(function(args) {
var input = {
interface: state.interface(),
methodName: state.methodName(),
value: JSON.stringify(args),
reset: true
};
smartService.update('learner-method-invocation', input).then(function() {
log.debug('Removing method invocation', input);
return refreshRecommendations(state);
}).then(function() {
return events.toast({
text: 'Removed suggestion: ' + getMethodSignature(state(), args),
type: 'info'
});
}).catch(function(err) {
var errText = 'Failed to remove suggestion';
log.error(errText, err);
events.toast({
text: errText,
type: 'error'
});
});
});
// This event removes the specified input suggestion for an argument.
// Afterwards, all input suggestions are refreshed.
events.removeInputSuggestion(function(data) {
var input = {
interface: state.interface(),
methodName: state.methodName(),
argName: data.argName,
value: data.arg,
reset: true
};
smartService.update('learner-method-input', input).then(function() {
log.debug('Removing method input', input);
return refreshInputSuggestions(state);
}).catch(function(err) {
var errText = 'Failed to remove suggestion';
log.error(errText, err);
events.toast({
text: errText,
type: 'error'
});
});
});
}
/*
* The main rendering function for the method form.
* Shows the method signature and a run button.
* If arguments are necessary, then they can be shown when the form is expanded.
*/
function render(state, events) {
// Display the method name/sig header with expand/collapse/run button.
var methodNameHeader = renderMethodHeader(state, events);
// Return immediately if we don't need arguments or haven't expanded.
if (state.args.length === 0 || !state.expanded) {
return makeMethodTooltip(state, h('div.method-input', methodNameHeader));
}
// Render the stars first, and if there's extra room, the recommendations.
// TODO(alexfandrianto): Show 1 of the pinned items even when not expanded?
var recs = renderStarsAndRecommendations(state, events);
// Form for filling up the arguments
var argForm = []; // contains form elements
for (var i = 0; i < state.args.length; i++) {
argForm.push(renderMethodInput(state, events, i));
}
// Setup the STAR and RUN buttons.
var starButton = renderStarUserInputButton(state, events);
var runButton = renderRPCRunButton(state, events);
var footer = h('div.method-input-expanded', [argForm, runButton, starButton]);
return makeMethodTooltip(state,
h('div.method-input', [methodNameHeader, recs, footer]));
}
/*
* Wrap the method form with a tooltip.
*/
function makeMethodTooltip(state, child) {
// The tooltip contains the documentation for the method name.
var methodSig = getMethodData(state.interface, state.methodName);
var tooltip = methodSig.doc || '<no description>';
// If the method takes input, add documentation about the input arguments.
if (methodSig.inArgs && methodSig.inArgs.length > 0) {
tooltip += '\n\nParameters';
methodSig.inArgs.forEach(function(inArg) {
tooltip += '\n';
tooltip += '- ' + inArg.name + ': ' + inArg.type.toString();
if (inArg.doc) {
tooltip += ' ' + inArg.doc;
}
});
}
// If the method returns output, add documentation about the output arguments.
if (methodSig.outArgs && methodSig.outArgs.length > 0) {
tooltip += '\n\nOutput';
methodSig.outArgs.forEach(function(outArg) {
tooltip += '\n';
tooltip += '- ' + outArg.name + ': ' + outArg.type.toString();
if (outArg.doc) {
tooltip += ' ' + outArg.doc;
}
});
}
// If the method has tags, show the tag types and values.
if (methodSig.tags && methodSig.tags.length > 0) {
tooltip += '\n\nTags';
methodSig.tags.forEach(function(tag) {
tooltip += '\n';
tooltip += '- ' + tag;
});
}
return h('core-tooltip.tooltip.method-tooltip', {
'label': tooltip,
'position': 'top'
}, child);
}
/*
* Draw the method header: A method signature and either a run or expand button.
*/
function renderMethodHeader(state, events) {
if (state.args.length === 0) {
return renderInvocation(state, events);
}
var labelText = getMethodSignature(state);
var label = makeMethodLabel(labelText);
var expand = h('a.drill', {
'href': 'javascript:;',
'title': state.expanded ? 'Hide form' : 'Show form',
'ev-click': mercury.event(events.expandAction)
}, h('core-icon.action-icon', {
attributes: {
'icon': state.expanded ? 'expand-more' : 'chevron-right'
}
}));
return h('div.item.card', [label, expand]);
}
/*
* Extracts a pretty-printed version of the method signature.
* If the method has no input args, print the name
* If the method does have input args, also show parentheses
* @args is an optional list whose elements are also printed out.
*/
function getMethodSignature(state, args) {
var methodName = state.methodName;
var param = getMethodData(state.interface, methodName);
var text = methodName;
var inArgList = param.inArgs || [];
var hasArgs = (inArgList.length > 0);
if (hasArgs) {
text += '(';
}
if (args !== undefined) {
for (var i = 0; i < inArgList.length; i++) {
if (i > 0) {
text += ', ';
}
text += args[i];
}
} else if (hasArgs) {
text += '...';
}
if (hasArgs) {
text += ')';
}
if (param.inStream || param.outStream) {
text += ' - streaming';
}
return text;
}
var SOFTCAP_INVOCATIONS = 3;
/*
* Renders the starred invocations followed by the recommended ones. Stars are
* shown with no limit. Recommendations are only shown if there is extra room.
*/
function renderStarsAndRecommendations(state, events) {
var s = state.starred.map(
function addStarred(invocation) {
return renderInvocation(state, events, invocation);
}
);
// Add the remaining recommenations, as long as they are not duplicates and
// don't exceed the soft cap on the # of invocations shown.
var remainingRecommendations = Math.min(
SOFTCAP_INVOCATIONS - s.length,
state.recommended.length
);
var count = 0;
state.recommended.forEach(function(rec) {
if (count < remainingRecommendations && state.starred.indexOf(rec) === -1) {
s.push(renderInvocation(state, events, rec, true));
count++;
}
});
return s;
}
/*
* Render the invocation, showing the method signature and a run button.
* argsStr is optional and is used for starred and recommended invocations.
* When given, then the card is smaller and has a star icon.
*/
function renderInvocation(state, events, argsStr, recommended) {
var noArgs = argsStr === undefined;
var args = noArgs ? [] : JSON.parse(argsStr);
var labelText = getMethodSignature(state, args);
var label = makeMethodLabel(labelText);
var runButton = h('a.drill', {
'href': 'javascript:;',
'title': 'Run ' + state.methodName,
'ev-click': getRunEvent(state, events, args)
}, renderPlayIcon());
if (noArgs) {
return h('div.item.card', [label, runButton]);
}
var starred = state.starred.indexOf(argsStr) !== -1;
var starButton = h('a.drill.star', {
'href': 'javascript:;',
'title': starred ? 'Forget Method Call' : 'Save Method Call',
'ev-click': mercury.event(events.starAction, {
argsStr: argsStr,
star: !starred
})
}, renderStarIcon(starred));
var negFeedback;
if (recommended) {
negFeedback = h('div.action-bar', h('paper-fab', {
attributes: {
'aria-label': 'Remove suggestion',
'title': 'Remove suggestion',
'icon': 'clear',
'mini': true
},
'ev-click': events.removeRecommendation.bind(null, args)
}));
}
return h('div.item.card.invocation',
[starButton, label, runButton, negFeedback]
);
}
/*
* Render a method label using labelText.
*/
function makeMethodLabel(labelText) {
return h('div.label', labelText);
}
/*
* Draws a single method argument input using the paper-autocomplete element.
* Includes a placeholder and suggestions from the internal state.
*/
function renderMethodInput(state, events, index) {
var methodName = state.methodName;
var inArg = getMethodData(state.interface, state.methodName).inArgs[index];
var argName = inArg.name;
var argTypeStr = inArg.type.name || inArg.type.toString();
var inputSuggestions = state.inputSuggestions[index];
var args = state.args;
// The children are the suggestions for this paper-autocomplete input.
var children = inputSuggestions.map(function(suggestion) {
return h('paper-item', {
attributes: {
// Attach as an attribute for later retrieval
'input-suggestion': suggestion
}
}, suggestion);
});
// Event used to update state when the value is changed.
var changeEvent = new PropertyValueEvent(function(data) {
log.debug(methodName, argName, 'value changed.', data);
args[index] = data;
}, 'value');
// TODO(alexfandrianto): It may be nice to link feedback between the
// method-input and method-invocation learners.
// Event used to remove an input suggestion.
var removeEvent = function(e) {
events.removeInputSuggestion({
argName: argName,
arg: e.target.getAttribute('input-suggestion')
});
};
// TODO(alexfandrianto): Note that Mercury and Polymer create a bug together.
// Polymer normally captures internal events and stops them from propagating.
// Unfortunately, Mercury reads and replays events using capturing mode.
// That means spurious 'change' and 'input' events may appear occasionally.
var elem = h('paper-autocomplete.method-input-item.autocomplete', {
'key': state.itemName, // Enforce element refresh when switching items
attributes: {
'label': argName + ' (' + argTypeStr + ')',
'value': args[index],
'spellcheck': 'false',
'maxItems': METHOD_INPUT_MAX_ITEMS
},
'ev-change': changeEvent,
'ev-delete-item': removeEvent
}, children);
return elem;
}
/*
* Draws the STAR button with the star event, which saves the user's input.
*/
function renderStarUserInputButton(state, events) {
var starButton = h(
'paper-button.secondary',
{
'href': 'javascript:;',
attributes: {
'raised': 'true'
},
'ev-click': mercury.event(events.starAction, {
star: true
})
},
[
renderStarIcon(false),
h('span', 'Save')
]
);
return starButton;
}
/*
* Draws the RUN button with the RPC run event with the user's input as args.
*/
function renderRPCRunButton(state, events) {
var runButton = h(
'paper-button',
{
'href': 'javascript:;',
attributes: {
'raised': 'true'
},
'ev-click': getRunEvent(state, events, state.args)
},
[
renderPlayIcon(),
h('span', 'Run')
]
);
return runButton;
}
/*
* The generic run event for making RPCs. In general, the arguments are taken
* from state.args, a starred invocation's arguments, or a recommendation's.
*/
function getRunEvent(state, events, args) {
var methodData = getMethodData(state.interface, state.methodName);
var outArgList = methodData.outArgs || [];
return mercury.event(events.runAction, {
name: state.itemName,
methodName: state.methodName,
args: args,
numOutArgs: outArgList.length
});
}
/*
* Render a star icon.
*/
function renderStarIcon(starred) {
return h('core-icon.action-icon' + (starred ? '.starred' : ''), {
attributes: {
'icon': starred ? 'star' : 'star-outline',
'alt': starred ? 'saved' : 'recommended'
}
});
}
/*
* Render a play icon.
*/
function renderPlayIcon() {
return h('core-icon..action-icon', {
attributes: {
'icon': 'av:play-circle-outline',
'alt': 'run'
}
});
}
},{"../../../../lib/array-set":217,"../../../../lib/log":223,"../../../../lib/mercury/property-value-event":228,"../../../../lib/mercury/set-mercury-array":229,"../../../../lib/store":232,"../../../../services/namespace/interface-util":245,"../../../../services/smart/service":251,"./make-rpc.js":162,"lodash":43,"mercury":45,"uuid":143}],162:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var namespaceService = require('../../../../services/namespace/service');
var log = require('../../../../lib/log')(
'components:browse:item-details:method-form:make-rpc'
);
module.exports = makeRPC;
/*
* Use the namespaceService to perform an RPC request, resolving with the result
* or rejecting with the error.
* data needs to have name, methodName, and args.
*/
function makeRPC(data) {
// TODO(alexfandrianto): Once JS signatures have type information and/or VOM
// gets better, we can be smarter about this.
// Parse if possible. Otherwise, a string (or invalid JSON) will be used.
// Solves a problem where booleans did not seem to be parsed properly.
var args = data.args.map(function(arg) {
arg = arg || ''; // 'undefined' input should be treated as ''.
try {
return JSON.parse(arg);
} catch(e) {
return arg;
}
});
return namespaceService.makeRPC(
data.name, data.methodName, args, data.numOutArgs).catch(function(err) {
log.error('Error during RPC',
data.name,
data.methodName,
err, (err && err.stack) ? err.stack : undefined
);
return Promise.reject(err);
}
);
}
},{"../../../../lib/log":223,"../../../../services/namespace/service":248}],163:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var namespaceService = require('../../../../services/namespace/service');
var log = require('../../../../lib/log')(
'components:browse:item-details:mount-point:display-mountpoint-details'
);
module.exports = displayMountPointDetails;
// Holds name of the last requested name.
var lastRequestedName;
/*
* Loads all the information needed to render the mount point details page.
*/
function displayMountPointDetails(state, events, data) {
var itemObs = data.itemObs;
var name = itemObs().objectName;
lastRequestedName = name;
state.put('item', itemObs);
state.put('itemName', name);
state.put('error', null);
state.put('showLoadingIndicator', false);
state.put('notAuthorizedToSeePermissions', false);
state.put('objectAddresses', '');
// Whether we have finished loading yet.
var isLoaded = false;
// How long to wait before showing loading if things have not loaded yet
var SHOW_LOADING_THRESHOLD = 250;
setTimeout(function maybeShowLoadingIndicator() {
if (isLoaded || !isCurrentlySelected()) {
return;
}
state.put('showLoadingIndicator', true);
}, SHOW_LOADING_THRESHOLD);
var allPromises = Promise.all([
loadPermissions(),
resolveToMounttable()
]);
return allPromises.then(function() {
// Indicate we finished loading
setIsLoaded();
}).catch(function(err) {
log.error('Error while getting mount point details for', name, err);
if (!isCurrentlySelected()) {
return;
}
events.toast({
text: 'Error while getting mount point details for:' + name,
type: 'error'
});
state.put('error', err);
setIsLoaded();
});
function loadPermissions() {
// Protect this call; this must be the selected item.
if (!isCurrentlySelected()) {
return;
}
return namespaceService.getPermissions(name).then(function(permissions) {
if (permissions) {
state.put('permissions', permissions);
}
}).catch(function(err) {
// TODO(alexfandrianto): We don't have access to VErrors, so this is the
// closest we can get to determining "notAuthorizedToSeePermissions".
if (err.toString().contains('NoAccess')) {
state.put('notAuthorizedToSeePermissions', true);
}
log.error('Failed to get mountpoint permissions for:', name, err);
state.put('permissions', null);
});
}
function resolveToMounttable() {
// Protect this call; this must be the selected item.
if (!isCurrentlySelected()) {
return;
}
return namespaceService.resolveToMounttable(name).then(function(eps) {
state.put('objectAddresses', eps);
}).catch(function(err) {
log.error('Failed to resolve to mounttable for:', name, err);
state.put('parentMounttable', '');
state.put('suffix', '');
});
}
/*
* Indicates the current request has finished loading
*/
function setIsLoaded() {
isLoaded = true;
state.put('showLoadingIndicator', false);
}
/*
* Returns whether we are still the currently selected item or not
*/
function isCurrentlySelected() {
return (name === lastRequestedName);
}
}
},{"../../../../lib/log":223,"../../../../services/namespace/service":248}],164:[function(require,module,exports){
module.exports = ":root{}:root{}.permission-item .permission-name{font-size:0.9em;}.permission-item .permission-in,.permission-item .permission-out{white-space:nowrap;color:#00838F;padding-left:0.5em;}.permission-item ul{padding-left:0.75em;}.permission-item ul li{padding-bottom:0.5em;}.permissions-wrapper{display:flex;flex-direction:row;}"
},{}],165:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var displayMountPointDetails = require('./display-mountpoint-details');
var mountPointManager = require('./manage-mountpoint');
var dialogClickHook = require('../../../../lib/mercury/dialog-click-hook');
var FieldItem = require('../field-item');
var ErrorBox = require('../../../error/error-box');
var log = require('../../../../lib/log')(
'components:browse:item-details:mount-point'
);
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
module.exports.displayMountPointDetails = displayMountPointDetails;
/*
* MountPointDetails component provides user interfaces for displaying
* details about a mount point such the permissions, its parent mounttable
* and the full name of the mount point.
* TODO(aghassemi) Add UI for manipulating the mountpoint such as mount,
* unmount, setPermissions, etc..
*/
function create() {
var state = mercury.varhash({
/*
* namespace item to display mount point details for.
* @see services/namespace/item
* @type {namespaceitem}
*/
item: mercury.value(null),
/*
* Name of the item.
* @type {string}
*/
itemName: mercury.value(''),
/*
* Any fatal error while getting the mount point details.
* Note: will be displayed to user.
* @type Error
*/
error: mercury.value(null),
/*
* Whether a loading indicator should be displayed instead of content
* @type {mercury.value<boolean>}
*/
showLoadingIndicator: mercury.value(false),
/*
* Map of permissions for the mount point.
* @type {map<string,vanadium.security.Permissions>}
*/
permissions: mercury.value(null),
/*
* Whether user is even authorized to see the permission for the mount point
* @type {boolean}
*/
notAuthorizedToSeePermissions: mercury.value(false),
/*
* The objectAddresses as resolveToMounttable
* @type {mercury.array<string>}
*/
objectAddresses: mercury.array([]),
/*
* Whether we should render a dialog prompting for an action.
* @type {boolean}
*/
promptAction: mercury.value(false),
/*
* The text for the prompt.
* @type {string}
*/
promptActionText: mercury.value(''),
/*
* The text for the positive button of the prompt.
* @type {string}
*/
promptActionButtonText: mercury.value(''),
/*
* The event handler that will be called when confirmed.
* @type {function}
*/
promptActionCallback: mercury.value()
});
var events = mercury.input([
'toast',
'promptDeleteMountPoint',
'promptCanceled',
'promptConfirmed'
]);
wireUpEvents(state, events);
return {
state: state,
events: events
};
}
/*
* Render the mount point details page.
*/
function render(state, events, browseState, navEvents) {
insertCss(css);
var content = [];
// Details can only be shown if there is an item.
if (state.item) {
var displayItems = [];
displayItems.push(renderNameField(state));
displayItems.push(renderObjectAddressesField(state));
displayItems.push(renderPermissionsField(state));
displayItems.push(renderActionsField(state, events, navEvents));
content.push(h('div', displayItems));
}
// Show any errors from getting the details
if (state.error) {
var errorTitle = 'Unable to connect to ' + state.itemName;
content.push(ErrorBox.render(errorTitle, state.error.toString()));
}
// Show the loading indicator if it's available.
if (state.showLoadingIndicator) {
content.push(h('paper-spinner', {
attributes: {
'active': true,
'aria-label': 'Loading'
}
}));
}
return content;
}
/*
* Renders the Full Name field
*/
function renderNameField(state) {
return FieldItem.render('Full Name', (state.itemName || '<Home>'));
}
/*
* Renders the ObjectAddresses field which should be the objectAddresses at the
* parent mount table (i.e. result of call to resolveToMounttable())
*/
function renderObjectAddressesField(state) {
return FieldItem.render(
'Mount Point Object Addresses', (state.objectAddresses), {
contentTooltip: 'Object addresses at the parent mount table'
});
}
/*
* Renders the permissions field
*/
function renderPermissionsField(state) {
var content;
if (state.notAuthorizedToSeePermissions) {
content = h('span', 'Not authorized to see the permissions');
} else if (state.permissions && state.permissions.size > 0) {
content = formatPermissions(state.permissions);
} else if (state.permissions) {
content = h('span', 'No specific permissions set');
}
return FieldItem.render('Permissions', content);
}
/*
* Renders the mountpoint actions.
*/
function renderActionsField(state, events, navEvents) {
var actions = [
renderDeleteAction(state, events, navEvents)
];
var filteredActions = actions.filter(function(a) {
return !!a;
});
if (filteredActions.length === 0) {
return;
}
return [
FieldItem.render('Manage', h('div', filteredActions)),
renderPrompt(state, events)
];
}
/*
* Renders a modal prompt dialog if an action is taking place to confirm.
*/
function renderPrompt(state, events) {
return h('paper-action-dialog', {
attributes: {
'autoCloseDisabled': true,
'layered': true,
'backdrop': true,
},
'opened': state.promptAction
}, [
h('p', state.promptActionText),
h('paper-button', {
attributes: {
'dismissive': true,
},
'click-hook': dialogClickHook(mercury.send(events.promptCanceled))
}, 'Cancel'),
h('paper-button', {
attributes: {
'affirmative': true,
'autofocus': true
},
'click-hook': dialogClickHook(mercury.send(events.promptConfirmed))
}, state.promptActionButtonText)
]);
}
/*
* Renders the mountpoint delete action.
*/
function renderDeleteAction(state, events, navEvents) {
/* TODO(aghassemi) We really should only render items user has access to.
* This was attempted by trying to match remoteBlessings with peerBlessings
* but we intentionally do not expose blessing names for peerBlessings so
* approach did not work.
* This needs https://github.com/vanadium/issues/issues/210 to be fixed first.
*/
var action = h('paper-button', {
'ev-click': mercury.send(events.promptDeleteMountPoint, {
cb: navEvents.reload,
name: state.itemName
})
}, 'Delete');
return action;
}
/*
* Formats a permissions object to string
* TODO(aghassemi): we need a nicer permission formatter
* @param {vanadium.security.Permissions} perms
*/
function formatPermissions(perms) {
var results = [];
perms.forEach(function(p, key) {
results.push(
h('div.permission-item', [
h('div.permission-name', key),
h('div', formatPermission(p))
])
);
});
return h('div', results);
}
/*
* Formats a single permission object to string
* @param {vanadium.security.AccessList} perm
*/
function formatPermission(perm) {
var results = [];
if (perm.in && perm.in.length > 0) {
results.push(
h('div.permissions-wrapper', [
h('span.permission-in', 'In: '),
renderBlessingsList(perm.in)
])
);
}
if (perm.notIn && perm.notIn.length > 0) {
results.push(
h('div', [
h('span.permission-out', 'Not In: '),
renderBlessingsList(perm.notIn)
])
);
}
function renderBlessingsList(list) {
var items = list.map(function(item) {
return h('li', item);
});
return h('ul', items);
}
return h('div', results);
}
// Wire up events that we know how to handle
function wireUpEvents(state, events) {
events.promptDeleteMountPoint(function(data) {
state.promptAction.set(true);
state.promptActionText.set(
'Are you sure you want to delete ' + data.name + ' ?'
);
state.promptActionButtonText.set('Delete');
state.promptActionCallback.set(deleteMountPoint.bind(null, data));
});
events.promptCanceled(function() {
state.promptAction.set(false);
});
events.promptConfirmed(function() {
var cb = state.promptActionCallback();
cb();
state.promptAction.set(false);
});
function deleteMountPoint(data) {
mountPointManager.deleteMountPoint(state, events).then(function() {
if (data.cb) {
data.cb();
}
}, function(err) {
log.error('Could not delete mount point', err);
});
}
}
},{"../../../../lib/log":223,"../../../../lib/mercury/dialog-click-hook":225,"../../../error/error-box":191,"../field-item":158,"./display-mountpoint-details":163,"./index.css":164,"./manage-mountpoint":166,"insert-css":37,"mercury":45}],166:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var namespaceService = require('../../../../services/namespace/service');
var log = require('../../../../lib/log')(
'components:browse:item-details:mount-point:manage-mountpoint'
);
module.exports = {
deleteMountPoint: deleteMountPoint
};
/*
* Delete a given mountpoint
*/
//TODO(aghassemi) Prompt for confirmation
function deleteMountPoint(state, events) {
var name = state.itemName;
return namespaceService.deleteMountPoint(name).then(function() {
events.toast({
text: name + ' deleted successfully'
});
}).catch(function(err) {
var errText = 'Could not delete ' + name;
if (err && err.id === 'v.io/v23/verror.NoAccess') {
errText = 'Not authorized to delete ' + name;
}
log.error(errText, name, err);
events.toast({
text: errText,
type: 'error'
});
return Promise.reject(err);
});
}
},{"../../../../lib/log":223,"../../../../services/namespace/service":248}],167:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = PluginWidgetAdapter;
// Map of plugin.id to previous names. This map allows up to
// only call render when name changes.
var previousNames = {};
// Map of plugin.id to the rendered node for the latest name.
var renderedNodes = {};
/*
* Adapts a plugin into a mercury widget
*/
function PluginWidgetAdapter(name, plugin) {
this.name = name;
this.plugin = plugin;
}
PluginWidgetAdapter.prototype.type = 'Widget';
PluginWidgetAdapter.prototype.init = function() {
this.render();
// wrap in a new element, needed for Mercury vdom to patch properly.
var wrapper = document.createElement('div');
wrapper.appendChild(renderedNodes[this.plugin.id]);
return wrapper;
};
PluginWidgetAdapter.prototype.update = function() {};
PluginWidgetAdapter.prototype.render = function() {
// do not rerender if name has not changed
if (previousNames[this.plugin.id] === this.name &&
renderedNodes[this.plugin.id]) {
return;
}
previousNames[this.plugin.id] = this.name;
// render and cache the DOM
renderedNodes[this.plugin.id] = this.plugin.render(this.name);
};
},{}],168:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var methodNameToVarHashKey = require('./methodNameToVarHashKey');
var methodStart = require('./method-start.js');
var methodEnd = require('./method-end.js');
var methodForm = require('../method-form/index.js');
var namespaceService = require('../../../../services/namespace/service');
var log = require('../../../../lib/log')(
'components:browse:item-details:server:display-server-details'
);
module.exports = displayServerDetails;
// Holds name of the last requested name.
var lastRequestedName;
/*
* Loads all the information needed to render the server details page.
*/
function displayServerDetails(state, events, data) {
var itemObs = data.itemObs;
var name = itemObs().objectName;
// Return if we are already on that item.
if (isCurrentlySelected()) {
return;
}
lastRequestedName = name;
state.put('item', itemObs);
state.put('itemName', name);
state.put('error', null);
state.put('signature', null);
state.put('remoteBlessings', null);
state.put('objectAddresses', null);
state.put('showLoadingIndicator', false);
// Whether we have finished loading yet.
var isLoaded = false;
// How long to wait before showing loading if things have not loaded yet
var SHOW_LOADING_THRESHOLD = 250;
setTimeout(function maybeShowLoadingIndicator() {
if (isLoaded || !isCurrentlySelected()) {
return;
}
state.put('showLoadingIndicator', true);
}, SHOW_LOADING_THRESHOLD);
var allPromises = Promise.all([
loadRemoteBlessings(itemObs()),
loadObjectAddresses(itemObs()),
loadSignature(itemObs())
]);
return allPromises.then(function() {
// Indicate we finished loading
setIsLoaded();
}).catch(function(err) {
log.error('Error while getting server details for', name, err);
if (!isCurrentlySelected()) {
return;
}
events.toast({
text: 'Error while getting server details for:' + name,
type: 'error'
});
state.put('error', err);
setIsLoaded();
});
function loadRemoteBlessings(item) {
if (!item.hasServer) {
return;
}
return namespaceService.getRemoteBlessings(name).then(function(rbs) {
// Protect this call; this must be the selected item.
if (!isCurrentlySelected()) {
return;
}
state.put('remoteBlessings', rbs);
});
}
function loadObjectAddresses(item) {
if (!item.hasServer) {
return;
}
return namespaceService.getObjectAddresses(name).then(function(eps) {
// Protect this call; this must be the selected item.
if (!isCurrentlySelected()) {
return;
}
state.put('objectAddresses', eps);
});
}
function loadSignature(item) {
if (!item.hasServer) {
return;
}
return namespaceService.getSignature(name).then(function(signatureResult) {
// Protect this call; this must be the selected item.
if (!isCurrentlySelected()) {
return;
}
state.put('signature', signatureResult);
if (!signatureResult) {
return;
}
// Go through each signature method from each interface. Prepare the state
// needed for the form to be rendered and its events to function.
signatureResult.forEach(function(interface, i) {
var forms = mercury.varhash();
var formEvents = mercury.varhash();
interface.methods.forEach(function(methodData) {
var methodName = methodData.name;
var methodKey = methodNameToVarHashKey(methodName);
var form = methodForm();
forms.put(methodKey, form.state);
formEvents.put(methodKey, form.events);
// Hook up the new form's method start, end, and toast events.
form.events.methodStart(
methodStart.bind(null, state, methodName)
);
form.events.methodEnd(
methodEnd.bind(null, state, methodName, interface)
);
form.events.toast = events.toast;
// Finally, allow the form to gather the info it needs to display.
form.events.displayMethodForm({
itemName: name,
interface: interface,
methodName: methodName
});
});
// Save the method forms, events, open-status of each interface.
// Note: Some services have more interfaces than others. If a service
// has fewer than usual, it won't override/delete any extra interfaces.
// It isn't necessary because those old interfaces won't be rendered.
state.methodForms.put(i, forms);
events.methodForms[i] = formEvents;
// Note: We want the __Reserved interface to be closed by default.
// It has a common pool of methods that would be distracting in the UI.
state.methodFormsOpen.put(i, interface.name !== '__Reserved');
});
});
}
/*
* Indicates the current request has finished loading
*/
function setIsLoaded() {
isLoaded = true;
state.put('showLoadingIndicator', false);
}
/*
* Returns whether we are still the currently selected item or not
*/
function isCurrentlySelected() {
return (name === lastRequestedName);
}
}
},{"../../../../lib/log":223,"../../../../services/namespace/service":248,"../method-form/index.js":161,"./method-end.js":172,"./method-start.js":173,"./methodNameToVarHashKey":174,"mercury":45}],169:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var log = require('../../../../lib/log')(
'components:browse:item-details:format-detail');
/*
* The plugins listed here are listed in order with highest priority first.
* Plugins must export functions shouldFormat(input) and format(input).
* The default plugin should always be last.
*/
var plugins = [
require('./output-plugins/empty.js'),
require('./output-plugins/error.js'),
require('./output-plugins/histogram.js'),
require('./output-plugins/default.js')
];
module.exports = formatDetail;
/*
* Transforms the input into the desired detail output.
* Various plugins are tested until the correct one is found.
* With the default plugin, this should always return something.
*/
function formatDetail(input) {
for (var i = 0; i < plugins.length; i++) {
if (plugins[i].shouldFormat(input)) {
return plugins[i].format(input);
}
}
log.error('No plugins rendered the detail', input);
}
},{"../../../../lib/log":223,"./output-plugins/default.js":175,"./output-plugins/empty.js":176,"./output-plugins/error.js":177,"./output-plugins/histogram.js":178}],170:[function(require,module,exports){
module.exports = ""
},{}],171:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var methodNameToVarHashKey = require('./methodNameToVarHashKey');
var displayServerDetails = require('./display-server-details');
var methodForm = require('../method-form');
var FieldItem = require('../field-item');
var ErrorBox = require('../../../error/error-box');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
module.exports.displayServerDetails = displayServerDetails;
/*
* ServerDetails component provides user interfaces for displaying details for
* a server such is its objectAddresses, signature, remote blessings, etc..
*/
function create() {
var state = mercury.varhash({
/*
* namespace item to display details for.
* @see services/namespace/item
* @type {namespaceitem}
*/
item: mercury.value(null),
/*
* Name of the item.
* @type {string}
*/
itemName: mercury.value(''),
/*
* Any fatal error while getting the details.
* Note: will be displayed to user.
* @type Error
*/
error: mercury.value(null),
/*
* remoteBlessings for the item. []string
* @type {[]string}
*/
remoteBlessings: mercury.value(null),
/*
* signature for the item. []interface
* @see services/namespace/interface-util
* @type {vanadium.vdl.signature}
*/
signature: mercury.value(null),
/*
* An associative array from item names to method outputs.
* The outputs are in RPC call-order and store render information.
* @type {map[string]Array<Object>}
*/
methodOutputs: mercury.varhash(),
/*
* Each method form corresponds to an interface in the signature. It is a
* map from method names to the relevant state used in the method-form
* component.
* @type {[]map[string]mercury.struct}
*/
methodForms: mercury.array([]),
/*
* Each method form could be open or closed. All start out open, except
* for __Reserved, which is explicitly set to closed.
* @type {[]boolean}
*/
methodFormsOpen: mercury.array([]),
/*
* Whether a loading indicator should be displayed instead of content
* @type {mercury.value<boolean>}
*/
showLoadingIndicator: mercury.value(false),
/*
* Whether item is bookmarked
* @type {mercury.value<boolean>}
*/
isBookmarked: mercury.value(false),
/*
* List of objectAddresses for the name.
* @type {mercury.array<string>}
*/
objectAddresses: mercury.array([])
});
var events = mercury.input([
'methodForms',
'toggleMethodForm',
'toast'
]);
wireUpEvents(state, events);
// events.methodForms is []events; the index order matches state.methodForms
// and state.methodFormsOpen.
events.methodForms = [];
return {
state: state,
events: events
};
}
/*
* Render the server details page.
*/
function render(state, events, browseState, navEvents) {
insertCss(css);
var content = [];
// Details can only be shown if there is an item.
if (state.item) {
var detailsContent = renderDetailsContent(state, events);
content.push(detailsContent);
}
// The method forms can only be shown under these conditions.
if (state.item && state.item.hasServer && state.signature) {
var methodsContent = renderMethodsContent(state, events);
content.push(methodsContent);
}
// Show any errors from getting the details
if (state.error) {
var errorTitle = 'Unable to connect to ' + state.itemName;
content.push(ErrorBox.render(errorTitle, state.error.toString()));
}
// Show the loading indicator if it's available.
if (state.showLoadingIndicator) {
content.push(h('paper-spinner', {
attributes: {
'active': true,
'aria-label': 'Loading'
}
}));
}
return content;
}
/*
* Renders details about the current service object.
* Assumes that there is a state.item
* Note: Currently renders in the same tab as renderMethodsContent.
*/
function renderDetailsContent(state, events) {
var displayItems = [
renderNameField(state)
];
if (state.item.hasServer) {
displayItems.push(renderObjectAddressesFieldItem(state));
if (state.remoteBlessings) {
displayItems.push(renderRemoteBlessingsFieldItem(state));
}
}
return [
h('div', displayItems)
];
}
/*
* Renders the ObjectAddresses Field Item, a simple listing of the server's
* objectAddresses.
*/
function renderObjectAddressesFieldItem(state) {
var objectAddressDivs;
if (!state.objectAddresses || state.objectAddresses.length === 0) {
objectAddressDivs = [
h('div', h('span', 'No Object Addresses Found'))
];
} else {
// Show 1 div per server objectAddress.
objectAddressDivs = state.objectAddresses.map(function(objectAddress) {
return h('div', h('span', objectAddress));
});
}
return FieldItem.render('Service Object Addresses', h('div', {
attributes: {
'vertical': true,
'layout': true
}
}, objectAddressDivs));
}
/*
* Renders the Full Name field
*/
function renderNameField(state) {
return FieldItem.render('Full Name', (state.itemName || '<Home>'));
}
/*
* Renders the Remote Blessings Field Item, a list of the server's blessings.
* Does not appear until the data has been fetched.
*/
function renderRemoteBlessingsFieldItem(state) {
var remoteBlessings = state.remoteBlessings;
var blessingDivs;
if (remoteBlessings.length === 0) {
blessingDivs = [
h('div', h('span', 'No blessings found'))
];
} else {
// Show 1 div per blessing.
blessingDivs = remoteBlessings.map(function(blessing) {
return h('div', h('span', blessing));
});
}
return FieldItem.render('Remote Blessings', h('div', {
attributes: {
'vertical': true,
'layout': true
}
}, blessingDivs));
}
/*
* Renders the method signature forms and the RPC output area.
* Does not appear until the data has been fetched.
*/
function renderMethodsContent(state, events) {
var sig = state.signature;
if (!sig || sig.size === 0) {
return FieldItem.render('Methods',
h('div', h('span', 'No method signature')));
}
// Render each interface and an output region.
var content = state.signature.map(function(interface, interfaceIndex) {
var label = interface.pkgPath + '.' + interface.name;
var content;
var open = state.methodFormsOpen[interfaceIndex];
var options = {
labelTooltip: interface.doc,
collapsed: !open,
callback: events.toggleMethodForm.bind(null, {
index: interfaceIndex,
value: !open
})
};
if (!open) {
content = h('span');
} else {
content = renderMethodInterface(state, events, interfaceIndex);
}
return FieldItem.render(label, content, options);
});
content.push(FieldItem.render('Output', renderMethodOutput(state)));
return h('div', content);
}
/*
* Renders each method signature belonging to one of the interfaces of the
* service. Each form allows RPCs to be made to the associated service.
*/
function renderMethodInterface(state, events, interfaceIndex) {
var methods = [];
// Render all the methods in alphabetical order.
// ES6 Map iterates in the order values were added, so we must sort them.
var methodNames = [];
state.signature[interfaceIndex].methods.forEach(
function(methodData) {
methodNames.push(methodData.name);
}
);
methodNames.sort().forEach(function(methodName) {
var methodKey = methodNameToVarHashKey(methodName);
methods.push(methodForm.render(
state.methodForms[interfaceIndex][methodKey],
events.methodForms[interfaceIndex][methodKey]
));
});
return h('div', methods); // Note: allows 0 method signatures
}
/*
* Renders the method outputs received by the current service object.
* Prints each output received in reverse order; most recent is on top.
*/
function renderMethodOutput(state) {
var outputs = state.methodOutputs[state.item.objectName];
if (outputs === undefined) {
return h('div.method-output', h('span', 'No method output'));
}
var outputRows = [h('tr', [
h('th', '#'),
h('th', 'Method'),
h('th', 'Output')
])];
for (var i = outputs.length - 1; i >= 0; i--) {
var output = outputs[i];
if (output.shouldShow) {
outputRows.push(
h('tr', [
h('td', {
'scope': 'row'
}, '' + (i + 1)),
h('td', h('pre', output.method)),
h('td', h('pre', output.result))
])
);
}
}
var outputTable = h('table', {
attributes: {
'summary': 'Table showing the outputs of methods run on' +
'the service. The results are shown in reverse order.'
}
}, outputRows);
return h('div.method-output', outputTable);
}
// Wire up events that we know how to handle
function wireUpEvents(state, events) {
events.toggleMethodForm(function(data) {
state.methodFormsOpen.put(data.index, data.value);
});
}
},{"../../../error/error-box":191,"../field-item":158,"../method-form":161,"./display-server-details":168,"./index.css":170,"./methodNameToVarHashKey":174,"insert-css":37,"mercury":45}],172:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var formatDetail = require('./format-detail');
var smartService = require('../../../../services/smart/service');
var getMethodData =
require('../../../../services/namespace/interface-util').getMethodData;
var log = require('../../../../lib/log')(
'components:browse:item-details:method-end');
var h = require('mercury').h;
module.exports = methodEnd;
/*
* Use the data from a successful/failed RPC to record the results properly.
* Note that the recorded results are rendered according to formatDetail.
* Successful RPCs also update the smartService.
* data needs to have runID and either (error) or (result and args)
*/
function methodEnd(state, method, interface, data) {
// Simply draw the error message if there was an error.
if (data.error !== undefined) {
formatResult(state, method, data.runID, data.error, false);
return;
}
// Otherwise, we'll have to learn from the results and draw them, if possible.
var params = getMethodData(interface, method);
var numInArgs = params.inArgs.length;
// Since the RPC was successful, we can assume the inputs were good.
if (numInArgs > 0) {
learnMethodInput(method, interface, data.args);
learnMethodInvocation(method, interface, data.args);
}
// Do not process results we expect to be empty. Instead, indicate that the
// RPC terminated successfully.
// TODO(alexfandrianto): Streaming results are ignored with this logic.
var expectedOutArgs = params.outArgs.length;
if (expectedOutArgs === 0) {
replaceResult(state, data.runID, h('span', '<ok>'));
return;
}
// Draw the results.
formatResult(state, method, data.runID, data.result);
}
/*
* The result will be rendered, overwriting the placeholder identified by runID.
*/
function formatResult(state, method, runID, result) {
// Use formatDetail to process the raw result into a renderable format.
var formattedResult = formatDetail(result);
// Then overwrite the old value.
replaceResult(state, runID, formattedResult);
}
/*
* Find the correct output replacement mercury struct and replace its result.
* If the replacement cannot be found, then no substitution occurs.
*/
function replaceResult(state, runID, newResult) {
var match = state.methodOutputs.get(state.item().objectName).filter(
function matchesRunID(output) {
return output.get('runID') === runID;
}
).get(0);
if (match !== undefined) {
match.put('result', newResult);
}
}
/*
* Learn from the method inputs to be able to suggest them in the future.
*/
function learnMethodInput(method, interface, args) {
args.forEach(function(value, i) {
var argName = getMethodData(interface, method).inArgs[i].name;
var input = {
argName: argName,
methodName: method,
interface: interface,
value: args[i]
};
log.debug('Update Input:', input);
smartService.update('learner-method-input', input).catch(function(err) {
log.error('Error while updating method input learner', err);
});
});
}
/*
* Learn from this invocation to be able to suggest them in the future.
*/
function learnMethodInvocation(method, interface, args) {
var input = {
methodName: method,
interface: interface,
value: JSON.stringify(args)
};
log.debug('Update Invocation:', input);
smartService.update('learner-method-invocation', input).catch(function(err) {
log.error('Error while updating method invocation learner', err);
});
}
},{"../../../../lib/log":223,"../../../../services/namespace/interface-util":245,"../../../../services/smart/service":251,"./format-detail":169,"mercury":45}],173:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var h = require('mercury').h;
module.exports = methodStart;
/*
* Indicate that the method is in-progress by appending to the method outputs.
* data needs to have runID.
*/
function methodStart(state, method, data) {
// TODO(alexfandrianto): Instead of now displaying for 25 ms, consider
// showing a loading icon right away. The result can be revealed when it
// arrives, or after ~200 ms.
var output = mercury.varhash({
runID: data.runID,
shouldShow: false,
method: method,
result: h('span', '<running>')
});
setTimeout(function() {
output.put('shouldShow', true); // prevent flicker for near-instant RPCs.
}, 25);
var itemName = state.item().objectName;
var outputs = state.methodOutputs.get(itemName);
if (outputs === undefined) {
state.methodOutputs.put(itemName, mercury.array([output]));
} else {
outputs.push(output);
}
}
},{"mercury":45}],174:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* Mercury VarHash has an issue where reserved keywords like 'delete', 'put'
* can not be used a hash keys :`(
* https://github.com/nrw/observ-varhash/issues/2
* Since signature methods names can be anything (specially something like
* delete is very likely), we need to prefix them.
*/
module.exports = function methodNameToVarHashKey(methodName) {
return 'method_' + methodName;
};
},{}],175:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var h = require('mercury').h;
module.exports = {
'shouldFormat': shouldFormat,
'format': format
};
/*
* By default, always format.
*/
function shouldFormat(input) {
return true;
}
/*
* By default, the input is returned as prettified JSON.
*/
function format(input) {
return h('span', JSON.stringify(input, null, 2));
}
},{"mercury":45}],176:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var h = require('mercury').h;
module.exports = {
'shouldFormat': shouldFormat,
'format': format
};
/*
* The input is empty in various cases.
*/
function shouldFormat(input) {
return input === undefined || input === null || input === '' ||
(input instanceof Array && input.length === 0);
}
/*
* Indicate that nothing was there.
*/
function format(input) {
return h('span', '<no data>');
}
},{"mercury":45}],177:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var h = require('mercury').h;
module.exports = {
'shouldFormat': shouldFormat,
'format': format
};
/*
* Only format if this is an Error
*/
function shouldFormat(input) {
return input instanceof Error;
}
/*
* Print the error with a dangerous-looking icon.
*/
function format(input) {
var error;
if (input.message) {
error = input.message;
} else {
error = input.toString();
}
return h('div', [
h('core-icon.error', {
attributes: {
'icon': 'error'
}
}),
h('pre', error)
]);
}
},{"mercury":45}],178:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var h = require('mercury').h;
var histogram = require('bars');
module.exports = {
'shouldFormat': shouldFormat,
'format': format
};
/*
* Format if the appropriate histogram fields are present.
* TODO(alexfandrianto): Negotiate a better way of identifying histogram data.
*/
function shouldFormat(input) {
return input.count !== undefined && input.sum !== undefined &&
input.buckets !== undefined;
}
/*
* The histogram is formatted with bars (a fork of ascii-histogram).
* TODO(alexfandrianto): Consider using a prettier formatting package.
*/
function format(input) {
var histData = {};
input.buckets.forEach(function(obj) {
histData[obj.lowBound] = obj.count;
});
return h('span', histogram(histData, { bar: '*', width: 20 }));
}
},{"bars":1,"mercury":45}],179:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var ItemCardList = require('../item-card-list/index');
var recommendationsService =
require('../../../services/recommendations/service');
var log = require('../../../lib/log')('components:browse:recommendation');
module.exports = create;
module.exports.render = render;
module.exports.load = load;
/*
* Recommendation view
*/
function create() {
var state = mercury.varhash({
/*
* List of recommended shortcuts to display
* @see services/namespace/item
* @type {Array<namespaceitem>}
*/
recShortcuts: mercury.array([])
});
return {
state: state
};
}
function render(state, browseState, browseEvents, navEvents) {
// An event used to reduce a recommendation score to 0, or to recover it.
var modifyRecommendation = function(score, objectName) {
recommendationsService.setRecommendationScore(objectName, score).then(
function(oldScore) {
var desc = (oldScore === 0 ? 'Restored ' : 'Forgot ');
browseEvents.toast({
text: desc + ' recent item ' + objectName,
action: modifyRecommendation.bind(null, oldScore, objectName),
actionText: 'UNDO'
});
}
).catch(function(err) {
var errText = 'Failed to forget recent item ' + objectName;
log.error(errText, err);
browseEvents.toast({
text: errText,
type: 'error'
});
});
};
return ItemCardList.render(
state.recShortcuts,
browseState,
browseEvents,
navEvents, {
title: 'Recent',
emptyText: 'No recently accessed items.',
showShortName: false,
hoverActionInfo: {
icon: 'clear',
description: 'Forget recent item',
action: modifyRecommendation.bind(null, 0)
}
}
);
}
/*
* Does the initialization and loading of the data necessary to display the
* recommendations.
* Called and used by the parent browse view to initialize the view on
* request.
* Returns a promise that will be resolved when loading is finished. Promise
* is used by the parent browse view to display a loading progressbar.
*/
function load(state) {
return new Promise(function(resolve, reject) {
recommendationsService.getAll()
.then(function recReceived(items) {
state.put('recShortcuts', items);
items.events.once('end', resolve);
}).catch(function(err) {
log.error(err);
reject();
});
});
}
},{"../../../lib/log":223,"../../../services/recommendations/service":249,"../item-card-list/index":152,"mercury":45}],180:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var namespaceUtil = require('../../../../services/namespace/service').util;
var ItemCardList = require('../../item-card-list/index');
module.exports = create;
module.exports.render = render;
function create() {}
function render(viewsState, browseState, browseEvents, navEvents) {
var isSearch = !!browseState.globQuery;
var emptyText = (isSearch ? 'No glob search results' : 'No visible children');
var title;
if (isSearch) {
title = 'Glob Search Results';
} else {
var mountedName = namespaceUtil.basename(browseState.namespace) || 'Home';
title = mountedName;
}
return ItemCardList.render(
viewsState.items,
browseState,
browseEvents,
navEvents, {
title: title,
emptyText: emptyText,
showShortName: true
}
);
}
},{"../../../../services/namespace/service":248,"../../item-card-list/index":152}],181:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var uuid = require('uuid');
var GridView = require('./grid-view/index');
var TreeView = require('./tree-view/index');
var VisualizeView = require('./visualize-view/index');
var namespaceService = require('../../../services/namespace/service');
var stateService = require('../../../services/state/service');
var log = require('../../../lib/log')('components:browse:items');
module.exports = create;
module.exports.render = render;
module.exports.load = load;
module.exports.trySetViewType = trySetViewType;
module.exports.clearCache = clearCache;
var VALID_VIEW_TYPES = ['grid', 'tree', 'visualize'];
/*
* Items view.
* Renders one of: Grid, Tree or Visualize views depending on the state
*/
function create() {
var treeComponent = new TreeView();
var state = mercury.varhash({
tree: treeComponent.state,
/*
* List of namespace items to display
* @see services/namespace/item
* @type {Array<namespaceitem>}
*/
items: mercury.array([]),
/*
* Specifies the current view type of the items.
* One of: tree, radial, grid
* Note: This value is persisted between namespace browser sessions.
*/
viewType: mercury.value('tree'),
/*
* uuid for the current browse-namespace request.
* Needed to handle out-of-order return of async calls.
* @type {String}
*/
currentRequestId: mercury.value('')
});
var events = mercury.input([
'tree'
]);
events.tree = treeComponent.events;
return {
state: state,
events: events
};
}
function trySetViewType(state, viewType) {
var isValid = VALID_VIEW_TYPES.indexOf(viewType) >= 0;
if (!isValid) {
return false;
}
// async call to persist the view type
stateService.saveBrowseViewType(viewType);
state.viewType.set(viewType);
return true;
}
/*
* Does the initialization and loading of the data necessary to display the
* namespace items.
* Called and used by the parent browse view to initialize the view on
* request.
* Returns a promise that will be resolved when loading is finished. Promise
* is used by the parent browse view to display a loading progressbar.
*/
function load(state, namespace, globQuery) {
// TODO(aghassemi)
// -Rename the concept to "init", not every component may have it.
// does not return anything, we can have showLoadingIndicator(bool) be an
// functionality that can be requested of the browse view.
// -Move items to "GridView"
// -Have a common component between tree and vis to share the childrens map
if (state.viewType() === 'tree') {
TreeView.expand(state.tree, namespace);
// During a reload, some tree nodes may already have been expanded.
// If so, call expand to re-glob their children.
var expandedNames = state.tree.expandedMap();
for (var name in expandedNames) {
if (expandedNames[name] === true) {
TreeView.expand(state.tree, name);
}
}
return namespaceService.getNamespaceItem(namespace)
.then(function(item) {
state.tree.put('rootItem', item);
})
.catch(function(err) {
state.tree.put('rootItem', null);
return Promise.reject(err);
});
}
if (state.viewType() !== 'grid') {
return Promise.resolve();
}
// Search the namespace and update the browseState's items.
var requestId = uuid.v4();
state.currentRequestId.set(requestId);
state.put('items', mercury.array([]));
return new Promise(function(resolve, reject) {
namespaceService.search(namespace, globQuery).
then(function globResultsReceived(items) {
if (!isCurrentRequest()) {
resolve();
return;
}
state.put('items', items);
items.events.once('end', loadingFinished);
items.events.on('globError', loadingFinished);
}).catch(function(err) {
log.error(err);
reject();
});
function loadingFinished() {
if (!isCurrentRequest()) {
return;
}
resolve();
}
});
// Whether we are still the current request. This is used to ignore out of
// order return of async calls where user has moved on to another item
// by the time previous requests result comes back.
function isCurrentRequest() {
return state.currentRequestId() === requestId;
}
}
function render(state, events, browseState, browseEvents, navEvents) {
switch (state.viewType) {
case 'grid':
return GridView.render(state, browseState, browseEvents, navEvents);
case 'tree':
return TreeView.render(state.tree, events.tree,
browseState, browseEvents);
case 'visualize':
return VisualizeView.render(state, browseState, browseEvents, navEvents);
default:
log.error('Unsupported viewType: ' + state.viewType);
}
}
// Clears any locally cached data
function clearCache(state, namespace) {
state.put('items', mercury.array([]));
TreeView.clearCache(state.tree, namespace);
VisualizeView.clearCache();
}
},{"../../../lib/log":223,"../../../services/namespace/service":248,"../../../services/state/service":252,"./grid-view/index":180,"./tree-view/index":184,"./visualize-view/index":186,"mercury":45,"uuid":143}],182:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var namespaceService = require('../../../../services/namespace/service');
var log = require('../../../../lib/log')(
'components:browse:tree-view:expand');
module.exports = expand;
/*
* Expand the treenode the a given name including loading children.
*/
function expand(state, name) {
state.expandedMap.put(name, true);
return loadChildren(state, name);
}
/*
* Loads children for a given name.
* Sets a loading indicator on the child until the 'end' signal is received.
*/
function loadChildren(state, name) {
// if we have already have the children, just return
var existingChildren = state.childrenMap.get(name);
if(existingChildren) {
return Promise.resolve(existingChildren);
} else {
state.isLoadingMap.put(name, true);
}
return namespaceService.getChildren(name)
.then(function childrenReceived(items) {
//TODO(aghassemi) prefix name due to invalid key names like delete
state.childrenMap.put(name, items);
items.events.once('end', function() {
state.isLoadingMap.delete(name);
});
return items;
}).catch(function(err) {
//TODO(aghassemi) Go to error page
log.error(err);
return Promise.reject(err);
});
}
},{"../../../../lib/log":223,"../../../../services/namespace/service":248}],183:[function(require,module,exports){
module.exports = ":root{}:root{}tree-node::shadow .item{color:rgba(0, 0, 0, 0.87);padding:0.2em 0.5em;}tree-node::shadow .highlight{color:#ffffff;background-color:#FF6E40;}tree-node::shadow .highlight .itemicon{color:#ffffff;}tree-node::shadow .itemicon{color:rgba(0, 0, 0, 0.54);transform:scale(0.7);}#tree-container{margin-top:1em;margin-bottom:1em;margin-left:-0.5em;}"
},{}],184:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var extend = require('extend');
var namespaceService = require('../../../../services/namespace/service');
var polymerEvent = require('../../../../lib/mercury/polymer-event');
var expand = require('./expand');
var getServiceIcon = require('../../get-service-icon');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
module.exports.expand = expand;
module.exports.clearCache = clearCache;
function create() {
var state = mercury.varhash({
/*
* Map of objectNames to child namespace items
* @see services/namespace/item
* @type {varhash<string,Array<namespaceitem>>}
* Always contains the children for every item in the tree (including
* leaf nodes) so we can know whether to display the expand icon
*/
childrenMap: mercury.varhash({}),
/*
* Map of objectNames to Boolean flag showing if tree view is expanded
* @type {varhash<string,Boolean>}
* For each item, says whether it is expanded in the tree view.
* If there is no value, assumes false.
*/
expandedMap: mercury.varhash({}),
/*
* Map of objectNames to Boolean flag for whether this is being loaded.
* @type {varhash<string,Boolean>}
* If the item is not present, it is not considered to be loading.
*/
isLoadingMap: mercury.varhash({}),
/*
* The current item to be used as the root of the tree
* @see services/namespace/item
* @type {namespaceitem}
*/
rootItem: mercury.value(null)
});
var events = mercury.input([
'openChange', // expand / collapse of tree node
'activate' // tap on tree node
]);
wireUpEvents(state, events);
return {
state: state,
events: events
};
}
function render(state, events, browseState, browseEvents) {
insertCss(css);
var item = state.rootItem; // start at the root
if (item === null) {
return;
} // TODO(wm) Maybe show "Loading..."?
var rootEvents = { // events to attach to root of tree
'ev-openchange': polymerEvent(events.openChange),
'ev-activate': polymerEvent(
events.activate, {
browseEvents: browseEvents
}
)
};
return h('div#tree-container',
createTreeNode(state, browseState.selectedItemName, item, rootEvents)
);
}
/*
* Recursively render tree from the bottom up
* Has to be from bottom up because virtual DOM is immutable.
* extraprops is extra properties to add (used for root events)
*/
function createTreeNode(state, selected, item, extraprops) {
var childrenArr = state.childrenMap[item.objectName];
var descendants = []; // all viewed descendants of this item
if (childrenArr) {
descendants = childrenArr.map(function(child) {
return createTreeNode(state, selected, child);
});
}
var iconInfo = getServiceIcon(item);
var props = {
attributes: {
label: item.mountedName || '<Home>',
emptytext: 'No visible children',
icon: iconInfo.icon,
itemTitle: iconInfo.title,
open: !!state.expandedMap[item.objectName],
highlight: (item.objectName === selected),
isExpandable: !item.isLeaf,
loading: state.isLoadingMap[item.objectName]
},
objectName: item.objectName
};
if (extraprops) { // root of tree
extend(props, extraprops);
}
return h('tree-node', props, descendants);
}
function wireUpEvents(state, events) {
// expand or collapse item
events.openChange(function(data) {
var objectName = data.polymerDetail.node.objectName;
var openMe = data.polymerDetail.node.open;
if (openMe) {
expand(state, objectName);
} else { // collapse this item
state.expandedMap.delete(objectName);
}
});
// highlight item and display details
events.activate(function(data) {
var objectName = data.polymerDetail.node.objectName;
data.browseEvents.selectItem({
name: objectName
});
});
}
/*
* Given a name, it clears local cache of any items that match the name or
* are a suffix of it.
*/
function clearCache(state, namespace) {
deleteFromVarHashByPrefix(state.childrenMap, namespace);
}
function deleteFromVarHashByPrefix(varhash, prefix) {
var childrenKeys = Object.keys(varhash());
childrenKeys.forEach(function(ck) {
// Ideally we want a transaction here but VarHash does not support it yet
// https://github.com/nrw/observ-varhash/issues/15
if (namespaceService.prefixes(prefix, ck)) {
varhash.delete(ck);
}
});
}
},{"../../../../lib/mercury/polymer-event":227,"../../../../services/namespace/service":248,"../../get-service-icon":148,"./expand":182,"./index.css":183,"extend":36,"insert-css":37,"mercury":45}],185:[function(require,module,exports){
module.exports = ":root{}:root{}.network,.networkParent{position:absolute;overflow:hidden;top:0;left:0;right:0;bottom:0;font-family:'Roboto', sans-serif;}.network svg.overlay{overflow:hidden;}.vismenu{position:absolute;top:5px;left:10px;width:92px;}.vismenu paper-fab{background-color:#ffffff;margin:5px 3px;}paper-shadow.contextmenu{display:none;background-color:#ffffff;position:absolute;width:13em;}paper-shadow.contextmenu paper-item::shadow .button-content{padding:5px 10px;font-size:0.9em;}paper-shadow.contextmenu paper-item div.ksc{position:absolute;right:10px;}.contextmenu paper-item:hover,.contextmenu paper-item:focus{background-color:rgba(236, 239, 241, 0.8);}.node{cursor:pointer;}.node path{fill:#ffffff;}.node text{font-size:12px;font-family:'Roboto', sans-serif;text-shadow:4px 4px 3px #ffffff,\n -4px -4px 3px #ffffff;}.node text:hover,.node text:focus{font-size:1.1em;transition:font-size 0.1s;}.node text:not(:hover){transition:font-size 1s;transition-delay:0.5s;}.link{fill:none;stroke:#ccc;stroke-width:1.5px;}@-webkit-keyframes blinking{0%{opacity:1;}25%{opacity:0.1;}50%{opacity:1;}100%{opacity:1;}}@keyframes blinking{0%{opacity:1;}20%{opacity:0.1;}40%{opacity:1;}100%{opacity:1;}}.node path.loading{-webkit-animation:blinking 0.7s ease infinite;animation:blinking 0.7s ease infinite;}"
},{}],186:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var d3 = require('d3');
var namespaceService = require('../../../../services/namespace/service');
var browseRoute = require('../../../../routes/browse');
var getServiceIcon = require('../../get-service-icon');
var log = require('../../../../lib/log')(
'components:browse:items:visualize-view'
);
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
module.exports.clearCache = clearCache;
var DURATION = 500; // d3 animation duration
var STAGGER = 5; // mS delay for each node
var MIN_ZOOM = 0.5; // minimum zoom allowed
var MAX_ZOOM = 20; // maximum zoom allowed
var SYMBOL_STROKE_COLOR = '#00838F';
var SELECTED_COLOR = '#E65100'; // color of selected node
var ZOOM_INC = 0.06; // zoom factor per animation frame
var PAN_INC = 3; // pan per animation frame
var ROT_INC = 0.5; // rotation per animation frame
var RELATIVE_ROOT = '<Home>';
// keyboard key codes
var KEY_PLUS = 187; // + (zoom in)
var KEY_MINUS = 189; // - (zoom out)
var KEY_PAGEUP = 33; // (rotate CCW)
var KEY_PAGEDOWN = 34; // (rotate CW)
var KEY_LEFT = 37; // left arrow
var KEY_UP = 38; // up arrow
var KEY_RIGHT = 39; // right arrow
var KEY_DOWN = 40; // down arrow
var KEY_SPACE = 32; // (expand node)
var KEY_RETURN = 13; // (expand tree)
var KEY_HOME = 36; // (center root)
var KEY_END = 35; // (center selection)
function create() {}
var widget;
function clearCache() {
widget = null;
}
function render(itemsState, browseState, browseEvents, navEvents) {
insertCss(css);
if (!widget) {
widget = createWidget(browseState, browseEvents, navEvents);
} else {
widget.update(browseState, browseEvents);
}
return [
widget,
h('div.vismenu', { // visualization menu
}, [
h('paper-fab.zoom', {
attributes: {
mini: true,
raised: true,
icon: 'add',
title: 'Zoom In (+)',
'aria-label': 'zoom in'
},
'ev-down': widget.polydown.bind(undefined, KEY_PLUS),
'ev-up': widget.polyup.bind(undefined, KEY_PLUS)
}),
h('paper-fab.zoom', {
attributes: {
mini: true,
icon: 'remove',
title: 'Zoom Out (\u2212)',
'aria-label': 'zoom out'
},
'ev-down': widget.polydown.bind(undefined, KEY_MINUS),
'ev-up': widget.polyup.bind(undefined, KEY_MINUS),
}),
h('paper-fab.rotate', {
attributes: {
mini: true,
icon: 'image:rotate-left',
title: 'Rotate CCW (Page Up)',
'aria-label': 'rotate counterclockwise'
},
'ev-down': widget.polydown.bind(undefined, KEY_PAGEUP),
'ev-up': widget.polyup.bind(undefined, KEY_PAGEUP)
}),
h('paper-fab.rotate', {
attributes: {
mini: true,
icon: 'image:rotate-right',
title: 'Rotate CW (Page Down)',
'aria-label': 'rotate clockwise'
},
'ev-down': widget.polydown.bind(undefined, KEY_PAGEDOWN),
'ev-up': widget.polyup.bind(undefined, KEY_PAGEDOWN)
}),
h('paper-fab.expand', {
attributes: {
mini: true,
icon: 'unfold-more', // 'expand-less',
title: 'Load +1 Level (space bar)',
'aria-label': 'load +1 level'
},
'ev-click': widget.menu.bind(undefined, KEY_SPACE, false)
})
]),
h('paper-shadow.contextmenu', { // context menu
attributes: {
z: 3 // height above background
}
}, [ // context menu
h('paper-item', {
'ev-mouseup': widget.menu.bind(undefined, KEY_RETURN, false),
'ev-mousedown': widget.menu.bind(undefined, KEY_RETURN, false)
}, [h('div.ecnode', 'Expand Node'), h('div.ksc', 'Return')]),
h('paper-item', {
'ev-mouseup': widget.menu.bind(undefined, KEY_RETURN, true),
'ev-mousedown': widget.menu.bind(undefined, KEY_RETURN, true)
}, [h('div', 'Show Loaded'), h('div.ksc', '\u21E7 Return')]),
h('paper-item', {
'ev-mouseup': widget.menu.bind(undefined, KEY_SPACE, false),
'ev-mousedown': widget.menu.bind(undefined, KEY_SPACE, false)
}, [h('div', 'Load +1 Level'), h('div.ksc', 'space bar')]),
h('paper-item', {
'ev-mouseup': widget.menu.bind(undefined, KEY_SPACE, true),
'ev-mousedown': widget.menu.bind(undefined, KEY_SPACE, true)
}, [h('div', 'Browse Into'), h('div.ksc', '\u21E7 space bar')]),
h('paper-item', {
'ev-mouseup': widget.menu.bind(undefined, KEY_END, false),
'ev-mousedown': widget.menu.bind(undefined, KEY_END, false)
}, [h('div', 'Center Selected'), h('div.ksc', 'End')]),
h('paper-item', {
'ev-mouseup': widget.menu.bind(undefined, KEY_HOME, false),
'ev-mousedown': widget.menu.bind(undefined, KEY_HOME, false)
}, [h('div', 'Center Root'), h('div.ksc', 'Home')])
])
];
}
function createWidget(browseState, browseEvents, navEvents) {
var networkElem; // DOM element for visualization
var selNode; // currently selected node
var selectItem; // function to select item in app
var width, height; // size of the visualization diagram
var curX, curY, curR, curZ; // transforms (x, y, rotate, zoom)
var modZ; // modified zoom for nodes and text
var diagonal; // d3 diagonal projection for use by the node paths
var treeD3; // d3 tree layout
var svgBase, svgGroup; // svg elements
var root; // data trees
var rootIndex = {}; // index id to nodes
browseInto.browseState = browseState;
browseInto.navEvents = navEvents;
// Constructor for mercury widget for d3 element
function D3Widget(browseState, browseEvents) {
this.browseState = browseState;
this.browseEvents = browseEvents;
}
D3Widget.prototype.type = 'Widget';
D3Widget.prototype.init = function() {
if (!networkElem) {
networkElem = document.createElement('div');
networkElem.className = 'network';
networkElem.setAttribute('tabindex', 0); // allow focus
selectItem = this.browseEvents.selectItem.bind(this.browseEvents);
requestAnimationFrame(initD3);
}
// wrap in a new element, needed for Mercury vdom to patch properly.
var wrapper = document.createElement('div');
wrapper.className = 'networkParent';
wrapper.appendChild(networkElem);
requestAnimationFrame(this.updateRoot.bind(this));
return wrapper;
};
// Keep track of previous namespace that was browsed to so we can
// know when navigating to a different namespace happens.
var previousNamespace;
D3Widget.prototype.polyup = polyup;
D3Widget.prototype.polydown = polydown;
D3Widget.prototype.menu = menu;
D3Widget.prototype.update = function(browseState, browseEvents) {
// handle changed selection
selNode = rootIndex[browseState.selectedItemName] || selNode;
this.browseState = browseState;
this.browseEvents = browseEvents;
// check to see if window was resized while we were away
if (width !== networkElem.offsetWidth) {
resize();
}
this.updateRoot();
networkElem.focus();
};
// build new data tree
D3Widget.prototype.updateRoot = function() {
var rootNodeId = this.browseState.namespace;
if (previousNamespace !== rootNodeId) {
previousNamespace = rootNodeId;
// parse root id
var parts = namespaceService.util.parseName(rootNodeId);
var isRooted = namespaceService.util.isRooted(rootNodeId);
var buildId = '';
if (!isRooted) {
parts.unshift('');
} // create <Home> node
var parent; // used to connect each new node to their parent
parts.forEach(function(v) {
buildId += (buildId.length > 0 || isRooted ? '/' : '') + v;
var nn = rootIndex[buildId] || {};
var isNew = (nn.id === undefined);
nn.id = buildId;
nn.name = v || RELATIVE_ROOT;
nn.isLeaf = false;
nn.hasServer = true; // assume true, fix later
nn.hasMountPoint = true; // assume true, fix later
if (parent !== undefined) {
nn.parent = parent;
if (parent.children === undefined && parent._children === undefined) {
parent._children = [nn]; // initially hidden
}
}
if (isNew) {
rootIndex[buildId] = nn;
}
parent = nn;
});
root = parent; // new root
if (selNode === undefined) {
selectNode(root);
}
loadItem(root); // load rest of information for this node
loadSubItems(root); // load the children
}
updateD3(root, true); // always animate
};
// initialize d3 HTML elements
function initD3() {
// size of the diagram
width = networkElem.offsetWidth;
height = networkElem.offsetHeight;
// current pan, zoom, and rotation
curX = width / 2; // center
curY = height / 2;
curZ = modZ = 1.0; // current zoom
curR = 270; // current rotation
// d3 diagonal projection for use by the node paths
diagonal = d3.svg.diagonal.radial().
projection(function(d) {
return [d.y, d.x / 180 * Math.PI];
});
// d3 tree layout
treeD3 = d3.layout.tree().
// circular coordinates to fit in window
// 120 is to allow space for text strings
size([360, Math.min(width, height) / 2 - 120]).
// space between nodes, depends on if they have same parent
// dividing by a.depth is for radial coordinates
separation(function(a, b) {
return (a.parent === b.parent ? 1 : 2) / (a.depth + 1);
});
// define the svgBase, attaching a class for styling and the zoomListener
svgBase = d3.select('.network').append('svg').
attr('width', width).
attr('height', height).
attr('class', 'overlay').
on('mousedown', mousedown);
// Group which holds all nodes and manages pan, zoom, rotate
svgGroup = svgBase.append('g').
attr('transform', 'translate(' + curX + ',' + curY + ')');
networkElem.focus();
d3.select('.network'). // set up document events
on('wheel', wheel). // zoom, rotate
on('keydown', keydown).
on('keyup', keyup).
on('mouseover', function() {
networkElem.focus();
});
d3.select(window).on('resize', resize);
}
// draw tree using d3js
// subroot - source node of the update
// doAni - whether to do a transition animation
function updateD3(subroot, doAni) {
// length of d3 animation
var duration = (d3.event && d3.event.altKey ? DURATION * 4 : DURATION);
// Compute the new tree layout.
var d3nodes = treeD3.nodes(root);
var d3links = treeD3.links(d3nodes);
// Update the view
var view = doAni ? svgGroup.transition().duration(duration) : svgGroup;
view.attr('transform',
'rotate(' + curR + ' ' + curX + ' ' + curY +
')translate(' + curX + ' ' + curY +
')scale(' + curZ + ')');
var gnode = svgGroup.selectAll('g.node').
data(d3nodes, function(d) {
return d.id;
});
// Enter any new nodes at the parent's previous position
var nodeEnter = gnode.enter().insert('g', ':first-child').
attr('class', 'node').
attr('opacity', 0).
attr('transform', 'rotate(' + (subroot.x - 90) +
')translate(' + subroot.y + ')').
on('click', click).on('dblclick', dblclick).
on('contextmenu', showContextMenu);
nodeEnter.append('title').text(function(d) {
return getServiceIcon(d).title;
});
nodeEnter.filter(function(d) { // Mount Point
return d.hasMountPoint;
}).append('path').attr('class', 'mountpointicon').
attr('d', d3.svg.symbol().type('square'));
nodeEnter.filter(function(d) { // Server
return d.hasServer;
}).append('path').attr('class', 'servericon').
attr('d', d3.svg.symbol().type('circle').size(60));
nodeEnter.append('text').
text(function(d) {
return d.name;
}).
attr('transform', ((subroot.x + curR) % 360 <= 180 ?
'rotate(-7)translate(8)scale(' : 'rotate(187)translate(-8)scale('
) + modZ + ')');
// update existing graph nodes
// set path style for selection, loading, and scale
gnode.select('path').
attr('transform', 'scale(' + modZ + ')').
classed('loading', function(d) {
return d.loading;
}).
attr('stroke', function(d) {
return d === selNode ? SELECTED_COLOR : SYMBOL_STROKE_COLOR;
}).
attr('stroke-width', function(d) {
return d === selNode ? 3 : 2;
});
gnode.select('title').text(function(d) {
return getServiceIcon(d).title;
});
// remove icons if assumed true but turn out to be false
gnode.select('path.servericon').filter(function(d) {
return !d.hasServer;
}).remove();
gnode.select('path.mountpointicon').filter(function(d) {
return !d.hasMountPoint;
}).remove();
gnode.select('text').
attr('text-anchor', function(d) {
return (d.x + curR) % 360 <= 180 ? 'start' : 'end';
}).
attr('transform', function(d) {
return ((d.x + curR) % 360 <= 180 ?
'rotate(-7)translate(8)scale(' :
'rotate(187)translate(-8)scale('
) + modZ + ')';
}).
attr('fill', function(d) {
return d === selNode ? SELECTED_COLOR : 'black';
}).
attr('dy', '5px');
var nodeUpdate = (doAni ?
gnode.transition().duration(duration).delay(function(d, i) {
return i * STAGGER + Math.max(0, d.depth - selNode.depth);
}) : gnode);
nodeUpdate.attr('transform', function(d) {
return 'rotate(' + (d.x - 90) + ')translate(' + d.y + ')';
}).style('opacity', 1);
nodeUpdate.select('path').
attr('transform', 'scale(' + modZ + ')');
// Transition exiting nodes to the parent's new position and remove
var nodeExit = doAni ? gnode.exit().transition().duration(duration).
delay(function(d, i) {
return i * STAGGER;
}): gnode.exit();
nodeExit.attr('transform', function(d) {
return 'rotate(' + (subroot.x - 90) + ')translate(' + subroot.y + ')';
}).
attr('opacity', 0).
remove();
nodeExit.select('.node path').attr('transform', 'scale(0)');
nodeExit.select('.node text').style('fill-opacity', 0);
// Update the links…
var glink = svgGroup.selectAll('path.link').
data(d3links, function(d) {
return d.target.id;
});
// Enter any new links at the parent's previous position
glink.enter().insert('path', 'g').
attr('class', 'link').
attr('d', function() {
var o = {
x: subroot.x,
y: subroot.y
};
return diagonal({
source: o,
target: o
});
});
// Transition links to their new position
(doAni ? glink.transition().duration(duration).delay(function(d, i) {
return i * STAGGER + Math.max(0, d.source.depth - selNode.depth);
}) : glink).
attr('d', diagonal);
// Transition exiting nodes to the parent's new position
(doAni ? glink.exit().transition().duration(duration) : glink.exit()).
attr('d', function() {
var o = {
x: subroot.x,
y: subroot.y
};
return diagonal({
source: o,
target: o
});
}).
remove(); // remove edge at end of animation
} // end updateD3
// find place to insert new node in children
var bisectfun = d3.bisector(function(d) {
return d.name;
}).right;
// create node or merge new item data into it
function mergeNode(item, parent) {
var nn = rootIndex[item.objectName] || {};
var isNew = nn.id === undefined; // not found in rootIndex
nn.id = item.objectName;
nn.name = item.mountedName || RELATIVE_ROOT;
nn.parent = parent || nn.parent;
nn.isLeaf = item.isLeaf;
nn.hasMountPoint = item.hasMountPoint;
nn.hasServer = item.hasServer;
if (isNew && parent !== undefined) { // insert node in proper place
rootIndex[nn.id] = nn;
if (parent.children === undefined) {
parent.children = [nn];
} else {
parent.children.splice(bisectfun(parent.children, nn.name), 0, nn);
}
}
return isNew; // need to animate it in
} // end mergeNode
function loadItem(node) { // load a single item (used for root of tree)
namespaceService.getNamespaceItem(node.id).then(function(observable) {
mercury.watch(observable, updateItem);
function updateItem(item) { // currently only gets called once
mergeNode(item, node.parent); // update elsewhere
}
});
}
// load children items asynchronously
function loadSubItems(node) {
if (node.subNodesLoaded) {
return;
}
var namespace = node.id;
if (node._children) {
node.children = node._children;
node._children = null;
}
node.subNodesLoaded = true;
showLoading(node, true); // node is loading
namespaceService.getChildren(namespace).then(function(resultObservable) {
var initialValues = resultObservable();
initialValues.forEach(function(item) {
batchUpdate(node, mergeNode(item, node));
});
resultObservable.events.once('end', function() {
showLoading(node, false); // node no longer loading
});
resultObservable(updatedValues);
function updatedValues(results) {
// TODO(wmleler) support removed and updated nodes for watchGlob
var item = results._diff[0][2]; // changed item from Mercury
batchUpdate(node, mergeNode(item, node));
}
}).catch(function(err) {
log.error('glob failed', err);
});
} // end loadSubItems
// batch up groups of updates to speed up transitions
var batchNode = null;
var batchId = null;
function batchUpdate(node, doAni) {
if (node !== batchNode) {
if (batchNode !== null) {
updateD3(batchNode, doAni);
}
batchNode = node;
if (batchId !== null) {
clearTimeout(batchId);
batchId = null;
}
} else {
batchId = setTimeout(function() {
updateD3(batchNode, doAni);
batchId = null;
}, DURATION);
}
}
function selectNode(node) { // highlight node and show details
if (node === selNode) {
return;
}
selNode = node;
selectItem({
name: node.id
}); // notify rest of app
}
function browseInto(node) { // make this node the root
var browseUrl = browseRoute.createUrl(browseInto.browseState, {
namespace: node.id
});
browseInto.navEvents.navigate({
path: browseUrl
});
}
// set view with no animation
function setview() {
svgGroup.attr('transform',
'rotate(' + curR + ' ' + curX + ' ' + curY +
')translate(' + curX + ' ' + curY +
')scale(' + curZ + ')');
svgGroup.selectAll('text').
attr('text-anchor', function(d) {
return (d.x + curR) % 360 <= 180 ? 'start' : 'end';
}).
attr('transform', function(d) {
return ((d.x + curR) % 360 <= 180 ?
'rotate(-7)translate(8)scale(' :
'rotate(187)translate(-8)scale('
) + modZ + ')';
});
svgGroup.selectAll('.node path').
attr('transform', 'scale(' + modZ + ')').
attr('stroke-width', function(d) {
return d === selNode ? 3 : 2;
});
}
// show nodes that are loading
function showLoading(node, v) {
node.loading = v;
svgGroup.selectAll('.node path').
classed('loading', function(d) {
return d.loading;
});
}
//
// Helper functions for collapsing and expanding nodes
//
// Toggle expand / collapse
function toggle(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else if (d._children && d.subNodesLoaded) {
d.children = d._children;
d._children = null;
} else {
loadSubItems(d);
}
}
function collapse(d) { // collapse one level
if (d.children) {
d._children = d.children;
d.children = null;
}
}
// expand all loaded children and descendents
function expandTree(d) {
if (d._children) {
d.children = d._children;
d._children = null;
}
if (d.children) {
d.children.forEach(expandTree);
}
}
// expand one level of tree using breadth first search
function expand1Level(d) {
var q = [d]; // non-recursive using queue
var cn;
var done = null;
while (q.length > 0) {
cn = q.shift();
if (done !== null && done < cn.depth) {
return;
}
if (cn._children) {
done = cn.depth;
cn.children = cn._children;
cn._children = null;
cn.children.forEach(collapse);
} else if (!(cn.isLeaf || cn.subNodesLoaded)) {
done = cn.depth;
loadSubItems(cn);
}
if (cn.children) {
q = q.concat(cn.children);
}
}
// no nodes to open
}
var moveX = 0,
moveY = 0,
moveZ = 0,
moveR = 0; // animations
var keysdown = []; // which keys are currently down
var animation = null;
var aniTime = null; // time since last animation frame
// update animation frame
function frame(frametime) {
var diff = aniTime ? (frametime - aniTime) / 16 : 0;
aniTime = frametime;
var dz = Math.pow(1.2, diff * moveZ);
var newZ = limitZ(curZ * dz);
dz = newZ / curZ;
curZ = newZ;
modZ = Math.pow(1.1, -curZ); // limit text and node size as scale increases
curX += diff * moveX - (width / 2 - curX) * (dz - 1);
curY += diff * moveY - (height / 2 - curY) * (dz - 1);
curR = limitR(curR + diff * moveR);
setview();
animation = requestAnimationFrame(frame);
}
// enforce zoom extent
function limitZ(z) {
return Math.max(Math.min(z, MAX_ZOOM), MIN_ZOOM);
}
// keep rotation between 0 and 360
function limitR(r) {
return (r + 360) % 360;
}
//
// d3 event handlers
//
function resize() { // window resize
if (networkElem.offsetWidth === 0) {
return;
}
var oldwidth = width;
var oldheight = height;
width = networkElem.offsetWidth;
height = networkElem.offsetHeight;
treeD3.size([360, Math.min(width, height) / 2 - 120]);
svgBase.attr('width', width).attr('height', height);
curX += (width - oldwidth) / 2;
curY += (height - oldheight) / 2;
svgGroup.attr('transform',
'rotate(' + curR + ' ' + curX + ' ' + curY +
')translate(' + curX + ' ' + curY +
')scale(' + curZ + ')');
updateD3(root, false);
}
function click(d) { // Select node
if (d3.event.defaultPrevented || d === selNode) {
return;
}
selectNode(d);
updateD3(d, false);
d3.event.preventDefault();
}
function dblclick(d) { // Toggle children of node
if (d3.event.defaultPrevented) {
return;
} // click suppressed
d3.event.preventDefault();
if (d3.event.shiftKey) {
expand1Level(d);
} else {
toggle(d);
}
updateD3(d, true);
}
var startposX, startposY; // initial position on mouse button down for pan
function mousedown() { // pan action from mouse drag
if (d3.event.which !== 1) {
return;
} // ingore other mouse buttons
startposX = curX - d3.event.clientX;
startposY = curY - d3.event.clientY;
d3.select(document).on('mousemove', mousemove, true);
d3.select(document).on('mouseup', mouseup, true);
networkElem.focus();
d3.event.preventDefault();
}
function mousemove() { // drag
curX = startposX + d3.event.clientX;
curY = startposY + d3.event.clientY;
setview();
d3.event.preventDefault();
}
function mouseup() { // cleanup
d3.select(document).on('mousemove', null);
d3.select(document).on('mouseup', null);
}
function wheel() { // mousewheel (including left-right)
var dz, newZ;
var slow = (d3.event && d3.event.altKey) ? 0.25 : 1;
if (d3.event.wheelDeltaY !== 0) { // up-down = zoom
dz = Math.pow(1.2, d3.event.wheelDeltaY * 0.001 * slow);
newZ = limitZ(curZ * dz);
dz = newZ / curZ;
curZ = newZ;
// zoom around mouse position
curX -= (d3.event.clientX - curX) * (dz - 1);
curY -= (d3.event.clientY - curY) * (dz - 1);
setview();
}
if (d3.event.wheelDeltaX !== 0) { // left-right = rotate
curR = limitR(curR + d3.event.wheelDeltaX * 0.01 * slow);
updateD3(root, false);
}
}
function polydown(key, evt) { // polymer ev-mousedown event
actionDown(key, evt.shiftKey, evt.altKey);
}
function polyup(key, evt) { // polymer ev-mouseup event
actionUp(key);
}
function menu(key, shift, evt) { // context menu selection event
if (evt === undefined) { // shiftkey not supplied
evt = shift;
shift = evt.shiftKey;
}
actionDown(key, shift, evt.altKey);
networkElem.focus();
}
function keydown() { // d3 keydown event
var evt = d3.event;
if (evt.repeat) {
return;
}
actionDown(evt.which, evt.shiftKey, evt.altKey);
}
function keyup() { // d3 keyup event
var evt = d3.event;
actionUp(evt.which);
}
// right click, show context menu and select this node
function showContextMenu(d) {
d3.event.preventDefault();
d3.select('.ecnode').text(
(d.children ? 'Collapse ' : 'Expand ') + 'Node');
var cmenu = d3.select('.contextmenu');
cmenu.style({
left: Math.min(d3.event.offsetX + 3,
width - cmenu.style('width').replace('px', '') - 5) + 'px',
top: (d3.event.offsetY + 8) + 'px',
display: 'block'
});
var doc = d3.select(document);
doc.on('mousedown.cm', hideContextMenu, true);
setTimeout(function() {
doc.on('mouseup.cm', hideContextMenu, true);
}, 500);
selectNode(d);
}
function hideContextMenu() {
var doc = d3.select(document);
d3.select('.contextmenu').style('display', 'none');
doc.on('mouseup.cm', null);
doc.on('mousedown.cm', null);
networkElem.focus();
}
// Event actions
// Almost all UI actions pass through here,
// even if they are not originally generated from the keyboard
// There are two types of actions:
// * Press-and-Hold actions perform some action while they are pressed,
// until they are released, like pan, zoom, and rotate. These actions end
// with "break", so the key can be saved, and actionUp can stop the action.
// * Click actions mostly happen on keydown, like toggling children.
function actionDown(key, shift, alt) {
var parch; // parent's children
var slow = alt ? 0.25 : 1;
if (keysdown.indexOf(key) >= 0) {
return;
} // defeat auto repeat
switch (key) {
case KEY_PLUS: // zoom in
moveZ = ZOOM_INC * slow;
break;
case KEY_MINUS: // zoom out
moveZ = -ZOOM_INC * slow;
break;
case KEY_PAGEUP: // rotate counterclockwise
moveR = -ROT_INC * slow;
break;
case KEY_PAGEDOWN: // rotate clockwise
moveR = ROT_INC * slow;
break;
case KEY_LEFT:
if (shift) { // move selection to parent
if (!selNode) {
selectNode(root);
} else if (selNode.parent) {
selectNode(selNode.parent);
updateD3(selNode, false);
}
return;
}
moveX = -PAN_INC * slow; // pan left
break;
case KEY_UP:
if (shift) { // move selection to previous child
if (!selNode) {
selectNode(root);
} else if (selNode.parent) {
parch = selNode.parent.children;
selectNode(parch[(parch.indexOf(selNode) +
parch.length - 1) % parch.length]);
updateD3(selNode, false);
}
return;
}
moveY = -PAN_INC * slow; // pan up
break;
case KEY_RIGHT:
if (shift) { // move selection to first/last child
if (!selNode) {
selectNode(root);
} else {
if (selNode.children && selNode.children.length > 0) {
selectNode(selNode.children[0]);
updateD3(selNode, false);
}
}
return;
}
moveX = PAN_INC * slow; // pan right
break;
case KEY_DOWN:
if (shift) { // move selection to next child
if (!selNode) {
selectNode(root);
} else if (selNode.parent) {
parch = selNode.parent.children;
selectNode(parch[(parch.indexOf(selNode) + 1) % parch.length]);
updateD3(selNode, false);
}
return;
}
moveY = PAN_INC * slow; // pan down
break;
case KEY_RETURN:
if (!selNode) {
selectNode(root);
}
if (shift) { // show loaded
expandTree(selNode);
loadSubItems(selNode);
} else {
toggle(selNode); // expand/collapse node
}
updateD3(selNode, true);
return;
case KEY_SPACE:
if (!selNode) {
selectNode(root);
}
if (shift) { // browse into
browseInto(selNode);
} else { // load +1 level
expand1Level(selNode);
updateD3(selNode, true);
}
return;
case KEY_HOME: // reset transform
curX = width / 2;
curY = height / 2;
curR = limitR(90 - root.x);
curZ = 1;
updateD3(root, true);
return;
case KEY_END: // zoom to selection
if (!selNode) {
return;
}
curX = width / 2 - selNode.y * curZ;
curY = height / 2;
curR = limitR(90 - selNode.x);
updateD3(selNode, true);
return;
default:
return; // ignore other keys
}
keysdown.push(key);
// start animation if anything happening
if (keysdown.length > 0 && animation === null) {
animation = requestAnimationFrame(frame);
}
}
function actionUp(key) {
var pos = keysdown.indexOf(key);
if (pos < 0) {
return;
}
switch (key) {
case KEY_PLUS: // - = zoom out
case KEY_MINUS: // + = zoom in
moveZ = 0;
break;
case KEY_PAGEUP: // page up = rotate CCW
case KEY_PAGEDOWN: // page down = rotate CW
moveR = 0;
break;
case KEY_LEFT: // left arrow
case KEY_RIGHT: // right arrow
moveX = 0;
break;
case KEY_UP: // up arrow
case KEY_DOWN: // down arrow
moveY = 0;
break;
}
keysdown.splice(pos, 1); // remove key
if (keysdown.length > 0 || animation === null) {
return;
}
cancelAnimationFrame(animation);
animation = aniTime = null;
networkElem.focus();
}
return new D3Widget(browseState, browseEvents);
}
},{"../../../../lib/log":223,"../../../../routes/browse":237,"../../../../services/namespace/service":248,"../../get-service-icon":148,"./index.css":185,"d3":32,"insert-css":37,"mercury":45}],187:[function(require,module,exports){
module.exports = ":root{}:root{}.bug-reporter{position:fixed;left:5px;bottom:12px;z-index:1000;}.bug-reporter .icon{opacity:0.75;color:rgba(0, 0, 0, 0.54);}.bug-reporter .icon::shadow #icon{width:16px;height:16px;}"
},{}],188:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var h = mercury.h;
var css = require('./index.css');
var BUG_REPORT_URL = 'https://github.com/vanadium/browser/issues/new';
var BUG_REPORT_ICON = 'bug-report';
module.exports = create;
module.exports.render = render;
module.exports.BUG_REPORT_URL = BUG_REPORT_URL;
module.exports.BUG_REPORT_ICON = BUG_REPORT_ICON;
function create() {}
function render() {
insertCss(css);
var reportBugAction = h('core-tooltip', {
'label': 'Report a bug or suggest features',
'position': 'right'
},
h('a', {
'href': BUG_REPORT_URL,
'target': '_blank'
}, h('paper-icon-button.icon', {
attributes: {
'icon': BUG_REPORT_ICON
}
}))
);
return h('div.bug-reporter', reportBugAction);
}
},{"./index.css":187,"insert-css":37,"mercury":45}],189:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var store = require('../../lib/store');
var log = require('../../lib/log')('debug');
module.exports = create;
module.exports.enableContinuousRendering = enableContinuousRendering;
function create() {
var state = mercury.varhash({
continuousRendering: mercury.struct({
/*
* Enables continuous rendering for debugging purposes.
*/
enabled: mercury.value(false),
/*
* Internal ticker that can be used to force state change.
*/
ticker: mercury.value(0)
})
});
watchContinuousRendering(state.get('continuousRendering'));
return {
state: state
};
}
/*
* Watches for changes to continuousRendering enabled state
*/
function watchContinuousRendering(state) {
var renderer;
mercury.watch(state.enabled, function(enabled) {
if (!enabled) {
clearInterval(renderer);
renderer = null;
return;
}
if (!renderer) {
log.warn('Continuous rendering is enabled.' +
' Use window.enableContinuousRendering(false) to disable');
// Add to ticker value every 16ms to cause state change and rerender
renderer = setInterval(function() {
state.ticker.set(state.ticker + 1);
}, 16);
}
});
// Load previous preference from store
store.getValue('continuousRendering').then(function(enabled) {
enabled = !!enabled; // Cast to bool
state.enabled.set(enabled);
}).catch(function() {
log.error('Could not get value of continuousRendering from store');
});
}
/*
* Enables continuous rendering for debugging purposes.
*/
function enableContinuousRendering(state, enabled) {
enabled = !!enabled; // Cast to bool
state.get('continuousRendering').enabled.set(enabled);
store.setValue('continuousRendering', enabled).catch(function() {
log.error('Could not save value of continuousRendering to store');
});
}
},{"../../lib/log":223,"../../lib/store":232,"mercury":45}],190:[function(require,module,exports){
module.exports = ":root{}:root{}.error-box-title{width:100%;font-size:1.2em;color:rgba(0, 0, 0, 0.54);}.error-box-details{width:100%;font-size:0.7em;color:rgba(0, 0, 0, 0.26);padding:0.2em;padding-top:1.25em;}.error-box{overflow:hidden;word-break:break-word;}.error-box-icon{padding-right:0.2em;margin-left:-0.2em;color:#D32F2F;}"
},{}],191:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var css = require('./index.css');
var h = mercury.h;
module.exports.render = render;
/*
* Renders an error in a box with details section
* @param message {string} errTitle short error title
* @param details {string} details Error details
*/
function render(errTitle, details) {
insertCss(css);
var titleView = h('div.error-box-title', [
h('core-icon.error-box-icon', {
attributes: {
icon: 'error'
}
}),
h('span', errTitle)
]);
var detailsView = h('div.error-box-details', h('span', details));
return h('div.error-box', [titleView, detailsView]);
}
},{"./index.css":190,"insert-css":37,"mercury":45}],192:[function(require,module,exports){
module.exports = ":root{}.error-page{padding:1em;}.error-page .error-box-title{font-size:1.4em;}.error-page .error-box-details{font-size:1.1em;}"
},{}],193:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var ErrorBox = require('./error-box/index');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
/*
* Help view
*/
function create() {
var state = mercury.struct({
/*
* Detailed description of error
* @type {string}
*/
message: mercury.value('')
});
return {
state: state
};
}
function render(state) {
insertCss(css);
var errorTitle = 'Something went wrong :(';
return h('div.error-page', ErrorBox.render(errorTitle, state.message));
}
},{"./error-box/index":191,"./index.css":192,"insert-css":37,"mercury":45}],194:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var helpRoute = require('../../routes/help');
var tabKeys = Object.freeze({
MAIN: 'main', // Describes the Vanadium Browser to new users.
VIEWS: 'views', // Defines service information and icons.
BROWSE: 'browse', // Introduces how to browse the namespace.
METHODS: 'methods', // Explains how to make RPCs.
SAMPLE: 'sample', // Sample world (house and cottage)
FAQ: 'faq' // Frequently asked questions and contact information.
});
var sections = Object.freeze(new Map([
[tabKeys.MAIN, {
index: 0,
header: 'Overview and Concepts',
markdownContent: require('./content/main.md'),
path: helpRoute.createUrl(tabKeys.MAIN)
}],
[tabKeys.VIEWS, {
index: 1,
header: 'What You See',
markdownContent: require('./content/views.md'),
path: helpRoute.createUrl(tabKeys.VIEWS)
}],
[tabKeys.BROWSE, {
index: 2,
header: 'Browse',
markdownContent: require('./content/browse.md'),
path: helpRoute.createUrl(tabKeys.BROWSE)
}],
[tabKeys.METHODS, {
index: 3,
header: 'Details and Methods',
markdownContent: require('./content/methods.md'),
path: helpRoute.createUrl(tabKeys.METHODS)
}],
[tabKeys.SAMPLE, {
index: 4,
header: 'Sample World',
markdownContent: require('./content/sample.md'),
path: helpRoute.createUrl(tabKeys.SAMPLE)
}],
[tabKeys.FAQ, {
index: 5,
header: 'FAQ',
markdownContent: require('./content/faq.md'),
path: helpRoute.createUrl(tabKeys.FAQ)
}]
]));
module.exports = {
tabKeys: tabKeys,
sections: sections
};
},{"../../routes/help":240,"./content/browse.md":195,"./content/faq.md":196,"./content/main.md":197,"./content/methods.md":198,"./content/sample.md":199,"./content/views.md":200}],195:[function(require,module,exports){
module.exports = "<p>In Browse mode, the left pane is used to browse the current namespace.</p>\n<p>There are three views for browsing: Tree, Radial and Grid.\nAs discussed in the <a href=\"#/help/main\">Overview and Concepts</a> tab,\na Vanadium name consists of a list of mounted names separated by slashes.\nAll views show a set of <em>items</em>, and in all views each item includes a\nmounted name and an icon.</p>\n<h2 id=\"item-icons\">Item icons</h2>\n<p>If the icon for an item is a square\n<img src=\"helpimg/square.png\" style=\"border:none\" />,\nthen the item represents a mount point in a mount table.\nIf the icon is a circle\n<img src=\"helpimg/circle.png\" style=\"border:none\" />,\nthen the item points at a service.\nIf the icon includes both a square and a circle\n<img src=\"helpimg/squarecircle.png\" style=\"border:none\" />,\nthen the name both represents a mount point and it also points at a service.\nIf the namespace browser cannot access the name\n(typically because of permissions), then the icon indicates an error\n<img src=\"helpimg/inaccessible.png\" style=\"border:none\" />.</p>\n<p>Put another way, the mount point represents the mounted name itself,\nand the service represents what the name points to.\nThis is significant because permissions (such as Access Control Lists)\ncan be set both on names (mount points) and on services.</p>\n<p>In any view, you can select an item to show details for it in the right pane.\nThe right pane will contain one or two tabs, depending on whether the selected\nitem represents a mount point, has a pointer to a service, or both.</p>\n<h2 id=\"tree-view\">Tree view</h2>\n<p>Tree view browses a namespace as a hierarchy.\nThe tree view shows each item on a separate line.\nEach item consists of an arrow, an icon, and a mounted name.</p>\n<p><img src=\"helpimg/tree.png\" alt=\"Tree View\"></p>\n<p>The arrow is used to expand and collapse the children of the item.\nItems that cannot have children do not show an arrow.\nClick on a right-pointing arrow to expand its children.\nIf the arrow changes to a dash (&mdash;)\nthen the item currently does not have any children\n(or has children that the current user does not have permission to view).</p>\n<p>Because an item&#39;s children may be distributed across multiple devices,\nit may take a moment before the children appear.\nA loading icon is shown circling the arrow while children are still loading.</p>\n<p>The icon is discussed above.</p>\n<h2 id=\"radial-view\">Radial view</h2>\n<p>Radial view browses a namespace as items radiating out from the root,\nusing a circular network graph with nodes and edges.\nThe nodes are shown as the icons for each item (square and/or circle).\nThe edges are shown as curved lines.</p>\n<p><img src=\"helpimg/radial.png\" alt=\"Radial view\"></p>\n<p>You can click on a node to select it.\nYou can double-click on the node to expand its children (if any).\nYou can expand a whole level of the graph (children, grandchildren, etc.)\nby clicking repeatedly on the expand widget\n<img src=\"helpimg/unfold-more.png\" style=\"border:none\" />.\nThe node blinks while children are loading.</p>\n<p>You can interact with the visualization using the five widget buttons,\nby right-clicking on a node to see a context menu,\nor using keyboard shortcuts:</p>\n<p><style>\nthead td { font-weight: bold; font-size: 1.1em; border-bottom: solid gray 1px; }\ntable tr:nth-child(even) { background-color: rgba(220, 220, 220, 0.8); }\ntd.big { font-size: 1.2em; }\ntd:nth-child(1), td:nth-child(2), td:nth-child(3), td:nth-child(4) { text-align: center; }\ntd:nth-child(5) { padding-left: 5px; }\n</style></p>\n<table>\n <thead>\n <tr><td>Widgets</td><td>Context menu</td><td>Keyboard shortcut</td><td>Other</td><td>Description</td></tr>\n </thead>\n <tr><td></td><td></td><td>Shift + arrow keys</td><td>click on node</td><td>select item</td></tr>\n <tr><td></td><td></td><td>arrow keys</td><td>drag with mouse</td><td>move visualization</tr>\n <tr><td class=\"big\">+ &minus;</td><td></td><td>+ &minus;</td><td>mouse scrollwheel</td><td>zoom</td></tr>\n <tr><td class=\"big\">&#8634; &#8635;</td><td></td><td>PageUp PageDown</td><td>Shift + scrollwheel</td><td>rotate</td></tr>\n <tr><td><img src=\"helpimg/unfold-more.png\" style=\"border:none\"></td><td>Load +1 Level</td><td>space bar</td><td>Shift + double-click</td><td>load 1 additional level, from selection</tr>\n <tr><td></td><td>Browse Into</td><td>Shift + space bar</td><td>breadcrumbs</td><td>change current root to selection</tr>\n <tr><td></td><td>Expand/Collapse</td><td>Return</td><td>double-click</td><td>expand/collapse immediate children</tr>\n <tr><td></td><td>Show Loaded</td><td>Shift + Return</td><td></td><td>show all loaded children</tr>\n <tr><td></td><td>Center Selected</td><td>End</td><td></td><td>center selected node</tr>\n <tr><td></td><td>Center Root</td><td>Home</td><td></td><td>reset rotate and zoom</td></tr>\n</table>\n\n<h2 id=\"grid-view\">Grid view</h2>\n<p>Grid view shows a set of items, typically the children of an item.</p>\n<p><img src=\"helpimg/grid.png\" alt=\"Grid view\"></p>\n<p>The blue name (<code>identity</code>) is the parent of the items.</p>\n<p>Unlike the tree view, in the grid view the arrow is shown on the right\nside of the item.\nIf an item does not include an arrow, then it cannot have children.</p>\n<p>Click on the arrow for an item to show its children (if any),\nor click on the &quot;browse into&quot; widget\n<img src=\"helpimg/browseInto.png\" alt=\"Browse into\"> in the right pane to display\nthe children of the currently selected item.\nYou can also use the breadcrumbs to move up and down the hierarchy.</p>\n<p>Grid view is also used for Bookmarks and Recent, and to show the results\nof a search.</p>\n<p>&nbsp;</p>\n"
},{}],196:[function(require,module,exports){
module.exports = "<h2 id=\"how-can-i-report-bugs-or-suggest-features-\">How can I report bugs or suggest features?</h2>\n<p>Visit us on github to make suggestions and report bugs.</p>\n<p><a href=\"https://github.com/vanadium/browser/issues/new\">https://github.com/vanadium/browser/issues/new</a></p>\n<h2 id=\"how-can-i-contribute-to-the-namespace-browser-\">How can I contribute to the namespace browser?</h2>\n<p>Read the contributing instructions here:\n<a href=\"https://vanadium.github.io/community/contributing.html\">https://vanadium.github.io/community/contributing.html</a></p>\n"
},{}],197:[function(require,module,exports){
module.exports = "<p>The namespace browser is a tool to browse Vanadium namespaces\nand interact with Vanadium services.</p>\n<h2 id=\"names\">Names</h2>\n<p>Vanadium names identify objects in a namespace (similar to how URLs identify\nobjects on the web). In Vanadium, the objects are all <em>services</em> on <em>servers</em>.\nSee <a href=\"https://vanadium.github.io/concepts/naming.html\">the Naming concepts\ndocument</a> for\nmore information.</p>\n<p>Names in Vanadium are a sequence of simple name components –\ncalled <em>mounted names</em> – separated by slashes (/).\nThe process of using a Vanadium name to find a service on a server is\ncalled <em>name resolution</em>.\nA name is resolved by special servers called <em>mount tables</em>,\nand (optionally) by (all) servers using something called a <em>dispatcher</em>.\nNames are resolved from left to right.</p>\n<p>For example, the Vanadium name <code>User/jane/images/vacation/42.jpg</code>\ncould be used to access a photo on an image storage server.\nOne or more mount tables would be traversed to find the <code>images</code> server,\nwhose dispatcher would then be used to find the <code>vacation</code> photo named <code>42.jpg</code>.\nA <em>method</em> can then be called on this object; for example,\n<code>User/jane/images/vacation/42.jpg.Get()</code> might return the image,\nor <code>Delete()</code> might delete it.</p>\n<h2 id=\"mount-tables\">Mount tables</h2>\n<p>A <em>mount table</em> is a kind of Vanadium server used to find other services.\nA mount table contains a set of <em>mount points</em>, which map names into distributed\npointers to other services (including to other mount tables).\nAn interconnected set of mount tables forms a Vanadium <em>namespace</em>.</p>\n<p>Like other Vanadium servers, a mount table has a dispatcher that is\nused to help resolve names. In the above example the name\n<code>User/jane/images</code> may have been created in more than one way.</p>\n<p><img src=\"helpimg/name2.png\" alt=\"Two mount tables\"></p>\n<p>In this figure <code>User</code> resolves to a mount table that\ncontains a mount point named <code>jane</code>. This mount point then points\nto another mount table (possibly on another device)\nthat contains a mount point named <code>images</code>.</p>\n<p><img src=\"helpimg/name1.png\" alt=\"Single mount table\"></p>\n<p>Alternatively, in this figure the <code>User</code> mount table contains a mount point named\n<code>jane</code> that does not have a distributed pointer associated with it.\nSuch a name can point only to other mount points in the same mount table.\nIn this case, it points to a single name <code>images</code>, which does contain a\ndistributed pointer to the server.</p>\n<p>One way to think about this second situation is that the mount point\nnamed <code>jane/images</code> points directly to the image store server.\nEven though the name <code>jane/images</code> contains a slash, it is resolved\nby the mount table dispatcher to a single distributed pointer.</p>\n<p>Another way to think about this is that a mount table can contain <em>subtables</em>,\nso <code>User/jane</code> represents a subtable in the <code>User</code> mount table. These subtables\nare used to group objects together (like directories in a file system on a computer).\nFor example, the User mount table could also contain <code>jane/movies</code>.</p>\n<p>Note that even though Vanadium names look hierarchical, namespaces can\n(and often do) contain cycles. A mount table could even contain a mount point\nthat points directly to the same mount table.\nIn addition, more than one mount point in different mount tables can point to\nthe same server (including to mount tables), so the same service can be accessed\nvia more than one name.</p>\n<h2 id=\"rooted-and-relative-names\">Rooted and relative names</h2>\n<p>Names in Vanadium can either be <em>rooted</em> or <em>relative</em>.\nA rooted name begins with a slash (/), while a relative name does not.</p>\n<h2 id=\"rooted-names\">Rooted names</h2>\n<p>The name following the (required) initial slash of a rooted name is the <em>root</em>,\nand always points to a service (often a mount table).\nA root is specified in one of three ways:</p>\n<ol>\n<li>using a (DNS) domain name (typically with an optional port number),\nlike &quot;ns.dev.v.io:8101&quot; or &quot;localhost:5167&quot;,</li>\n<li>using an IP address (also with an optional port number), like &quot;127.0.0.1:5167&quot;\n(the IP address can use either IPv4 or IPv6 format),</li>\n<li>or a Vanadium endpoint address for a mount table, which will look something like\n&quot;@3@@batman.com:2345@00000000000000000000000000000000@2@3@s@@&quot;.</li>\n</ol>\n<h2 id=\"relative-names\">Relative names</h2>\n<p>A relative name does not begin with a slash.\nThe meaning of a relative name depends on a root stored in the user&#39;s environment\n(this is similar to the concept of a &quot;current directory&quot;, except it can\nbe on a different device).</p>\n<p>For example, each user can have their own mount table where they store things\nthey own. This mount table can contain names like &quot;phone/messages&quot; that\ncould be used to access the messages on their mobile phone.\nDifferent users (or devices) would normally have a different default root,\nso they would access their own messages.</p>\n<h2 id=\"identity\">Identity</h2>\n<p>In Vanadium, mount tables (and thus names) are by default secure.\nWhat names are accessible to a user depend on the identity of the user, and\nthe services (including mount tables) to which the user has been given access.</p>\n<h2 id=\"help-topics\">Help topics</h2>\n<ul>\n<li><p><a href=\"#/help/views\">What You See</a> –\nthe visible parts of the namespace browser and what they do.</p>\n</li>\n<li><p><a href=\"#/help/browse\">Browse</a> – how to browse a namespace,\nincluding the different views provided by the namespace browser.</p>\n</li>\n<li><p><a href=\"#/help/methods\">Details and Methods</a> – how to find details, such as\npermissions on names. For services, how to invoke methods.</p>\n</li>\n<li><p><a href=\"#/help/sample\">Sample World</a> – a sample namespace for you to\nexplore and manipulate.</p>\n</li>\n<li><p><a href=\"#/help/faq\">FAQ</a> – answers to frequently asked questions.</p>\n<p>&nbsp;</p>\n</li>\n</ul>\n"
},{}],198:[function(require,module,exports){
module.exports = "<p>When you select an item in any of the Browse views (Tree, Radial, or Grid),\ndetails for that item appear in the right pane.\nFor the item named <code>applications</code>, the right pane has a header and\na set of tabs that look like this:</p>\n<p><img src=\"helpimg/detailsheader.png\" alt=\"Details header\"></p>\n<p>On the left side between the header and the tabs is a widget\n<img src=\"helpimg/hide.png\" alt=\"hide\"> that hides the right pane.\nYou can also adjust the size of the right pane by dragging the\nline that separates the left and right panes.</p>\n<p>The header displays the mounted name of the selected item and two widgets:\n<img src=\"helpimg/bookmark.png\" alt=\"bookmark\"> to set a bookmark on the selected item, and\n<img src=\"helpimg/browseinto.png\" alt=\"browse into\"> to browse into the selected item\n(make it the root of the current view).\nIf this item is already bookmarked, the bookmark widget looks like\n<img src=\"helpimg/bookmarked.png\" alt=\"bookmarked\"> and you can click on it to remove the bookmark.\nWhen you browse into an item, the browse into widget changes to\n<img src=\"helpimg/revert.png\" alt=\"browse up\">, and you can click on it to undo\n(revert the view back up to the previous item).</p>\n<p>The <code>applications</code> item has two tabs, because it has a mount point and\nit also points to a service.</p>\n<h2 id=\"mountpoint-tab\">MountPoint tab</h2>\n<p>The MountPoint tab shows details about the mount point associated\nwith this item:</p>\n<p><img src=\"helpimg/mountpoint.png\" alt=\"MountPoint details\"></p>\n<p>The &quot;Full Name&quot; shows the full path used to access this item.\nThe &quot;Mount Point Object Addresses&quot; is a set of resolved names\nfor this item. This can be the same as the Full Name,\nor can be multiple names.</p>\n<p>&quot;Permissions&quot; shows all permissions set on this mount point.\nRecall that an item can have permissions set on both the name,\nand what the name points to.\nSee <a href=\"https://vanadium.github.io/concepts/security.html\">the Security concepts document</a>\nfor information about permissions.</p>\n<h2 id=\"service-tab\">Service tab</h2>\n<p>The Service tab shows details about the Vanadium service pointed to by this name:</p>\n<p><img src=\"helpimg/service.png\" alt=\"Service details\"></p>\n<p>The &quot;Full Name&quot; shows the full path used to access this item\n(same as in the MountPoint tab).\nThe &quot;Service Object Addresses&quot; is a set of resolved names\n(object addresses) for the service pointed to by this item.\nIn this case it is a single endpoint.\nThe &quot;Remote Blessings&quot; is the security blessing the service\nis running under.</p>\n<p>Next is a set of interfaces that are supported by this service.\nFor each interface, the first line shows the name of the interface\n(from the VDL file used to define the service),\nan information widget\n<img src=\"helpimg/info.png\" alt=\"information\">,\nand an arrow\n<img src=\"helpimg/right.png\" alt=\"show/hide methods\">\nto show or hide the methods associated with this interface.\nHover over the information widget to see the documentation for that\ninterface (from the source code).</p>\n<p>Finally, for each interface you can invoke methods\nto examine or change the state of the service,\nand see output from method calls. If you have not called any methods,\nthen &quot;Output&quot; will show &quot;No method output&quot;.</p>\n<p>If the methods for an interface are showing, you can hover over the\nmethod name to see the documentation for that method from the source code.\nFor example, here is the documentation for the Remove method of the\napplications service:</p>\n<p><img src=\"helpimg/RemoveMethod.png\" alt=\"Remove method\"></p>\n<p>All Vanadium services implement the &quot;__Reserved&quot; interface, which includes\nmethods for introspection and searching.\nBy default, the methods for this interface are not displayed,\nbut you can click the\n<img src=\"helpimg/right.png\" alt=\"show methods\"> icon to show (and even invoke) its methods.</p>\n<h2 id=\"invoking-methods-on-services\">Invoking methods on services</h2>\n<p>Each service has one or more methods associated with it.\nYou can call these methods if you have the proper permissions.\nHere are the methods for the alarm service from the Sample World:</p>\n<p><img src=\"helpimg/alarm.png\" alt=\"Alarm methods\"></p>\n<p>If a method does not take any arguments\n(e.g., the Arm, Panic, Status and Unarm methods),\nthen you can invoke it by clicking on the\n<img src=\"helpimg/noargs.png\" alt=\"No arguments\"> icon.</p>\n<p>For example, click on the\n<img src=\"helpimg/noargs.png\" alt=\"No arguments\"> icon for the\nStatus method, then the Arm method, and then the Status method again.\nThe Output will look like:</p>\n<p><img src=\"helpimg/output1.png\" alt=\"Output\"></p>\n<p>This shows (from the bottom up) that the alarm is initially not armed,\nuntil after you click on the Arm method.</p>\n<h2 id=\"invoking-methods-with-arguments\">Invoking methods with arguments</h2>\n<p>If a method takes arguments, then the name of the method\nis followed by &quot;(...)&quot; and you click on the\n<img src=\"helpimg/right.png\" alt=\"arguments\"> icon to supply the arguments.\nFor example, if you click on the icon for the DelayArm(...) method,\nyou get this:</p>\n<p><img src=\"helpimg/delayarm.png\" alt=\"DelayArm method\"></p>\n<p>The documentation for the method is shown if you hover over the method.\nThis shows that the argument to DelayArm is a floating point number\nthat specifies a number of seconds to delay before arming the alarm.</p>\n<p>Type the number 2 into the &quot;seconds float(32)&quot;&quot; field and hit the &quot;Run&quot; button.\nIf the alarm is unarmed, after two seconds it will arm.</p>\n<p>Arguments are remembered between calls, but\nif you think you will call a method more than once with different sets of arguments,\nyou can also click the &quot;Save&quot; button. This saves the arguments like this:</p>\n<p><img src=\"helpimg/savedarg.png\" alt=\"Save arguments\"></p>\n<p>Click the\n<img src=\"helpimg/noargs.png\" alt=\"saved arguments\"> icon to invoke the method with the\nsaved arguments. You can also click the star to delete these saved arguments.\nYou can create as many sets of saved arguments as you want for each method.\nAlso note that saved arguments carry over to other services of the\nsame type.</p>\n<h2 id=\"mount-tables-as-services\">Mount tables as services</h2>\n<p>A mount table is also a service. The methods for a mount table allow you\nto call methods on a mount table (e.g., to Mount and Unmount items),\nassuming you have the proper permissions on the mount table.</p>\n<p>&nbsp;</p>\n"
},{}],199:[function(require,module,exports){
module.exports = "<p>Sample World is a sample namespace that allows you to experiment\nwith the Namespace Browser:</p>\n<p><img src=\"helpimg/sample-world.gif\" alt=\"Sample world radial view\"></p>\n<p>To enable the Sample World demo, visit <a href=\"/#/demo\">/#/demo</a> or pick\n&quot;Sample World Demo&quot; from the side navigation menu.</p>\n<p>You can browse through the Sample World namespace, and call methods.</p>\n<p>The Sample World represents two homes, called &quot;house&quot; and &quot;cottage&quot;,\nwhich both contain home automation to turn lights on and off,\narm and disarm alarms, play music, water the lawn, check the\nsmoke alarms, and feed the pet. The included (robotic) pet tests\nyour ability to keep it well fed and happy.</p>\n<p><img src=\"helpimg/sampletree.png\" alt=\"Sample world tree view\"></p>\n<p>The code for the Sample World services can be found on\n<a href=\"https://github.com/vanadium/browser/tree/master/src/services/sample-world\">Github</a>.</p>\n<p>&nbsp;</p>\n"
},{}],200:[function(require,module,exports){
module.exports = "<p><img src=\"helpimg/views.png\" alt=\"The Namespace Browser\"></p>\n<p>When you first open the namespace browser it has four main areas.\nAt the very top is the header (in cyan)\nand immediately below it is the toolbar (in light gray).</p>\n<p>In Browse mode, the remainder of the page is divided into two panes.\nThe left pane shows the view of the namespace for you to browse.\nIf you select an item in the left pane, the right pane shows details\nabout that item and (if it is a service) lets you call methods on it.</p>\n<h2 id=\"header\">Header</h2>\n<p><img src=\"helpimg/header.png\" alt=\"Header\"></p>\n<p>Starting from the left, the header contains a widget\n<img src=\"helpimg/menuicon.png\" alt=\"menu icon\">\nto bring up a menu drawer for changing modes.\nThe current mode (in this case, Browse) is displayed next.\nThere are other modes for starting the <a href=\"#/help/sample\">Sample World Demo</a>,\nviewing the Help pages, and submitting bugs/suggestions.</p>\n<p>In Browse mode, the header also shows the Vanadium name being used\nas the root of the current view.\nYou can type an arbitrary Vanadium name into this field to browse it.\n(For additional ways to change the root of the view, see the next section\non the toolbar).\nIf this field is empty, it defaults to the Home mount table for the\ncurrent environment (the root of relative names).</p>\n<p>For example, type in &quot;/ns.dev.v.io:8101/identity&quot; to this field (and hit return)\nto set the identity mount point to be the root of the current view.\nAlso clear out this field (and hit return) to see what happens.\nCan you tell what your default root is for relative names?</p>\n<p>The icon\n<img src=\"helpimg/reload.png\" alt=\"reload icon\">\nin front of this name is used to reload the browser.\nThe Namespace Browser does not automatically update when namespaces\nchange (because they may be distributed across remote machines).</p>\n<p>Finally, on the right side of the header is a widget\n<img src=\"helpimg/usericon.png\" alt=\"user account\">\nfor the current identity.\nHover over this widget to see the account name for the current user.\nThis is by default the identity used to sign into the web browser\nrunning the Namespace Browser webapp.</p>\n<h2 id=\"toolbar\">Toolbar</h2>\n<p><img src=\"helpimg/toolbar.png\" alt=\"Toolbar\"></p>\n<p>The left side of the toolbar contains three icons for the views\nshown in the left pane:</p>\n<ol>\n<li>Tree view (selected) shows items in a hierarchical tree.</li>\n<li>Radial view shows a visualization of the namespace,\ngood for getting an overview.</li>\n<li>Grid view shows items as individual objects.\n<br /><br /></li>\n</ol>\n<p>Next is a list of (slash separated) names showing\nwhat is being browsed, commonly called &quot;breadcrumbs&quot;.\nThe breadcrumbs start with the root name (for rooted names),\nand end at the currently selected node (if any).</p>\n<p>In the above figure, the breadcrumbs show three names:</p>\n<ol>\n<li><code>ns.dev.v.io:8101</code> is the root name (in grey).</li>\n<li><code>identity</code> is the root of the current view.</li>\n<li><code>role</code> is the currently selected item.\n<br /><br /></li>\n</ol>\n<p>The first breadcrumb shown in black (<code>identity</code>) is the root of the current view.\nYou can click on any name in the breadcrumbs to change the root of the current\nview, which makes it easy to navigate up and down a Vanadium name.</p>\n<p>Next there are two icons for Bookmarks\n<img src=\"helpimg/bookmarks.png\" alt=\"bookmarks\">\nand Recent\n<img src=\"helpimg/recent.png\" alt=\"recent\">.</p>\n<p>The bookmarks icon shows a set of bookmarked items.\nYou can set a bookmark for any item so you can access it quickly in the future.</p>\n<p>Recent shows items you have browsed recently.</p>\n<p>Lastly, you can use glob syntax to search for items.\nFor example, you are in a namespace that represents a house.\nUnder the house namespace are a number of rooms\n(bedroom, kitchen, living room, etc.) and under each room are things like\nlights, smoke detectors, thermostats, and speakers.\nTo search for the lights in all rooms, you could search for &quot;*/lights&quot;.\nNote that each glob (asterisk) only matches a single level in names.</p>\n<p>&nbsp;</p>\n"
},{}],201:[function(require,module,exports){
module.exports = ":root{}.markdown{padding:0.5em;}.markdown p{margin:0 0 0.5em 0;}.markdown h1{text-align:center;}.markdown h2{margin-top:0.75em;margin-bottom:0.25em;}.markdown ul,.markdown ol{padding-left:2em;}.markdown ul li{list-style:disc outside none;}.markdown ol li{list-style:decimal outside none;}.markdown img{border:solid black 1px;}.markdown a{text-decoration:none;color:#00838F;}.markdown a:hover,.markdown a:focus{color:#0097A7;}"
},{}],202:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var h = mercury.h;
var insertCss = require('insert-css');
var css = require('./index.css');
var constants = require('./constants.js');
var tabKeys = constants.tabKeys;
var sections = constants.sections;
module.exports = create;
module.exports.render = render;
/*
* Help view
*/
function create() {
var state = mercury.varhash({
selectedTab: mercury.value(tabKeys.MAIN)
});
var events = mercury.input([
'error', // Will be wired up by the application.
'navigate' // Will be wired up by the application.
]);
return {
state: state,
events: events
};
}
/*
* Draws the help page, which consists of a tabbed layout and the selected tab's
* help content. Content comes from a parsed markdown file.
*/
function render(state, events) {
insertCss(css);
// Render each help tab, as defined by the sections.
var tabs = [];
sections.forEach(function(section, key) {
var tab = h('paper-tab.tab', {
'tabKey': key,
'ev-click': mercury.event(events.navigate, {
'path': section.path
})
}, section.header);
tabs.push(tab);
});
// Show the tabs followed by the content of the selected help tab.
return [
h('paper-tabs.tabs', {
attributes: {
'selectedProperty': 'tabKey',
'selected': sections.get(state.selectedTab).index,
'noink': true
}
}, tabs),
h('.tab-content.core-selected', h('.markdown', {
'innerHTML': sections.get(state.selectedTab).markdownContent
}))
];
}
},{"./constants.js":194,"./index.css":201,"insert-css":37,"mercury":45}],203:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var sections = require('./constants').sections;
module.exports = selectTab;
/*
* Exported function that sets the given state to the given tabKey.
* If there is an error, however, the error event is run.
*/
function selectTab(state, events, tabKey) {
// If the tab is invalid, go to the error page.
if (sections.get(tabKey) === undefined) {
//TODO(aghassemi) Needs to be 404 error when we have support for 404
events.error(new Error('Invalid help page: ' + tabKey));
} else {
// Since the tabKey is valid, the selectedTab can be updated.
state.selectedTab.set(tabKey);
}
}
},{"./constants":194}],204:[function(require,module,exports){
module.exports=require(170)
},{}],205:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var Browse = require('../browse/index');
var Help = require('../help/index');
var ErrorPage = require('../error/index');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
module.exports.renderHeader = renderHeader;
/*
* MainContent part of the layout
*/
function create() {}
function renderHeader(state, events) {
var pageKey = state.navigation.pageKey;
switch (pageKey) {
case 'browse':
return Browse.renderHeader(
state.browse,
events.browse,
events.navigation
);
default:
return null;
}
}
function render(state, events) {
insertCss(css);
return [
h('div.main-container', renderContent(state, events))
];
}
function renderContent(state, events) {
var pageKey = state.navigation.pageKey;
switch (pageKey) {
case 'browse':
return Browse.render(state.browse, events.browse, events.navigation);
case 'help':
return Help.render(state.help, events.help);
case 'error':
return ErrorPage.render(state.error);
default:
// We shouldn't get here with proper route handlers, so it's an error(bug)
throw new Error('Could not find page ' + pageKey);
}
}
},{"../browse/index":150,"../error/index":193,"../help/index":202,"./index.css":204,"insert-css":37,"mercury":45}],206:[function(require,module,exports){
module.exports = ":root{}:root{}.nav-item.core-selected,.nav-item.core-selected /deep/ core-icon{color:#00838F;}.nav-item /deep/ core-icon{color:rgba(0, 0, 0, 0.54);}.nav-item{margin:0.75em;}.nav-item:hover,.nav-item:focus{background-color:rgba(236, 239, 241, 0.8);}"
},{}],207:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var browseRoute = require('../../routes/browse');
var helpRoute = require('../../routes/help');
var demoRoute = require('../../routes/demo');
var BugReport = require('../bug-report/index');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
/*
* Sidebar part of the layout
*/
function create() {}
function render(state, events) {
return [
h('core-menu', {
'selected': state.navigation.pageKey,
'valueattr': 'itemKey'
},
renderNavigationItems(events)
)
];
function renderNavigationItems() {
var navigationItems = [{
key: 'browse',
label: 'Browse',
icon: 'explore',
href: browseRoute.createUrl(state.browse)
}, {
key: 'demo',
label: 'Sample World Demo',
icon: 'av:play-circle-fill',
href: demoRoute.createUrl()
}, {
key: 'help',
label: 'Help',
icon: 'help',
href: helpRoute.createUrl()
}, {
key: 'bug',
label: 'Report a bug',
icon: BugReport.BUG_REPORT_ICON,
href: BugReport.BUG_REPORT_URL,
newWindow: true
}];
insertCss(css);
return navigationItems.map(function createMenuItem(navItem) {
return h('core-item.nav-item', {
'itemKey': navItem.key,
'icon': navItem.icon,
'label': navItem.label
}, [
h('a', {
'target': (navItem.newWindow ? '_blank' : undefined),
'href': navItem.href,
'ev-click': [
mercury.event(events.navigation.navigate, {
path: navItem.href
}),
mercury.event(events.viewport.closeSidebar)
]
})
]);
});
}
}
},{"../../routes/browse":237,"../../routes/demo":238,"../../routes/help":240,"../bug-report/index":188,"./index.css":206,"insert-css":37,"mercury":45}],208:[function(require,module,exports){
module.exports = ":root{}:root{}.user-icon{position:absolute;right:0.5em;top:1em;color:#ffffff;}.user-account{font-size:1.2em;}"
},{}],209:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var namespaceService = require('../../services/namespace/service');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
/*
* User Account
*/
function create() {
var state = mercury.struct({
/*
* User's account name
* @type {string}
*/
accountName: mercury.value('')
});
namespaceService.getAccountName().then(function(accountName) {
state.accountName.set(accountName);
});
return {
state: state
};
}
function render(state) {
insertCss(css);
return h('core-tooltip.user-icon', {
attributes: {
tipAttribute: 'usertip',
position: 'left'
}
}, [
h('div', {
attributes: { 'usertip': true }
},
h('span.user-account', 'Account name: ' + state.accountName)
),
h('core-icon', {
icon: 'account-box'
})
]
);
}
},{"../../services/namespace/service":248,"./index.css":208,"insert-css":37,"mercury":45}],210:[function(require,module,exports){
module.exports = "*{margin:0;padding:0;font-weight:normal;text-decoration:none;border:none;list-style:none;vertical-align:baseline;color:inherit;}:root{}:root{}.screen-reader{position:absolute;top:-1000px;left:-1000px;width:0px !important;height:0px !important;}:root{}:root{}.tabs{box-shadow:0px 3px 2px rgba(0, 0, 0, 0.2);}.tabs::shadow #selectionBar{background-color:#00838F;height:3px;}.tab{background-color:#ffffff;color:rgba(0, 0, 0, 0.87);}.tab::shadow #ink{color:#FF6E40;}.tab-content{padding:0.5em;}paper-spinner{margin:0.5em;}::shadow paper-input-decorator{padding:0;}::shadow paper-input-decorator /deep/ #focusedUnderline{background-color:#FF6E40;}paper-progress{width:100%;height:4px;}paper-progress.delayed{-webkit-animation:delayed-progressbar 0.5s;}@-webkit-keyframes delayed-progressbar{0%{visibility:hidden;}99%{visibility:hidden;}100%{visibility:visible;}}paper-progress::shadow #activeProgress{background-color:#FF6E40;}paper-progress::shadow #progressContainer{background-color:transparent;}paper-button{background-color:#00838F;color:#ffffff;margin:0.5em;}paper-button.secondary{background-color:#ffffff;color:#00838F;}paper-button::shadow .button-content{padding-top:0.35em;padding-bottom:0.35em;}paper-button > core-icon{margin-right:0.5em;}::shadow /deep/ paper-spinner::shadow .circle,paper-spinner::shadow .circle{border-color:#FF6E40;border-width:2px;}.empty{width:100%;padding:1em;text-align:center;color:rgba(0, 0, 0, 0.54);}.right-justify{direction:rtl;overflow:hidden;}.grayed-out,tree-node.grayed-out::shadow .item{opacity:0.5;}.margin-left-xxsmall{margin-left:0.2em;}core-header-panel{height:100%;}core-tooltip::shadow .core-tooltip{transition:visibility 0s;}core-tooltip[focused]::shadow .core-tooltip,core-tooltip:hover:not([disabled])::shadow .core-tooltip{transition-delay:0.5s;}body{font-family:'Roboto', sans-serif;color:rgba(0, 0, 0, 0.87);background-color:#ffffff;}.title{font-size:1.1em;color:#ffffff;}.drawer .toolbar{background-color:#00838F;}.toolbar{background-color:transparent;}.panel .drawer{background-color:#ffffff;}.drawer-toggle{color:#ffffff;}div.toasts{left:0;bottom:0;position:fixed;}paper-toast{min-height:0;position:relative;display:block;margin-bottom:0.5em;}paper-toast::shadow .toast-text{vertical-align:middle;font-family:'Roboto', sans-serif;padding:1em 1em;}paper-toast.info::shadow .toast-text{color:#ffffff;}paper-toast.error::shadow .toast-text{color:#D32F2F;}paper-toast.ok::shadow .toast-text,paper-toast::shadow .toast-text.toast-action{color:#388E3C;}core-header-panel::shadow #mainPanel{background-color:#ffffff;}"
},{}],211:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var insertCss = require('insert-css');
var Sidebar = require('../sidebar/index');
var MainContent = require('../main-content/index');
var ReportBug = require('../bug-report/index');
var UserAccount = require('../user-account/index');
var css = require('./index.css');
var h = mercury.h;
module.exports = create;
module.exports.render = render;
module.exports.setSplashMessage = setSplashMessage;
/*
* Page level layout of the application
*/
function create() {
var state = mercury.varhash({
/*
* Whether the sidebar drawer is visible
* @type {boolean}
*/
sidebarOpened: mercury.value(false),
/*
* Title text to display in the toolbar
* @type {string}
*/
title: mercury.value(''),
/*
* Toast messages to display
* @type {Array<Object>}
*/
toasts: mercury.array([])
});
var events = mercury.input([
'openSidebar',
'closeSidebar',
'deferRemoveToast',
]);
wireUpEvents(state, events);
return {
state: state,
events: events
};
}
/*
* Draw the full page of the application, which consists of a sidebar and main
* panel. The sidebar is usually hidden but acts as a selector for the content
* shown in the main panel. This content is rendered in the full browser window.
*
* See @app.js for the state definition. See @sidebar/index.js and
* @main-content/index.js for their rendering functions.
*/
function render(state, events) {
if (!state.initialized) {
return h('div');
} else {
removeSplashScreen();
}
insertCss(css);
if (!state.navigation.pageKey) {
return mercury.h('paper-spinner', {
attributes: {
'active': true,
'aria-label': 'Loading'
}
});
}
var panelAttributes = {
attributes: {
// Keep the drawer collapsed for any width size
'responsiveWidth': '10000px',
'selected': state.viewport.sidebarOpened ? 'drawer' : 'main'
},
// If drawer is open, clicking anywhere should close it
'ev-click': (state.viewport.sidebarOpened ?
mercury.event(events.viewport.closeSidebar) : null),
};
return h('core-drawer-panel.panel', panelAttributes, [
h('core-header-panel.drawer', {
attributes: {
'drawer': true
}
}, [
renderSideToolbar(state, events),
Sidebar.render(state, events)
]),
h('core-header-panel.main', {
attributes: {
'main': true
}
}, [
renderMainToolbar(state, events),
MainContent.render(state, events),
renderToasts(state, events),
ReportBug.render()
])
]);
}
/*
* The title of the sidebar.
*/
function renderSideToolbar(state, events) {
return h('core-toolbar.toolbar', [
h('h1.title', 'Vanadium Namespace Browser')
]);
}
/*
* The title of the main content.
*/
function renderMainToolbar(state, events) {
return h('core-toolbar.toolbar', [
h('paper-icon-button.drawer-toggle', {
attributes: {
'icon': 'menu'
},
'id': 'drawerToggle',
'ev-click': mercury.event(events.viewport.openSidebar)
}),
h('h2.title', state.viewport.title),
MainContent.renderHeader(state, events),
UserAccount.render(state.userAccount)
]);
}
/*
* Draws all the toasts stored in the state. Old toasts remain hidden.
*
* TODO(alexfandrianto): In order to limit mercury state, we attempt to purge
* state.viewport.toasts. core-overlay-close-completed isn't always fired if
* too many occur in the same time range, so setTimeout upon core-overlay-open-
* completed works to solve that.
* TODO(alexfandrianto): Try to get autoCloseDisabled accepted by Polymer so
* that the paper-toast behavior is more consistent.
*/
function renderToasts(state, events) {
return h('div.toasts', state.viewport.toasts.map(function(toast) {
return renderToast(toast, events);
}));
}
/*
* Draws a short duration toast to inform the user.
*/
var toastDuration = 3000; // ms
function renderToast(toast, events) {
// The toast type affects the css class
var cssClass = toast.type || 'info';
// If there is an event attached to the toast, draw it here.
var children = [];
if (toast.actionText) {
children.push(h('div', {
'ev-click': toast.action
}, toast.actionText));
}
return h('paper-toast.' + cssClass, {
'key': toast.key, // unique per toast => only drawn once
attributes: {
'text': toast.text,
'opened': true,
'duration': toastDuration,
'autoCloseDisabled': true
},
// Clean up the old toasts after enough time has passed.
'ev-core-overlay-open-completed': mercury.event(
events.viewport.deferRemoveToast,
toast.key
)
}, children);
}
/*
* Wire up events that we know how to handle.
*/
function wireUpEvents(state, events) {
events.openSidebar(function() {
state.sidebarOpened.set(true);
});
events.closeSidebar(function() {
state.sidebarOpened.set(false);
});
events.deferRemoveToast(function(key) {
// Remove the toast after a reasonable delay.
setTimeout(function() {
// Filter out the toast whose key matches.
state.put('toasts', state.toasts.filter(function(toast) {
return toast.key !== key;
}));
}, toastDuration);
});
}
/*
* Removes the splash screen once and then becomes a noop
* Splash screen fades so it is removed on animation end.
*/
var splashDomNode = document.querySelector('#splash');
function removeSplashScreen() {
if (splashDomNode) {
// keep a reference for the webkitAnimationEnd event handler
// since splashDomNode gets nuked after this to make this function a noop
var node = splashDomNode;
node.classList.add('fade');
node.addEventListener('webkitAnimationEnd', function() {
node.remove();
});
splashDomNode = null;
}
}
/*
* Sets a message on the slash screen.
* @param {string} message Text of message to sent
* @param {boolean} isError Boolean indicating whether this is an error message
*/
function setSplashMessage(message, isError) {
if (!splashDomNode) {
return;
}
var messageNode = splashDomNode.querySelector('#splashMessage');
var progressbar = splashDomNode.querySelector('#splashProgressbarWrapper');
if (isError) {
messageNode.classList.add('splashError');
progressbar.classList.add('hidden');
} else {
messageNode.classList.remove('splashError');
progressbar.classList.remove('hidden');
}
messageNode.textContent = message;
}
},{"../bug-report/index":188,"../main-content/index":205,"../sidebar/index":207,"../user-account/index":209,"./index.css":210,"insert-css":37,"mercury":45}],212:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var pluginRegistry = require('./registry');
// TODO(aghassemi) Do it automatically at build time based on folder structure
// or some other non-code way of registering plugins
var plugins = [
require('./system/log-viewer/plugin')
];
module.exports = function registerAll() {
plugins.forEach(function(p) {
pluginRegistry.register(p);
});
};
},{"./registry":213,"./system/log-viewer/plugin":215}],213:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var uuid = require('uuid');
module.exports = {
register: register,
matches: matches
};
var plugins = [];
/*
* Register a plugin
* @param {plugin} Plugin Plugin to register
* @see {plugin.js.doc}
*/
function register(plugin) {
// generate a unique id for the plugin.
// TODO(aghassemi) we may want these ids to be static, but that makes it
// harder to coordinate uniques across system and remote plugins. For now
// id is only used in a single UI context so it can stay dynamic.
plugin.id = uuid.v4();
plugins.push(plugin);
}
/*
* For a given pair of Vanadium object name and its signature, returns all
* plugins that support it.
* @param {string} name Vanadium object name for the item.
* @param {signature} signature Signature of the item.
* @return {Array<plugin>} Array of supported plugins.
*/
function matches(name, signature) {
return plugins.filter(function(p) {
return (p.canSupport && p.canSupport(name, signature));
});
}
},{"uuid":143}],214:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var polymer = require('../../../lib/polymer');
var publishedProperties = {
vname: ''
};
polymer('nsb-plugins-log-viewer', {
publish: publishedProperties,
ready: onReady
});
function onReady() {
}
},{"../../../lib/polymer":231}],215:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
require('./index.js');
module.exports = {
title: 'Log Viewer',
canSupport: canSupport,
render: render
};
function canSupport(name, signature) {
// Log Viewer supports all names
return false; //TODO(aghassemi) enable when completed
}
function render(name, signature) {
var logViewer = document.createElement('nsb-plugins-log-viewer');
logViewer.vname = name;
return logViewer;
}
},{"./index.js":214}],216:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = addAttributes;
/*
* Helper function to add additional attributes to an object.
* Does not replace existing attributes if already present.
*/
function addAttributes(obj, attrs) {
for (var key in attrs) {
if (attrs.hasOwnProperty(key) && !obj.hasOwnProperty(key)) {
obj[key] = attrs[key];
}
}
}
},{}],217:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = {
set: set,
add: add,
remove: remove
};
/*
* This is a utility function for arrays being used as ordered sets.
* If shouldSet is true, add the item to the array set. Otherwise, remove it.
* If no changes are needed, nothing happens.
* The function returns whether or not the array was modified.
*
* Note: indexOfCallback should be used if a custom indexOf function is needed.
* If indexOfCallback is omitted, then array.indexOf will be used by default.
*/
function set(array, item, shouldSet, indexOfCallback) {
var index = indexOfCallback ? indexOfCallback(item) : array.indexOf(item);
if (shouldSet && index === -1) { // need to add
array.push(item);
return true;
} else if (!shouldSet && index !== -1) { // need to remove
array.splice(index, 1);
return true;
}
return false; // did nothing
}
/*
* Wrapper for set that attempts to add the item to the array set.
*/
function add(array, item, indexOfCallback) {
return set(array, item, indexOfCallback, true);
}
/*
* Wrapper for set that attempts to remove the item from the array set.
*/
function remove(array, item, indexOfCallback) {
return set(array, item, indexOfCallback, false);
}
},{}],218:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* Given a collection of objects, returns true if all of them exist
* Returns false as soon as one does not exist.
* @param {*} [...] objects Objects to check existence of
* @return {bool} Whether all of the given objects exist or not
*/
module.exports = exists;
function exists(objects) {
if (!Array.isArray(objects)) {
objects = [objects];
}
for (var i = 0; i < objects.length; i++) {
var obj = objects[i];
if (typeof obj === 'undefined' || obj === null) {
return false;
}
}
return true;
}
},{}],219:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var extend = require('extend');
module.exports = extendDefaults;
/*
* Behaves like extend but does not copy over null values from the obj
*/
function extendDefaults(defaults, obj) {
if (obj) {
// Remove all properties with null values, since extend does not do that
Object.keys(obj).forEach(function(key) {
if (obj[key] === null) {
delete obj[key];
}
});
}
return extend(defaults, obj);
}
},{"extend":36}],220:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var util = require('./util');
module.exports = {
update: perceptronUpdate,
predict: perceptronPredict
};
/*
* Update the weights given the input features and associated score.
* The learning rate modulates the amount the weights are adjusted.
*/
function perceptronUpdate(weights, features, score, learningRate) {
var delta = score - perceptronPredict(weights, features);
for (var key in features) {
if (features.hasOwnProperty(key)) {
if (weights[key] === undefined) {
weights[key] = 0;
}
// Perceptron update rule.
weights[key] += features[key] * delta * learningRate;
}
}
}
/*
* Given the weights and input features, compute the predicted score.
*/
function perceptronPredict(weights, features) {
return util.dotProduct(weights, features);
}
},{"./util":222}],221:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var util = require('./util');
module.exports = {
getBestKItems: getBestKItems,
getBestItem: getBestItem,
getBestItemIndex: getBestItemIndex,
applyDiversityPenalty: applyDiversityPenalty
};
/*
* Given an array of scored items, find and return the top k scored items.
* These top k scored items should be sorted from highest to lowest.
* A scored item has an item and score attribute.
* Note: Order is not specified for ties.
* Note: Returns null in invalid scenarios.
*
* TODO(alexfandrianto): We can improve this algorithm by using a heap O(n*logk)
* or using Hoare's algorithm and median of medians O(n + k*logk).
*/
function getBestKItems(scoredItems, k) {
if (k < 0 || scoredItems.length === 0) {
return null;
}
// Shallow copy the scoredItems array to avoid modifying it.
var sItems = scoredItems.slice(0, scoredItems.length);
// Sort and return the top k items.
sItems.sort(function(a, b) {
return b.score - a.score; // descending sort
});
// Return the top k items
return sItems.slice(0, Math.min(k, scoredItems.length));
}
/*
* Given an array of scored items, find the highest scored item.
* A scored item has an item and score attribute.
* Note: Order is not specified for ties.
* Note: Returns null if there is no best item.
*/
function getBestItem(scoredItems) {
var index = getBestItemIndex(scoredItems);
if (index === -1) {
return null;
}
return scoredItems[index];
}
/*
* Given an array of scored items, find the index of the highest scored item.
* A scored item has an item and score attribute.
* Note: Order is not specified for ties.
* Note: Returns -1 if there is no best item.
*/
function getBestItemIndex(scoredItems) {
var maxScoredItemIndex = -1;
var maxScoredItem = null;
for (var i = 0; i < scoredItems.length; i++) {
var scoredItem = scoredItems[i];
if (maxScoredItem === null || scoredItem.score > maxScoredItem.score) {
maxScoredItemIndex = i;
maxScoredItem = scoredItem;
}
}
return maxScoredItemIndex;
}
/*
* Given scored items, penalize the scored items based on their similarity to
* a reference scored item.
* A scored item has an item and score attribute.
* The extractor takes an item and returns a map[string]float64
* The penalty is a float64.
*/
function applyDiversityPenalty(scoredItems, otherItem, extractor, penalty) {
var oFeatures = extractor(otherItem.item);
// Penalize the other item's score based on the cosine similarity.
for (var i = 0; i < scoredItems.length; i++) {
var iFeatures = extractor(scoredItems[i].item);
var cossim = util.cossim(iFeatures, oFeatures);
scoredItems[i].score -= cossim * penalty;
}
}
},{"./util":222}],222:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = {
dotProduct: dotProduct,
norm: norm,
cossim: cossim
};
/*
* Computes the dot product of these two objects.
*/
function dotProduct(a, b) {
var sum = 0.0;
for (var key in a) {
if (a.hasOwnProperty(key) && b.hasOwnProperty(key)) {
sum += a[key] * b[key];
}
}
return sum;
}
/*
* Computes the norm of the given object.
*/
function norm(a) {
return Math.sqrt(dotProduct(a, a));
}
/*
* Computes the cosine similarity of these two objects.
*/
function cossim(a, b) {
var cs = dotProduct(a, b);
if (cs !== 0) { // This check prevents dividing by a 0 norm.
cs /= norm(a) * norm(b);
}
return cs;
}
},{}],223:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* DeLogger wraps the popular debug (github.com/visionmedia/debug) module and
* adds error and warning levels on top of debug.
*
* var logger = require('DeLogger')('app:foo');
* var log.error('bad things happened', 'goes to stderr via console.error');
* var log.warn('bad things might happen', 'goes to stderr via console.warn');
* var log.debug('it's all good, probably', 'goes to stdout via console.log');
*
* log.enableError('app:*'); // Enables error log levels for pattern
* log.enableWarn('app:*'); // Enables error and warning log levels for pattern
* log.enable('app:*'); // Enables all log levels for pattern
* log.disable(); // Disables all logs
*
* TODO(aghassemi) maybe move to github as a separate module and publish on npm
* as DeLogger? DeLog is taken :(
*/
var debug = require('debug');
var extendDefaults = require('./extend-defaults');
module.exports = log;
module.exports.disable = disable;
module.exports.enable = debug.enable;
module.exports.enableError = enableError;
module.exports.enableWarn = enableWarn;
var ERROR_LEVEL_SUFFIX = ':error';
var WARN_LEVEL_SUFFIX = ':warn';
// Allows for different implementation of console to be injected.
var defaults = {
console: console
};
function log(namespace, options) {
options = extendDefaults(defaults, options);
var consoleInstance = options.console;
var errorLogger = debug(namespace + ERROR_LEVEL_SUFFIX);
var warnLogger = debug(namespace + WARN_LEVEL_SUFFIX);
var debugLogger = debug(namespace);
errorLogger.log = coerce(consoleInstance.error, consoleInstance);
warnLogger.log = coerce(consoleInstance.warn, consoleInstance);
debugLogger.log = coerce(consoleInstance.log, consoleInstance);
return {
error: errorLogger,
warn: warnLogger,
debug: debugLogger
};
}
function enableError(namespaces) {
debug.enable(appendLevelPattern(namespaces, '*' + ERROR_LEVEL_SUFFIX));
}
function enableWarn(namespaces) {
// debug.enable is not cumulative and overrides previous values.
debug.enable(
appendLevelPattern(namespaces, '*' + ERROR_LEVEL_SUFFIX) + ',' +
appendLevelPattern(namespaces, '*' + WARN_LEVEL_SUFFIX)
);
}
function disable() {
debug.disable();
debug.names = [];
debug.skips = [];
}
function appendLevelPattern(namespaces, pattern) {
var split = (namespaces || '').split(/[\s,]+/);
return split.map(function(namespace) {
return namespace += pattern;
}).join(',');
}
function coerce(consoleFunc, consoleInstance) {
return function() {
var args = Array.prototype.slice.call(arguments);
args = args.map(function(arg) {
if (arg instanceof Error) {
return arg.stack || arg.message;
}
return arg;
});
return consoleFunc.apply(consoleInstance, args);
};
}
},{"./extend-defaults":219,"debug":33}],224:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
module.exports = addDelegatedEvents;
/*
* Given a list of event names, have mercury's Delegator listenTo them.
*/
function addDelegatedEvents(eventNames) {
var delegator = mercury.Delegator({
defaultEvents: false
});
eventNames.forEach(function(eventName) {
delegator.listenTo(eventName);
});
}
},{"mercury":45}],225:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* Because of the way Mercury captures and delegates events, ev-click does not
* work for items inside a dialog because polymer moves the dialog's DOM around
* This hook is a work-around for that issue.
*/
module.exports = function(handler) {
return Object.create({
hook: function(elem) {
if (!elem.clickHandlerInstalled) {
elem.addEventListener('click', handler);
elem.clickHandlerInstalled = true;
}
}
});
};
},{}],226:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = freeze;
/*
* List of array methods that can't cause mutation
*/
var IMMUTABLE_ARRAY_METHODS = [
'concat', 'slice', 'every', 'filter', 'forEach', 'indexOf',
'join', 'lastIndexOf', 'map', 'reduce', 'reduceRight',
'some', 'toString', 'toLocaleString', 'get'];
/*
* Makes an observable into an immutable observable.
*/
function freeze(observable) {
function immutableObservable(fn) {
return observable(fn);
}
if(observable._type === 'observ-array') {
copyMethods(immutableObservable, observable, IMMUTABLE_ARRAY_METHODS);
}
return immutableObservable;
}
function copyMethods(target, source, methods) {
methods.forEach(function (name) {
target[name] = function() {
var result = source[name].apply(source, arguments);
// If result is an observable itself, freeze it again.
if( typeof result === 'function' ) {
result = freeze(result);
}
return result;
};
});
}
},{}],227:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var BaseEvent = require('mercury').BaseEvent;
// export extended BaseEvent!
module.exports = new BaseEvent(internalPolymerEvent);
/*
* This allows us to attach a single event listener at the root of a VDOM tree
* and receive polymer events from any item in the tree
*/
function internalPolymerEvent(ev, broadcast) {
this.data.polymerDetail = ev._rawEvent.detail;
this.data.target = ev._rawEvent.target;
this.data.rawEvent = ev._rawEvent;
broadcast(this.data);
}
},{"mercury":45}],228:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = PropertyValueEvent;
function PropertyValueEvent(sink, property, rawTypeIsCustom) {
if (!(this instanceof PropertyValueEvent)) {
return new PropertyValueEvent(sink);
}
this.sink = sink;
this.id = sink.id;
this.property = property;
// This final value is a sort of Mercury/Polymer capturing mode workaround to
// avoid handling the same event twice.
// By setting this to true, we filter out captured DOM Events and can focus
// on the CustomEvent's fired by Polymer elements.
this.rawTypeIsCustom = rawTypeIsCustom ? true : false; // optional
}
PropertyValueEvent.prototype.handleEvent = handleEvent;
function handleEvent(ev) {
if (!this.rawTypeIsCustom || ev._rawEvent instanceof CustomEvent) {
var data = ev.currentTarget[this.property];
if (typeof this.sink === 'function') {
this.sink(data);
} else {
this.sink.write(data);
}
}
}
},{}],229:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = setMercuryArray;
// TODO(alexfandrianto): observ-array's set() method works properly in 3.0.0,
// but mercury doesn't depend on that version yet. Use set() when it is.
function setMercuryArray(o, newArray) {
o.splice(0, o.getLength());
newArray.forEach(function(entry) {
o.push(entry);
});
}
},{}],230:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var _ = require('lodash');
module.exports = sortedPush;
/*
* sortedPush can be used to push an item to a sorted array without messing up
* the ordering. It uses binary search to find the index to insert, so it is
* faster than re-sorting on every push or using indexOf. It also supports
* custom sorter functions or string sorters that specify a property on the
* item to sort based on.
*
* @param {mercury.array} obsArray Observable array to push item to.
* @param {object} item Item to push to array. Can be observable itself.
* @sorter {string|function} if provided, it will be used to compute the sort
* ranking of each item, including the item you pass. The sorter may also be the
* string name of the property to sort by
*/
function sortedPush(obsArray, item, sorter) {
var valueList = obsArray();
// If item is an observable itself, get its value
var valueItem = item;
if( typeof item === 'function' ) {
valueItem = item();
}
var sortedIndex = _.sortedIndex(valueList, valueItem, sorter);
obsArray.splice(sortedIndex, 0, item);
}
},{"lodash":43}],231:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* Exposes the Global polymer object asynchronously.
* This allows Polymer object to be used with browserify and we do not require
* it to be loaded first as this module will queue up calls.
*/
module.exports = Polymer;
var queue = [];
var loaded = false;
function Polymer(tagName, proto) {
if (loaded) {
window.Polymer(tagName, proto);
} else {
queue.push({
tagName: tagName,
proto: proto
});
}
}
document.addEventListener('HTMLImportsLoaded', function() {
if (loaded) {
return;
}
loaded = true;
queue.forEach(function(c) {
window.Polymer(c.tagName, c.proto);
});
queue = null;
});
},{}],232:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* The store allows key-value store for string keys and any value.
*/
var localForage = require('localforage');
var stripFunctions = require('./strip-functions');
var _ = require('lodash');
module.exports = {
hasValue: hasValue,
setValue: setValue,
getValue: getValue,
removeValue: removeValue,
getKeysWithPrefix: getKeysWithPrefix
};
/*
* Given a string identifier, return a promise indicating if the key exists.
*/
function hasValue(key) {
return localForage.getItem(key).then(function(value) {
return value !== null;
});
}
/*
* Given a string identifier and any value, strip functions out of the value
* and put it into the store. Returns a promise.
*/
function setValue(key, value) {
return localForage.setItem(key, stripFunctions(value));
}
/*
* Given a string identifier, return a promise with the return value.
*/
function getValue(key) {
return localForage.getItem(key);
}
/*
* Given a string identifier, return a promise that removes the value.
*/
function removeValue(key) {
return localForage.removeItem(key);
}
/*
* Given a string prefix, return a promise with the corresponding keys.
* TODO(alexfandrianto): May be inefficient depending on backend. Avoid using.
* Upgrade to glob once the store is ready.
*/
function getKeysWithPrefix(key) {
return localForage.keys().then(function(keys) {
return _.filter(keys, function(candidate) {
return candidate.indexOf(key) === 0;
});
});
}
},{"./strip-functions":233,"localforage":42,"lodash":43}],233:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = stripFunctions;
/*
* Returns a copy of the input with its functions stripped out.
* Array entries would be set to null. Object entries are unset.
* The functions are stripped deeply, also purging from nested objects/arrays.
*/
function stripFunctions(data) {
if (typeof data === 'function') {
return null;
} else if (typeof data === 'object') {
// JSON.parse + stringify deeply purges function properties in objects.
return JSON.parse(JSON.stringify(data));
}
return data; // primitive type
}
},{}],234:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var bookmarkService = require('./services/bookmarks/service');
var store = require('./lib/store');
var log = require('./lib/log')('onboarding');
module.exports = onboarding;
// When a new user visits the namespace browser, do a simple onboarding.
function onboarding(email, appState) {
store.getValue('returning_user').then(function(returning) {
if (!returning) {
log.debug('Welcome to the Vanadium Namespace Browser!');
addDefaultBookmarks(email);
// TODO(alexfandrianto): We can improve the onboarding experience
// By changing the appState variable, we can do other things to help a new
// user learn the Namespace Browser.
completeOnboarding();
}
}).catch(function(err) {
log.error('Failed to get "returning_user" flag', err);
});
}
// Add default bookmarks to the user's store.
function addDefaultBookmarks(email) {
function bookmarkFail(err) {
log.warn('Could not add default bookmark', err);
}
// Determine the default bookmarks.
var globalMT = '/ns.dev.v.io:8101';
var personal;
if (email) {
// Point to their personal section of the global namespace.
personal = globalMT + '/users/' + email;
}
// If the bookmark already exists, then Mercury's observ-array will add it a
// 2nd time, so check if it's already bookmarked.
// Avoid racing bookmarks. Make sure to add them consecutively to the store.
bookmarkService.isBookmarked(globalMT).then(function(isGlobalMT) {
if (!isGlobalMT) {
bookmarkService.bookmark(globalMT, true);
}
}).catch(bookmarkFail).then(function() {
// Add a personal bookmark if present.
if (personal) {
bookmarkService.isBookmarked(personal).then(function(isPersonal) {
if (!isPersonal) {
bookmarkService.bookmark(personal, true);
}
});
}
}).catch(bookmarkFail);
}
// Set the returning_user flag to true.
function completeOnboarding() {
store.setValue('returning_user', true).catch(function(err) {
log.error('Failed to set "returning_user" flag', err);
});
}
},{"./lib/log":223,"./lib/store":232,"./services/bookmarks/service":244}],235:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var Routes = require('routes');
var registerRoutes = require('./routes/register-routes');
module.exports = router;
/*
* Implements a hash(#) router.
*
* Using # instead of regular routes to eliminate any configuration dependency
* on the server. Otherwise servers need to be configured to return index
* instead of 404. Although that's reasonable, for simplicity of deployment,
* hash-based routing is picked.
*/
function router(state, events) {
// Create and register routes
var routes = new Routes();
registerRoutes(routes);
// Match the path to a route and trigger the route handler for it
var handleRouteChange = function(data) {
var path = normalizePath(data.path);
var route = routes.match(path);
if (!route) {
//TODO(aghassemi) Needs to be 404 error when we have support for 404
return;
}
if (!data.skipHistoryPush) {
window.history.pushState(null, null, '#' + path);
}
route.fn.call(null, state, events, route.params);
};
// Triggers a navigate event using the current location as the path
var navigateToCurrentLocation = function() {
events.navigation.navigate({
path: window.location.hash,
skipHistoryPush: true
});
};
// Route and push to history when navigation event fires
events.navigation.navigate(handleRouteChange);
// Fire navigation event when hash changes
window.addEventListener('hashchange', navigateToCurrentLocation);
// Kick off the routing by navigating to current Url
navigateToCurrentLocation();
}
function normalizePath(path) {
// Remove #
if (path.indexOf('#') === 0) {
path = path.substr(1);
}
// Empty means root
if (path === '') {
path = '/';
}
return path;
}
},{"./routes/register-routes":243,"routes":141}],236:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = function(routes) {
routes.addRoute('/bookmarks', handleBookmarksRoute);
};
module.exports.createUrl = function() {
return '#/bookmarks';
};
function handleBookmarksRoute(state, events, params) {
// Set the page to browse
state.navigation.pageKey.set('browse');
state.viewport.title.set('Browse');
// Trigger browse components browseNamespace event
events.browse.browseNamespace({
'namespace': state.browse.namespace(),
'subPage': 'bookmarks',
'viewType': state.browse.views.viewType()
});
}
},{}],237:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var urlUtil = require('url');
var qsUtil = require('querystring');
var exists = require('../lib/exists');
var stateService = require('../services/state/service');
module.exports = function(routes) {
// Url pattern: /browse/vanadiumNameSpace?glob=*&viewType=grid
routes.addRoute('/browse/:namespace?', handleBrowseRoute);
};
module.exports.createUrl = function(browseState, opts) {
var globQuery;
var viewType;
var namespace;
if (opts) {
globQuery = opts.globQuery;
viewType = opts.viewType;
namespace = opts.namespace;
}
// We preserve namespace and viewtype if they are not provided
// We reset globquery unless provided
namespace = (namespace === undefined ? browseState.namespace : namespace);
viewType = (viewType === undefined ? browseState.views.viewType : viewType);
var path = '/browse';
if (exists(namespace)) {
namespace = encodeURIComponent(namespace);
path += '/' + namespace;
}
var query = {};
if (exists(globQuery)) {
query['glob'] = globQuery;
}
if (exists(viewType)) {
query['viewtype'] = viewType;
}
return '#' + urlUtil.format({
pathname: path,
query: query
});
};
function handleBrowseRoute(state, events, params) {
// Set the page to browse
state.navigation.pageKey.set('browse');
state.viewport.title.set('Browse');
var namespace;
var globquery;
var viewtype;
if (params.namespace) {
var parsed = urlUtil.parse(params.namespace);
if (parsed.pathname) {
namespace = parsed.pathname;
}
if (parsed.query) {
var queryString = qsUtil.parse(parsed.query);
globquery = queryString.glob;
viewtype = queryString.viewtype;
}
}
// Persist this namespace so that we know where to reload next time.
if (!state.demo()) {
stateService.saveNamespace(namespace);
}
// Trigger browse components browseNamespace event
events.browse.browseNamespace({
'namespace': namespace,
'globQuery': globquery,
'viewType': viewtype,
'subPage': 'views'
});
}
},{"../lib/exists":218,"../services/state/service":252,"querystring":14,"url":29}],238:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = function(routes) {
routes.addRoute('/demo', handleDemoRoute);
};
module.exports.createUrl = function() {
return '#/demo';
};
function handleDemoRoute(state) {
// If already initialized, reload the page in demo mode
if (state.initialized()) {
setTimeout(function() {
window.location.reload();
// Give time for the sidebar to close so interaction feels more natural
}, 300);
} else {
// Set demo true
state.demo.set(true);
}
}
},{}],239:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = function(routes) {
routes.addRoute('/error', handleErrorRoute);
};
module.exports.createUrl = function() {
return '#/error';
};
function handleErrorRoute(state) {
// Set the page to error
state.navigation.pageKey.set('error');
state.viewport.title.set('Error');
}
},{}],240:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var exists = require('../lib/exists');
module.exports = function(routes) {
routes.addRoute('/help/:topic?', handleHelpRoute);
};
module.exports.createUrl = function(topic) {
if (exists(topic)) {
return '#/help/' + topic;
}
return '#/help';
};
function handleHelpRoute(state, events, params) {
// Set the page to help
state.navigation.pageKey.set('help');
state.viewport.title.set('Help');
// If given, go to the specified help page tab.
if (params.topic) {
// Import selectTab here to avoid a cyclical dependency.
var selectTab = require('../components/help/selectTab');
selectTab(state.help, events.help, params.topic);
}
}
},{"../components/help/selectTab":203,"../lib/exists":218}],241:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var browseRoute = require('./browse');
module.exports = function(routes) {
routes.addRoute('/', handleIndexRoute);
};
function handleIndexRoute(state, events) {
// Send the user to the browse route with their current namespace.
events.navigation.navigate({
path: browseRoute.createUrl(state.browse(), {
namespace: state.browse.namespace()
})
});
}
},{"./browse":237}],242:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = function(routes) {
routes.addRoute('/recommendation', handleRecommendationRoute);
routes.addRoute('/recent', handleRecommendationRoute);
};
module.exports.createUrl = function() {
return '#/recent';
};
function handleRecommendationRoute(state, events, params) {
// Set the page to browse
state.navigation.pageKey.set('browse');
state.viewport.title.set('Browse');
// Trigger browse components browseNamespace event
events.browse.browseNamespace({
'namespace': state.browse.namespace(),
'subPage': 'recommendations',
'viewType': state.browse.views.viewType()
});
}
},{}],243:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = registerRoutes;
/*
* Registers all route handlers.
*/
function registerRoutes(routes) {
require('./index')(routes);
require('./help')(routes);
require('./browse')(routes);
require('./error')(routes);
require('./recommendations')(routes);
require('./bookmarks')(routes);
require('./demo')(routes);
}
},{"./bookmarks":236,"./browse":237,"./demo":238,"./error":239,"./help":240,"./index":241,"./recommendations":242}],244:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var _ = require('lodash');
var EventEmitter = require('events').EventEmitter;
var arraySet = require('../../lib/array-set');
var store = require('../../lib/store');
var freeze = require('../../lib/mercury/freeze');
var sortedPush = require('../../lib/mercury/sorted-push-array');
var namespaceService = require('../namespace/service');
var namespaceItem = require('../namespace/item');
var log = require('../../lib/log')('services:bookmarks:service');
module.exports = {
getAll: getAll,
bookmark: bookmark,
isBookmarked: isBookmarked
};
// Data is loaded from and saved to this key in the store.
var USER_BOOKMARKS_KEY = 'bookmarks-store-key';
// Singleton state for all the bookmarks.
var bookmarksObs = mercury.array([]);
/*
* Gets all the namespace items that are bookmarked
* As new bookmarks become available/removed the observable array will change
* to reflect the changes.
*
* The observable result has an events property which is an EventEmitter
* and emits 'end', 'itemError' events.
*
* @return {Promise.<mercury.array>} Promise of an observable array
* of bookmark items
*/
function getAll() {
// Empty out the array
bookmarksObs.splice(0, bookmarksObs.getLength());
var immutableBookmarksObs = freeze(bookmarksObs);
immutableBookmarksObs.events = new EventEmitter();
return loadKeys().then(getBookmarkItems);
function getBookmarkItems(names) {
var allItems = names.map(function(name) {
return addNamespaceItem(name).catch(function(err) {
immutableBookmarksObs.events.emit('itemError', {
name: name,
error: err
});
log.warn('Failed to create item for "' + name + '"', err);
});
});
Promise.all(allItems).then(function() {
immutableBookmarksObs.events.emit('end');
}).catch(function() {
immutableBookmarksObs.events.emit('end');
});
return immutableBookmarksObs;
}
}
/*
* Gets the namespace items for a name and adds it to the observable array
*/
function addNamespaceItem(name) {
return namespaceService.getNamespaceItem(name)
.then(function(item) {
var sorter = 'objectName';
sortedPush(bookmarksObs, item, sorter);
}).catch(function(err) {
// Add the object, anyway. It will show as inaccessible.
sortedPush(bookmarksObs, namespaceItem.createItem({
objectName: name
}), 'objectName');
throw err;
});
}
/*
* Whether a specific name is bookmarked or not
* @return {Promise.<boolean>} Promise indicating a name is bookmarked
*/
function isBookmarked(name) {
return loadKeys().then(function(keys) {
return (keys && keys.indexOf(name) >= 0);
});
}
/*
* Bookmarks/Unbookmarks a name.
* @return {Promise.<void>} Promise indicating whether operation succeeded.
*/
function bookmark(name, isBookmarked) {
if (isBookmarked) {
// new bookmark, add it to the state
addNamespaceItem(name).catch(function(err) {
log.warn('Bookmarking inaccessible item "' + name + '"', err);
});
} else {
// remove bookmark
arraySet.set(bookmarksObs, null, false, indexOf.bind(null, name));
}
// update store
return loadKeys().then(function(keys) {
keys = keys || []; // Initialize the bookmarks, if none were loaded.
arraySet.set(keys, name, isBookmarked);
return store.setValue(USER_BOOKMARKS_KEY, keys);
});
}
/*
* Check the observe array for the index of the given item. -1 if not present.
*/
function indexOf(name) {
return _.findIndex(bookmarksObs(), function(bookmark) {
// Since bookmarks can be assigned out of order, check for undefined.
return bookmark !== undefined && name === bookmark.objectName;
});
}
/*
* Loads all the bookmarked names from the store
*/
function loadKeys() {
return store.getValue(USER_BOOKMARKS_KEY).then(function(keys) {
keys = keys || [];
return keys.filter(function(key, index, self) {
// only return unique and existing values
return key !== null &&
key !== undefined &&
self.indexOf(key) === index;
});
});
}
},{"../../lib/array-set":217,"../../lib/log":223,"../../lib/mercury/freeze":226,"../../lib/mercury/sorted-push-array":230,"../../lib/store":232,"../namespace/item":246,"../namespace/service":248,"events":8,"lodash":43,"mercury":45}],245:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var jsonStableStringify = require('json-stable-stringify');
module.exports = {
getMethodData: getMethodData,
hashInterface: hashInterface
};
/*
* Given a service interface and method name, retrieve the method signature.
* @param {interface} interface The service interface
* @param {string} methodName The name of the method.
* @return {methodSig} An object containing info about the method.
*/
function getMethodData(interface, methodName) {
for (var i = 0; i < interface.methods.length; i++) {
var methodData = interface.methods[i];
if (methodData.name === methodName) {
return methodData;
}
}
return null;
}
/*
* Given a service signature, compute a reasonable hash that uniquely identifies
* a service without containing unnecessary information.
* This heuristic comes extremely close to uniquely identifying service methods.
*/
function hashInterface(interface) {
var pkgPath = interface.pkgPath + '.' + interface.name;
var methods = interface.methods.map(function(methodData) {
var inArgList = methodData.inArgs || [];
return {
name: methodData.name,
inArgs: inArgList.map(function(inArg) {
return inArg.name;
})
};
});
var output = jsonStableStringify([pkgPath, methods]);
return output;
}
},{"json-stable-stringify":38}],246:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
module.exports = {
createItem: createItem
};
/*
* Creates an observable struct representing basic information about
* an item in the namespace.
*
* @param {string} obj.objectName The full hierarchical object name of the item
* e.g. "bar/baz/foo"
* @param {string} obj.mountedName The nonhierarchical name of the item used
* when it was mounted to a mounttable. e.g. "foo"
* @param {boolean} obj.isLeaf. Whether the item can have children.
* @param {boolean} obj.hasServer. Whether there is a server behind this name.
* @param {boolean} obj.hasMountPoint. Whether there is a mountpoint behind this
* name.
* @param {boolean} obj.isMounttable. Whether the server is an mounttable server
* @return {mercury.struct}
*/
function createItem(obj) {
return mercury.struct({
objectName: mercury.value(obj.objectName),
mountedName: mercury.value(obj.mountedName),
isLeaf: mercury.value(obj.isLeaf),
hasServer: mercury.value(obj.hasServer),
hasMountPoint: mercury.value(obj.hasMountPoint),
isMounttable: mercury.value(obj.isMounttable)
});
}
},{"mercury":45}],247:[function(require,module,exports){
// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* @fileoverview Helpers for manipulating vanadium names.
* See vanadium/release/go/src/v.io/v23/naming/parse.go for the
* corresponding operations in golang.
* @private
*/
module.exports = {
clean: clean,
join: join,
isRooted: isRooted,
basename: basename,
stripBasename: stripBasename,
splitAddressName: splitAddressName,
};
/**
* Normalizes a name by collapsing multiple slashes and removing any
* trailing slashes.
* @param {string} name The vanadium name.
* @returns {string} The clean name.
* @memberof module:vanadium.naming
*/
function clean(name) {
return _removeTailSlash(_squashMultipleSlashes(name));
}
/**
* <p>Joins parts of a name into a whole. The joined name will be cleaned; it
* only preserved the rootedness of the name components.</p>
* <p>Examples:</p>
* <pre>
* join(['a, b']) -> 'a/b'
* join('/a/b/', '//d') -> '/a/b/d'
* join('//a/b', 'c/') -> '/a/b/c'
* </pre>
* @param {...string} parts Either a single array that contains the strings
* to join or a variable number of string arguments that will be joined.
* @return {string} A joined string.
* @memberof module:vanadium.naming
*/
function join(parts) {
if (Array.isArray(parts)) {
while (parts.length > 0 && parts[0] === '') {
parts.splice(0, 1); // Remove empty strings; they add nothing to the join.
}
var joined = parts.join('/');
return clean(joined);
}
return join(Array.prototype.slice.call(arguments));
}
/**
* Determines if a name is rooted, that is beginning with a single '/'.
* @param {string} name The vanadium name.
* @return {boolean} True iff the name is rooted.
* @memberof module:vanadium.naming
*/
function isRooted(name) {
return name[0] === '/';
}
/**
* SplitAddressName takes an object name and returns the server address and
* the name relative to the server.
* The name parameter may be a rooted name or a relative name; an empty string
* address is returned for the latter case.
* @param {string} name The vanadium name.
* @return {Object.<string, string>} An object with the address and suffix
* split. Returned object will be in the format of:
* <pre>
* {address: string, suffix: string}
* </pre>
* Address may be in endpoint format or host:port format.
* @memberof module:vanadium.naming
*/
function splitAddressName(name) {
name = clean(name);
if (!isRooted(name)) {
return {
address: '',
suffix: name
};
}
name = name.substr(1); // trim the beginning "/"
if (name.length === 0) {
return {
address: '',
suffix: ''
};
}
if (name[0] === '@') { // <endpoint>/<suffix>
var split = _splitIntoTwo(name, '@@/');
if (split.suffix.length > 0) { // The trailing "@@" was stripped, restore
split.address = split.address + '@@';
}
return split;
}
if (name[0] === '(') { // (blessing)@host:[port]/suffix
var tmp = _splitIntoTwo(name, ')@').suffix;
var suffix = _splitIntoTwo(tmp, '/').suffix;
return {
address: _trimEnd(name, '/' + suffix),
suffix: suffix
};
}
// host:[port]/suffix
return _splitIntoTwo(name, '/');
function _splitIntoTwo(str, separator) {
var elems = str.split(separator);
return {
address: elems[0],
suffix: elems.splice(1).join(separator)
};
}
}
/**
* Gets the basename of the given vanadium name.
* @param {string} name The vanadium name.
* @return {string} The basename of the given name.
* @memberof module:vanadium.naming
*/
function basename(name) {
name = clean(name);
var split = splitAddressName(name);
if (split.suffix !== '') {
return split.suffix.substring(split.suffix.lastIndexOf('/') + 1);
} else {
return split.address;
}
}
/**
* Retrieves the parent of the given name.
* @param {string} name The vanadium name.
* @return {string | null} The parent's name or null, if there isn't one.
* @memberof module:vanadium.naming
*/
function stripBasename(name) {
name = clean(name);
var split = splitAddressName(name);
if (split.suffix !== '') {
return name.substring(0, name.lastIndexOf('/'));
} else {
return '';
}
}
// Replace every group of slashes in the string with a single slash.
function _squashMultipleSlashes(s) {
return s.replace(/\/{2,}/g, '/');
}
// Remove the last slash in the string, if any.
function _removeTailSlash(s) {
return s.replace(/\/$/g, '');
}
// Helper util that removes the given suf from the end of str
function _trimEnd(str, suf) {
var index = str.lastIndexOf(suf);
if (index + suf.length === str.length) {
return str.substring(0, index);
} else {
return str;
}
}
},{}],248:[function(require,module,exports){
(function (process){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var LRU = require('lru-cache');
var EventEmitter = require('events').EventEmitter;
var itemFactory = require('./item');
var freeze = require('../../lib/mercury/freeze');
var sortedPush = require('../../lib/mercury/sorted-push-array');
var log = require('../../lib/log')('services:namespace:service');
var naming = require('./naming-util.js');
naming.parseName = parseName;
module.exports = {
getChildren: getChildren,
getNamespaceItem: getNamespaceItem,
getRemoteBlessings: getRemoteBlessings,
getSignature: getSignature,
getAccountName: getAccountName,
getEmailAddress: getEmailAddress,
getObjectAddresses: getObjectAddresses,
getPermissions: getPermissions,
resolveToMounttable: resolveToMounttable,
makeRPC: makeRPC,
search: search,
util: naming,
clearCache: clearCache,
deleteMountPoint: deleteMountPoint,
prefixes: prefixes
};
/*
* Returns an EventSource object connected to the local network.
* Only certain types of requests are allowed.
*
* accountName: <no parameters> => { accountName: <string>, err: <err> }
* glob: string pattern => a stream of responses
* { globRes: <glob res>, globErr: <glob err>, globEnd: <bool>, err: <err> }
* permissions: string name => { permissions: <permissions>, err: <err> }
* deleteMountPoint: string name => { err: <err string> }
* resolveToMounttable: string name => { addresses: []<string>, err: <err> }
* objectAddresses: string name => { addresses: []<string>, err: <err> }
* remoteBlessings: string name => { blessings: []<string>, err: <err> }
* signature: string name => { signature: <signature>, err: <err> }
* makeRPC: { name: <string>, methodName: <string>, args: []<string>,
* numOutArgs: <int> } =>
* { response: <undefined, output, OR []outputs>, err: <err> }
*/
// TODO(alexfandrianto): Make this configurable here and on the Go end.
// https://github.com/vanadium/issues/issues/1268
var eventSourceURL = 'http://127.0.0.1:9002';
function connectToEventSource(requestType, parameters) {
parameters = parameters || '';
var requestData = eventSourceURL +
'?request=' + encodeURIComponent(requestType) +
'&params=' + encodeURIComponent(JSON.stringify(parameters));
// Create the EventSource. Note: node does not have EventSource.
return new EventSource(requestData); // jshint ignore:line
}
/*
* Returns a Promise<value> drawn from the connected Event Source.
* See connectToEventSource.
*/
function getSingleEvent(type, params, field) {
return new Promise(function(resolve, reject) {
var ev = connectToEventSource(type, params);
ev.addEventListener('message', function(message) {
ev.close();
try {
var data = JSON.parse(message.data);
if (data.err) {
reject(data.err);
} else {
resolve(data[field]);
}
} catch (err) {
reject(err);
}
});
ev.addEventListener('error', function(err) {
ev.close();
reject(err);
});
});
}
/*
* Returns the accountName for the currently logged in user
* @return {Promise.<string>}
*/
var _accountNamePromise;
function getAccountName() {
if (!_accountNamePromise) {
_accountNamePromise =
getSingleEvent('accountName', undefined, 'accountName');
}
return _accountNamePromise;
}
/*
* Returns the email address for the currently logged in user
* @return {Promise.<string>}
*/
function getEmailAddress() {
return getAccountName().then(function(accountName) {
// TODO(alexfandrianto): Assumes a lot about the format of the blessings.
return accountName.split(':')[2];
});
}
/*
* globCache holds (name + globQuery, result) cache entry for
* GLOB_CACHE_MAX_SIZE items in an LRU cache
*/
var GLOB_CACHE_MAX_SIZE = 10000;
var GLOB_CACHE_PREFIX = 'glob|';
var globCache = new LRU({
max: GLOB_CACHE_MAX_SIZE
});
/*
* Given a name and a glob query returns a promise of an observable array
* of items as defined in @see item.js
* As new items become available the observable array will change to reflect
* the changes.
*
* The observable result has an events property which is an EventEmitter
* and emits 'end' and 'globError' events.
*
* @param {string} pattern Glob pattern
* @return {Promise.<mercury.array>} Promise of an observable array
* of namespace items
*/
function glob(pattern) {
var cacheKey = GLOB_CACHE_PREFIX + pattern;
var cacheHit = globCache.get(cacheKey);
if (cacheHit) {
// The addition of the end event to mark the end of a glob requires that
// our cache also causes the same event to be emitted.
if (cacheHit._hasEnded) {
// Remove old listeners to avoid memory leak but now we need to set
// _hasEnded to false until we trigger again otherwise a new request
// could wipe out an outstanding listener.
cacheHit._hasEnded = false;
cacheHit.events.removeAllListeners();
process.nextTick(function() {
cacheHit.events.emit('end');
cacheHit._hasEnded = true;
});
}
return Promise.resolve(cacheHit);
}
var globItemsObservArr = mercury.array([]);
var immutableResult = freeze(globItemsObservArr);
immutableResult.events = new EventEmitter();
var globItemsObservArrPromise =
Promise.resolve().then(function callGlobOnNamespace() {
return new Promise(function (resolve, reject) {
var ev = connectToEventSource('glob', pattern);
ev.addEventListener('error', function(err) {
ev.close();
reject(err);
});
function handleMessageConnectionResponse(response) {
try {
var data = JSON.parse(response.data);
if (data.err) {
ev.close();
reject(data.err);
} else {
// We have successfully established the stream.
// Keep the event source open to listen for more.
resolve();
}
} catch (err) {
ev.close();
reject(err);
}
}
function handleStreamEvent(message) {
try {
var data = JSON.parse(message.data);
if (data.globRes) {
var globResult = data.globRes;
// Handle a glob result by creating an item.
var item = createNamespaceItem(lowercasifyJSONObject(globResult));
var existingItem = globItemsObservArr.filter(function(curItem) {
return curItem().objectName === item().objectName;
}).get(0);
if (existingItem) {
// override the old one if new item has server
if (item().hasServer) {
var index = globItemsObservArr.indexOf(existingItem);
globItemsObservArr.put(index, item);
}
} else {
var sorter = 'mountedName';
sortedPush(globItemsObservArr, item, sorter);
}
} else if (data.globErr) {
var err = data.globErr;
// Handle a glob error by emitting that event.
immutableResult.events.emit('globError', err);
log.warn('Glob stream error', err);
} else if (data.globEnd) {
// Handle a glob end by emitting it. Close event source.
immutableResult.events.emit('end');
immutableResult._hasEnded = true;
ev.close();
} else {
// There was a data error. Close event source.
log.error('Event source error for', name, data.err);
ev.close();
// If this were an RPC, we probably would have failed earlier.
// So, we must also clear the cache key.
globCache.del(cacheKey);
}
} catch (err) {
log.error(err);
}
}
var initialResponse = false;
ev.addEventListener('message', function(response) {
if (!initialResponse) {
// Check whether the RPC and stream connection was established.
initialResponse = true;
handleMessageConnectionResponse(response);
} else {
// Handle the Glob Results and Errors from the stream.
handleStreamEvent(response);
}
});
});
}).then(function cacheAndReturnResult() {
globCache.set(cacheKey, immutableResult);
return immutableResult;
}).catch(function invalidateCacheAndRethrow(err) {
globCache.del(cacheKey);
return Promise.reject(err);
});
// Return our Promise of observable array. It will get filled as data comes in
return globItemsObservArrPromise;
}
/*
* Given a name, provide information about a the name as defined in @see item.js
* @param {string} objectName Object name to get namespace item for.
* @return {Promise.<mercury.value>} Promise of an observable value of an item
* as defined in @see item.js
*/
function getNamespaceItem(objectName) {
// Globbing the name itself would provide information about the name.
return glob(objectName).then(function(resultsObs) {
// Wait until the glob finishes before returning the item
return new Promise(function(resolve, reject) {
resultsObs.events.on('end', function() {
var results = resultsObs();
if (results.length === 0) {
reject(new Error(objectName + ' Not Found'));
} else {
resolve(resultsObs.get(0));
}
});
});
});
}
/*
* Given a name returns a promise of an observable array of immediate children
* @param {string} parentName Object name to glob
* @return {Promise.<mercury.array>} Promise of an observable array
*/
function getChildren(parentName) {
parentName = parentName || '';
var pattern = '*';
if (parentName) {
pattern = naming.join(parentName, pattern);
}
return glob(pattern);
}
/*
* Given a name and a glob search query returns a promise of an observable array
* of items as defined in @see item.js
* As new items become available the observable array will change to reflect
* the changes.
* @param {name} parentName Object name to search in.
* @param {string} pattern Glob search pattern.
* @return {Promise.<mercury.array>} Promise of an observable array
* of namespace items
*/
function search(parentName, pattern) {
parentName = parentName || '';
if (parentName) {
pattern = naming.join(parentName, pattern);
}
return glob(pattern);
}
/*
* Given a name, provide information about its mount point permissions.
* @param {string} objectName Object name to get permissions for.
* @return {Promise.<mercury.value<vanadium.security.Permissions>>} Promise of a
* vanadium.security.Permissions object.
*/
function getPermissions(name) {
return getSingleEvent('permissions', name, 'permissions').then(
function(perms) {
// perms is an object, but we want a map instead.
var p2 = new Map();
for (var key in perms) {
if (perms.hasOwnProperty(key)) {
p2.set(key, lowercasifyJSONObject(perms[key]));
}
}
return mercury.value(p2);
});
}
/*
* Deletes a mount point.
* @param {string} name mountpoint name to delete.
* @return {Promise<void>} Success or failure promise.
*/
function deleteMountPoint(name) {
// Note: The return value on success is undefined.
return getSingleEvent('deleteMountPoint', name, 'deleteMountPoint');
}
/*
* Given a name, provide information about its mounttable objectAddress.
* @param {string} objectName Object name to get mounttable objectAddress for.
* @return {Promise.<mercury.array<string>>} Promise of an array of
* objectAddress strings.
*/
function resolveToMounttable(name) {
return getSingleEvent('resolveToMounttable', name, 'addresses').then(
function(objectAddresses) {
return mercury.array(objectAddresses);
});
}
/*
* Given a name, provide information about its objectAddresses.
* @param {string} objectName Object name to get objectAddresses for.
* @return {Promise.<mercury.array<string>>} Promise of an observable value an
* array of string objectAddresses
*/
function getObjectAddresses(name) {
return getSingleEvent('objectAddresses', name, 'addresses').then(
function(objectAddresses) {
return mercury.array(objectAddresses);
});
}
/*
* remoteBlessingsCache holds (name, []string) cache entry for
* REMOTE_BLESSINGS_CACHE_MAX_SIZE items in an LRU cache
*/
var REMOTE_BLESSINGS_CACHE_MAX_SIZE = 10000;
var REMOTE_BLESSINGS_PREFIX = 'getRemoteBlessings|';
var remoteBlessingsCache = new LRU({
max: REMOTE_BLESSINGS_CACHE_MAX_SIZE
});
/*
* Given an object name, returns a promise of the service's remote blessings.
* @param {string} objectName Object name to get remote blessings for
* @return {[]string} remoteBlessings The service's remote blessings.
*/
function getRemoteBlessings(objectName) {
var cacheKey = REMOTE_BLESSINGS_PREFIX + objectName;
var cacheHit = remoteBlessingsCache.get(cacheKey);
if (cacheHit) {
return Promise.resolve(cacheHit);
}
return getSingleEvent('remoteBlessings', objectName, 'blessings').then(
function cacheAndReturnRemoteBlessings(remoteBlessings) {
// Remote Blessings is []string of the service's blessings.
remoteBlessingsCache.set(cacheKey, remoteBlessings);
return remoteBlessings;
});
}
/*
* signatureCache holds (name, signature) cache entry for
* SIGNATURE_CACHE_MAX_SIZE items in an LRU cache
*/
var SIGNATURE_CACHE_MAX_SIZE = 10000;
var SIGNATURE_CACHE_PREFIX = 'getSignature|';
var signatureCache = new LRU({
max: SIGNATURE_CACHE_MAX_SIZE
});
/*
* Given a object name, returns a promise of the signature of methods available
* on the object represented by that name.
* @param {string} objectName Object name to get signature for
* @return {signature} signature for the object represented by the given name
*/
function getSignature(objectName) {
var cacheKey = SIGNATURE_CACHE_PREFIX + objectName;
var cacheHit = signatureCache.get(cacheKey);
if (cacheHit) {
return Promise.resolve(cacheHit);
}
return getSingleEvent('signature', objectName, 'signature').then(
function cacheAndReturnSignature(signature) {
// Signature is []interface; each interface contains method data.
signatureCache.set(cacheKey, signature);
return signature;
});
}
// Go through the JSON object and lowercase everything recursively.
// We need this because it is annoying to change every Go struct to have the
// json annotation to lowercase its field name.
function lowercasifyJSONObject(obj) {
// number, string, boolean, or null
if (typeof obj !== 'object' || obj === null) {
return obj; // It's actually primitive.
}
// array
if (Array.isArray(obj)) {
var a = [];
for (var i = 0; i < obj.length; i++) {
a[i] = lowercasifyJSONObject(obj[i]);
}
return a;
}
// object
var cp = {};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
var lowerK = k[0].toLowerCase() + k.substr(1);
cp[lowerK] = lowercasifyJSONObject(obj[k]);
}
}
return cp;
}
/*
* Make an RPC call on a service object.
* name: string representing the name of the service
* methodName: string for the service method name
* args (optional): array of arguments for the service method
*/
function makeRPC(name, methodName, args, numOutArgs) {
log.debug('Calling', methodName, 'on', name, 'with', args, 'for', numOutArgs);
var call = {
name: name,
methodName: methodName,
args: args,
numOutArgs: numOutArgs
};
return getSingleEvent('makeRPC', call, 'response').then(function (result) {
// If the result was for 0 outArg, then this returns undefined.
// If the result was for 1 outArg, then it gets a single output.
// If the result was for >1 outArgs, then we return []output.
if (numOutArgs === 0) {
return;
} else if (numOutArgs === 1) {
return result[0];
}
return result;
});
}
/*
* Creates an observable struct representing basic information about
* an item in the namespace.
* @see item.js
* @param {MountEntry} mountEntry The mount entry from glob results.
* @return {Mercury.struct} observable struct representing basic information
* about an item.
*/
function createNamespaceItem(mountEntry) {
var name = mountEntry.name;
// mounted name relative to parent
var mountedName = naming.basename(name);
var isLeaf = mountEntry.isLeaf;
var hasServers = (mountEntry.servers && mountEntry.servers.length > 0);
var hasServer = hasServers || !mountEntry.servesMountTable;
var hasMountPoint = hasServers || mountEntry.servesMountTable;
var isMounttable = hasServers && mountEntry.servesMountTable;
var item = itemFactory.createItem({
objectName: name,
mountedName: mountedName,
isLeaf: isLeaf,
hasServer: hasServer,
hasMountPoint: hasMountPoint,
isMounttable: isMounttable
});
return item;
}
/*
* Given an arbitrary Vanadium name, parses it into an array
* of strings.
* For example, if name is '/ns.dev.v.io:8101/global/rps'
* returns ['ns.dev.v.io:8101', 'global', 'rps']
* Can use namespaceService.util.isRooted to see if the name
* is rooted (begins with a slash).
* Note that the address part can contain slashes.
*/
function parseName(name) {
var splitName = naming.splitAddressName(name);
var namespaceParts = [];
if (splitName.address) {
namespaceParts.push(splitName.address);
}
if (splitName.suffix) {
var suffixParts = splitName.suffix.split('/');
namespaceParts = namespaceParts.concat(suffixParts);
}
return namespaceParts;
}
/*
* Clears all caches (glob, signature, etc...) for the given name and all of its
* descendants.
* @param {string} parentName Name to clear caches for. If no name is given, all
* caches are cleared.
*/
function clearCache(parentName) {
if (!parentName) {
globCache.reset();
remoteBlessingsCache.reset();
signatureCache.reset();
return;
}
clearByPrefix(globCache, GLOB_CACHE_PREFIX + parentName);
clearByPrefix(remoteBlessingsCache, REMOTE_BLESSINGS_PREFIX + parentName);
clearByPrefix(signatureCache, SIGNATURE_CACHE_PREFIX + parentName);
function clearByPrefix(cache, parent) {
var keys = cache.keys();
keys.forEach(function(key) {
if (prefixes(parent, key)) {
cache.del(key);
}
});
}
}
/*
* Returns true iff parentName is a parent of childName or is same as childName
*/
function prefixes(parentName, childName) {
return (parentName === childName) ||
(childName.indexOf(naming.clean(parentName) + '/') === 0);
}
}).call(this,require("FWaASH"))
},{"../../lib/log":223,"../../lib/mercury/freeze":226,"../../lib/mercury/sorted-push-array":230,"./item":246,"./naming-util.js":247,"FWaASH":10,"events":8,"lru-cache":44,"mercury":45}],249:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var mercury = require('mercury');
var _ = require('lodash');
var EventEmitter = require('events').EventEmitter;
var arraySet = require('../../lib/array-set');
var freeze = require('../../lib/mercury/freeze');
var sortedPush = require('../../lib/mercury/sorted-push-array');
var namespaceService = require('../namespace/service');
var smartService = require('../smart/service');
var log = require('../../lib/log')('services:recommendations:service');
var LEARNER_KEY = 'learner-shortcut';
var MAX_NUM_RECOMMENDATIONS = 10;
module.exports = {
getAll: getAll,
getRecommendationScore: getRecommendationScore,
setRecommendationScore: setRecommendationScore
};
// Singleton state for all the bookmarks.
var recommendationsObs = mercury.array([]);
smartService.loadOrCreate(
LEARNER_KEY,
smartService.constants.LEARNER_SHORTCUT, {
k: MAX_NUM_RECOMMENDATIONS
}
).catch(function(err) {
log.error(err);
});
/*
* Gets all the namespace items that are recommended based on our learning agent
* As new recommendations become available/removed the observable array will
* change to reflect the changes.
*
* The observable result has an events property which is an EventEmitter
* and emits 'end', 'itemError' events.
*
* @return {Promise.<mercury.array>} Promise of an observable array
* of recommended items
*/
function getAll() {
// Empty out the array
recommendationsObs.splice(0, recommendationsObs.getLength());
var immutableRecommendationsObs = freeze(recommendationsObs);
immutableRecommendationsObs.events = new EventEmitter();
return smartService.predict(LEARNER_KEY).then(getRecommendationItems);
function getRecommendationItems(recs) {
var allItems = recs.map(function(rec) {
var name = rec.item;
return addNamespaceItem(name).catch(function(err) {
immutableRecommendationsObs.events.emit('itemError', {
name: name,
error: err
});
log.error('Failed to create item for "' + name + '"', err);
});
});
Promise.all(allItems).then(function() {
immutableRecommendationsObs.events.emit('end');
}).catch(function() {
immutableRecommendationsObs.events.emit('end');
});
return immutableRecommendationsObs;
}
}
/*
* Gets the namespace items for a name and adds it to the observable array
*/
function addNamespaceItem(name) {
return namespaceService.getNamespaceItem(name)
.then(function(item) {
var sorter = 'objectName';
sortedPush(recommendationsObs, item, sorter);
});
}
/*
* Get the score of a particular recommended object name.
*/
function getRecommendationScore(name) {
return smartService.predict(LEARNER_KEY, {
name: name,
penalize: false
}).then(function(res) {
var match = res.filter(function(rec) {
return rec.item === name;
})[0];
return match ? match.score : 0;
});
}
/*
* Set the score of a particular object name.
* Note: This will penalize (or boost) parents of the given name.
*/
function setRecommendationScore(name, newScore) {
if (newScore > 0) {
addNamespaceItem(name);
} else {
arraySet.set(recommendationsObs, null, false, indexOf.bind(null, name));
}
return getRecommendationScore(name).then(function(curScore) {
var delta = newScore - curScore;
return smartService.update(LEARNER_KEY, {
name: name,
weight: delta
}).then(function() {
return curScore;
});
}).catch(function(err) {
log.error('Failed to set the recommendation score of', name, 'to', newScore,
err);
});
}
/*
* Check the observe array for the index of the given item. -1 if not present.
*/
function indexOf(name) {
return _.findIndex(recommendationsObs(), function(rec) {
// Since recommendations can be assigned out of order, check for undefined.
return rec !== undefined && name === rec.objectName;
});
}
},{"../../lib/array-set":217,"../../lib/log":223,"../../lib/mercury/freeze":226,"../../lib/mercury/sorted-push-array":230,"../namespace/service":248,"../smart/service":251,"events":8,"lodash":43,"mercury":45}],250:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* smart-service-implementation includes this application's specific
* implementations of the smart-service.
*/
var addAttributes = require('../../lib/add-attributes');
var hashInterface = require('../namespace/interface-util').hashInterface;
var log = require('../../lib/log')('services:smart-service');
var perceptron = require('../../lib/learning/perceptron');
var rank = require('../../lib/learning/rank');
var _ = require('lodash');
var LEARNER_SHORTCUT = 1;
var LEARNER_AUTORPC = 2;
var LEARNER_METHOD_INPUT = 3;
var LEARNER_METHOD_INVOCATION = 4;
// Associate the learner types with the constructor
var LEARNER_MAP = {};
LEARNER_MAP[LEARNER_SHORTCUT] = shortcutLearner;
LEARNER_MAP[LEARNER_AUTORPC] = autoRPCLearner;
LEARNER_MAP[LEARNER_METHOD_INPUT] = methodInputLearner;
LEARNER_MAP[LEARNER_METHOD_INVOCATION] = methodInvocationLearner;
// Associate the learner types with additional functions.
// Note: update and predict are required.
var LEARNER_METHODS = {};
LEARNER_METHODS[LEARNER_SHORTCUT] = {
featureExtractor: shortcutLearnerFeatureExtractor,
update: shortcutLearnerUpdate,
predict: shortcutLearnerPredict
};
LEARNER_METHODS[LEARNER_AUTORPC] = {
featureExtractor: autoRPCLearnerFeatureExtractor,
update: autoRPCLearnerUpdate,
predict: autoRPCLearnerPredict
};
LEARNER_METHODS[LEARNER_METHOD_INPUT] = {
computeKey: methodInputLearnerComputeKey,
update: topKLearnerUpdate,
predict: topKLearnerPredict
};
LEARNER_METHODS[LEARNER_METHOD_INVOCATION] = {
computeKey: methodInvocationLearnerComputeKey,
update: topKLearnerUpdate,
predict: topKLearnerPredict
};
// Export the implementation constants
module.exports = {
LEARNER_SHORTCUT: LEARNER_SHORTCUT,
LEARNER_AUTORPC: LEARNER_AUTORPC,
LEARNER_METHOD_INPUT: LEARNER_METHOD_INPUT,
LEARNER_METHOD_INVOCATION: LEARNER_METHOD_INVOCATION,
LEARNER_MAP: LEARNER_MAP,
LEARNER_METHODS: LEARNER_METHODS
};
/*
* Create a shortcut learner that analyzes directory paths visited and predicts
* the most useful shortcuts.
* The expected attributes in params include:
* - k, the max # of shortcuts to return
*/
function shortcutLearner(type, params) {
this.directoryCount = {};
this.type = type;
this.params = params;
addAttributes(this, LEARNER_METHODS[type]);
}
/*
* Given an input name, return relevant features for the shortcut learner.
*/
function shortcutLearnerFeatureExtractor(name) {
return pathFeatureExtractor(name);
}
/*
* Given an input, extract the relevant feature vector and update the weights
* of the learner.
* input contains name and weight (default 1). Note: weight can be negative.
*/
function shortcutLearnerUpdate(input) {
var features = this.featureExtractor(input.name);
input.weight = input.weight || 1;
_.forOwn(features, function(value, key) {
if (this.directoryCount[key] === undefined) {
this.directoryCount[key] = 0;
}
this.directoryCount[key] += features[key] * input.weight;
}, this);
}
/*
* Given an input, determine which children are most popular.
* The input should have "name" (string) and "exclude" (Array<string>).
*/
function shortcutLearnerPredict(input) {
// Make sure to set proper defaults for bad input.
var defaults = {
name: '',
exclude: [],
penalize: true
};
input = _.assign({}, defaults, input);
// Also ensure that k, the number of children to return, is defined.
var k = this.params.k || 1;
var penalize = input.penalize;
log.debug('Predict top', k, 'children under', input.name, 'excluding',
input.exclude);
// First score the items that are prefixed by the input name.
// Separate the scored items from the excluded items.
var scoredItems = [];
var excludedItems = [];
_.forOwn(this.directoryCount, function(score, item) {
if (item.indexOf(input.name) === 0) {
var scoredItem = {
item: item,
score: score
};
if (input.exclude.indexOf(item) === -1) {
scoredItems.push(scoredItem);
} else {
excludedItems.push(scoredItem);
}
}
});
// Next, penalize all scoredItems by the excludedItems.
if (penalize) {
excludedItems.forEach(function(excludedItem) {
rank.applyDiversityPenalty(
scoredItems,
excludedItem,
shortcutLearnerFeatureExtractor,
excludedItem.score
);
});
}
// Then determine the top k items including diversity.
// TODO(alexfandrianto): This step forces us to take O(kn) runtime. Is there a
// faster way to find the 'best' shortcuts?
var topK = [];
for (var i = 0; i < k; i++) {
var bestItemIndex = rank.getBestItemIndex(scoredItems);
if (bestItemIndex >= 0) {
topK.push(scoredItems[bestItemIndex]);
} else {
return topK; // return early since there are no more top items.
}
// If we haven't yet found all topK, penalize similar items.
if (i < k - 1) {
// Remove the most recent top item, and return early if we can.
scoredItems.splice(bestItemIndex, 1);
if (scoredItems.length === 0) {
return topK;
}
// Otherwise, penalize all remaining items.
if (penalize) {
rank.applyDiversityPenalty(
scoredItems,
topK[i],
shortcutLearnerFeatureExtractor,
topK[i].score
);
}
}
}
return topK;
}
/*
* TODO(alexfandrianto): Don't ignore 'params'. Improve this algorithm.
* Create an autorpc learner that learns which RPCs should be performed
* automatically.
*/
function autoRPCLearner(type, params) {
this.weights = {};
this.type = type;
this.learningRate = 0.05;
addAttributes(this, LEARNER_METHODS[type]);
}
/*
* Given input data, return an appropriate feature vector for RPCs.
* Input must have: methodName, interface, and name.
*/
function autoRPCLearnerFeatureExtractor(input) {
var features = {};
// The user may have an innate bias for making RPCs.
features['_biasTerm'] = 1;
// Same-named methods may act similarly and might want to be queried too.
features[input.methodName] = 1;
// Same-named methods that share service interfaces are likely similar.
features[input.methodName + '|' + hashInterface(input.interface)] = 1;
// Services in the same namespace subtree may be queried similarly.
var pathFeatures = pathFeatureExtractor(input.name);
addAttributes(features, pathFeatures);
// Services in the same namespace subtree with this method name are also
// likely to be queried similarly.
for (var key in pathFeatures) {
if (pathFeatures.hasOwnProperty(key)) {
features[input.methodName + '|' + key] = pathFeatures[key];
}
}
return features;
}
/*
* Given input data, update the learner's weights.
* Input must have: methodName, interface, name, and reward.
* TODO(alexfandrianto): Remove the weights printout.
*/
function autoRPCLearnerUpdate(input) {
perceptron.update(
this.weights,
this.featureExtractor(input),
input.reward,
this.learningRate
);
log.debug('Final weights: ', this.weights);
}
/*
* Given input data, return the predicted reward.
*/
function autoRPCLearnerPredict(input) {
return perceptron.predict(this.weights, this.featureExtractor(input));
}
/*
* Create a method input learner that suggests the most likely inputs to a
* given argument of a method.
* Params can optionally include:
* - minThreshold, the minimum score of a suggestable value
* - maxValues, the largest number of suggestable values that may be returned
* - penalty, a constant for the rate to penalize incorrect suggestions
* - reward, a constant for the rate to reward chosen values
*
* Uses a simple topK Update and Prediction function.
* This learner's input needs to have argName, methodName, and interface.
* Update also needs an argument value.
*/
function methodInputLearner(type, params) {
this.type = type;
this.inputMap = {}; // map[string]map[string]number
// Override the default params with relevant fields from params.
this.params = {
penalty: 0.1,
reward: 0.4
};
_.assign(this.params, params);
addAttributes(this, LEARNER_METHODS[type]);
}
/*
* Given input data, compute the appropriate lookup key.
*/
function methodInputLearnerComputeKey(input) {
var keyArr = [
hashInterface(input.interface),
input.methodName,
input.argName
];
return keyArr.join('|');
}
/*
* Create a method invocation learner that suggests the most likely invocations
* for a given method.
* Params can optionally include:
* - minThreshold, the minimum score of a suggestable value
* - maxValues, the largest number of suggestable values that may be returned
* - penalty, a constant for the rate to penalize incorrect suggestions
* - reward, a constant for the rate to reward chosen values
*
* Uses a simple topK Update and Prediction function.
* This learner's input needs to have a methodName and interface.
* Update also needs a JSON-encoded arguments string.
*/
function methodInvocationLearner(type, params) {
this.type = type;
this.inputMap = {}; // map[string]map[string]number
// Override the default params with relevant fields from params.
this.params = {
penalty: 0.1,
reward: 0.4
};
_.assign(this.params, params);
addAttributes(this, LEARNER_METHODS[type]);
}
/*
* Given input data, compute the appropriate lookup key
* Input must have: methodName and interface.
*/
function methodInvocationLearnerComputeKey(input) {
var keyArr = [
hashInterface(input.interface),
input.methodName
];
return keyArr.join('|');
}
/*
* Given input data, boost the rank of the given value and penalize others.
* Note: Learners using this predict function need to be similar structurally.
* input can contain:
* - fields used to compute the key
* - value to update for that key
* - (optional) reset: a flag that resets the value
*/
function topKLearnerUpdate(input) {
var key = this.computeKey(input);
var predValues = this.predict(input);
var value = input.value;
// Setup the inputMap and values if not yet defined.
if (this.inputMap[key] === undefined) {
this.inputMap[key] = {};
}
var values = this.inputMap[key];
if (values[value] === undefined) {
values[value] = 0;
}
// Reset the value (for negative feedback).
if (input.reset) {
delete values[value];
return;
}
// Give a reward to the chosen value.
values[value] += this.params.reward * (1 - values[value]);
// Induce a penalty on failed predictions.
for (var i = 0; i < predValues.length; i++) {
var pred = predValues[i];
if (pred !== value) {
values[pred] += this.params.penalty * (0 - values[pred]);
}
}
}
/*
* Given input data, predict the most likely values.
* Note: Learners using this predict function need to be similar structurally.
*/
function topKLearnerPredict(input) {
var key = this.computeKey(input);
var values = this.inputMap[key];
// Immediately return nothing if there are no values to suggest.
if (values === undefined) {
return [];
}
// Convert the values to scored items for ranking.
var scoredItems = Object.getOwnPropertyNames(values).map(
function getScoredItem(value) {
return {
item: value,
score: values[value]
};
}
);
// Filter the scored items by minThreshold
if (this.params.minThreshold !== undefined) {
scoredItems = scoredItems.filter(function applyThreshold(scoredItem) {
return scoredItem.score >= this.params.minThreshold;
}, this);
}
// Rank the scored items and return the top values (limit to maxValues)
var maxValues = this.params.maxValues;
if (maxValues === undefined || maxValues < 0) {
maxValues = scoredItems.length;
}
var bestK = rank.getBestKItems(scoredItems, maxValues);
return bestK === null ? [] : bestK.map(function(goodItem) {
return goodItem.item;
});
}
/*
* Given a path string, this feature extractor assigns diminishing returns
* credit to each ancestor along the path.
*/
function pathFeatureExtractor(path) {
var vector = {};
var split = path.split('/');
var growingPath = '';
for (var i = 0; i < split.length; i++) {
if (split[i] === '') {
continue;
}
if (i === 0) {
growingPath += split[i];
} else {
growingPath += '/' + split[i];
}
// give 1, 1/2, 1/4, 1/8, ... credit assignment
vector[growingPath] = Math.pow(2, i+1-split.length);
}
return vector;
}
},{"../../lib/add-attributes":216,"../../lib/learning/perceptron":220,"../../lib/learning/rank":221,"../../lib/log":223,"../namespace/interface-util":245,"lodash":43}],251:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* smart-service provides an asynchronous interface for machine learning.
* Hooks to this service should make updates and ask for predictions.
* A few basic learners are implemented as wrappers around the learning library.
*/
var addAttributes = require('../../lib/add-attributes');
var store = require('../../lib/store');
var log = require('../../lib/log')('services:smart-service');
var constants = require('./service-implementation');
var extendDefaults = require('../../lib/extend-defaults');
// Export methods and constants
module.exports = {
loadOrCreate: loadOrCreate,
reset: reset,
save: save,
update: update,
predict: predict,
constants: constants
};
// This caches the learners loaded into memory.
var learners = {};
/*
* Given an id, type, and parameters, return a promise that attempts to load the
* learner from the store, and failing that, creates a new one.
*
* Registers and resolves the learner upon success.
* Rejects when the id is taken, or the type is invalid.
*/
function loadOrCreate(id, type, params) {
log.debug('load or create', id, type, params);
if (learners[id] !== undefined) {
return Promise.reject('Cannot reuse learner id ' + id);
}
// Store the learner right away. Calls to get should use this promise.
learners[id] = load(id).then(function loadSuccess(learner) {
log.debug('loaded learner', id);
learner.params = extendDefaults(learner.params, params);
return Promise.resolve(learner);
}, function loadFailure() {
return create(id, type, params).then(function(learner) {
log.debug('created learner', id);
return Promise.resolve(learner);
});
}).catch(function(err) {
log.error('Unable to load or create', id, err);
return Promise.reject(err);
});
return learners[id];
}
/*
* Return a promise containing the learner at the given id. The promise rejects
* if that learner has not been registered yet.
*/
function get(id) {
if (learners[id] === undefined) {
return Promise.reject('Unused learner id ' + id);
}
return learners[id];
}
/*
* Return a promise to delete from the store and in-memory buffer.
*/
function reset(id) {
log.debug('reset', id);
return store.removeValue(id).then(function() {
if (learners[id] === undefined) {
return Promise.reject('Cannot reset unused learner id ' + id);
}
delete learners[id];
}).catch(function(err) {
log.error('Failed to reset learner id:', id, err);
return Promise.reject(err);
});
}
/*
* Given an id, return a promise that saves the learner to the store.
*/
function save(id) {
if (learners[id] === undefined) {
return Promise.reject('Cannot save unused learner id ' + id);
}
return learners[id].then(function(learner) {
return store.setValue(id, learner);
}).catch(function(err) {
log.error('Unable to save learner', err);
return Promise.reject(err);
});
}
/*
* Given an id and input, return a promise to update the corresponding learner
* with that input and save to the store.
*/
function update(id, input) {
return get(id).then(function(learner) {
learner.update(input);
return save(id);
});
}
/*
* Given an id and input, return a promise that uses the corresponding learner
* to make a prediction on the input.
*/
function predict(id, input) {
return get(id).then(function(learner) {
return learner.predict(input);
});
}
/*
* Helper function; returns a promise to create a new learner.
*/
function create(id, type, params) {
log.debug('create', id, type, params);
if (constants.LEARNER_MAP[type] === undefined) {
return Promise.reject('Could not resolve learner type ' + type);
} else {
var LearnerConstructor = constants.LEARNER_MAP[type];
var learner = new LearnerConstructor(type, params);
return Promise.resolve(learner);
}
}
/*
* Helper function; returns a promise that loads a new learner from the store.
* Rejects if the value is null.
*/
function load(id) {
log.debug('load', id);
return store.getValue(id).then(function(learner) {
if (learner === null) {
return Promise.reject('Learner ' + id + ' was not present in the store.');
} else {
log.debug('Loaded Learner:', learner);
// Attach the learner's functions, then resolve.
addAttributes(learner, constants.LEARNER_METHODS[learner.type]);
return Promise.resolve(learner);
}
});
}
},{"../../lib/add-attributes":216,"../../lib/extend-defaults":219,"../../lib/log":223,"../../lib/store":232,"./service-implementation":250}],252:[function(require,module,exports){
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var store = require('../../lib/store');
var log = require('../../lib/log')('services:state:service');
var NAMESPACE_INDEX = 'index';
var SIDE_PANEL_WIDTH = 'sidePanelWidth';
var BROWSE_VIEW_TYPE = 'browseViewType';
module.exports = {
saveNamespace: saveNamespace,
loadNamespace: loadNamespace,
saveSidePanelWidth: saveSidePanelWidth,
loadSidePanelWidth: loadSidePanelWidth,
saveBrowseViewType: saveBrowseViewType,
loadBrowseViewType: loadBrowseViewType
};
// Save the namespace index to the store.
function saveNamespace(namespace) {
return store.setValue(NAMESPACE_INDEX, namespace).catch(function(err) {
log.warn('Unable to persist namespace index', namespace, err);
});
}
// Load the namespace index from the store.
// On any failure, use the default value instead.
function loadNamespace() {
// TODO(aghassemi): Do we want to point to v.io by default?
var defaultIndex = '/ns.dev.v.io:8101';
return store.getValue(NAMESPACE_INDEX).then(function(namespace) {
return namespace !== null ? namespace : defaultIndex;
}).catch(function(err) {
log.warn('Unable to access stored namespace index', err);
return defaultIndex;
});
}
// Save the side panel width to the store.
function saveSidePanelWidth(width) {
return store.setValue(SIDE_PANEL_WIDTH, width
).catch(function(err) {
log.error(err);
});
}
// Load the side panel width from the store.
// On any failure, use the default value instead.
function loadSidePanelWidth() {
var defaultWidth = '50%';
return store.getValue(SIDE_PANEL_WIDTH).then(function(width) {
return width !== null ? width : defaultWidth;
}).catch(function(err) {
log.warn('Unable to access stored side panel width', err);
return defaultWidth;
});
}
// Save the browse view type to the store.
function saveBrowseViewType(view) {
return store.setValue(BROWSE_VIEW_TYPE, view
).catch(function(err) {
log.error(err);
});
}
// Load the browse view type from the store.
// On any failure, use the default value instead.
function loadBrowseViewType() {
var defaultView = 'tree';
return store.getValue(BROWSE_VIEW_TYPE).then(function(view) {
return view !== null ? view : defaultView;
}).catch(function(err) {
log.warn('Unable to access stored browse view', err);
return defaultView;
});
}
},{"../../lib/log":223,"../../lib/store":232}]},{},[144])
//# sourceMappingURL=bundle.js.map