You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5307 lines
171 KiB
JavaScript

/**
* Modules in this bundle
* @license
*
* power-assert-renderers:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* homepage: http://github.com/twada/power-assert-renderers
* version: 0.1.1
*
* core-js:
* license: MIT (http://opensource.org/licenses/MIT)
* maintainers: zloirock <zloirock@zloirock.ru>
* homepage: https://github.com/zloirock/core-js#readme
* version: 2.4.0
*
* eastasianwidth:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Masaki Komagata
* maintainers: komagata <komagata@gmail.com>
* homepage: https://github.com/komagata/eastasianwidth#readme
* version: 0.1.1
*
* googlediff:
* licenses: Apache (http://opensource.org/licenses/Apache-2.0)
* author: Neil Fraser <root@neil.fraser.name>
* maintainers: shimondoodkin <helpmepro1@gmail.com>
* contributors: Shimon Doodkin <helpmepro1@gmail.com>, Ryan Graham <r.m.graham@gmail.com>
* homepage: http://code.google.com/p/google-diff-match-patch/
* version: 0.1.0
*
* inherits:
* license: ISC (http://opensource.org/licenses/ISC)
* maintainers: isaacs <i@izs.me>
* homepage: https://github.com/isaacs/inherits#readme
* version: 2.0.1
*
* power-assert-renderer-assertion:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* maintainers: twada <takuto.wada@gmail.com>
* homepage: https://github.com/twada/power-assert-runtime
* version: 1.0.1
*
* power-assert-renderer-base:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* maintainers: twada <takuto.wada@gmail.com>
* homepage: https://github.com/twada/power-assert-runtime
* version: 1.0.2
*
* power-assert-renderer-comparison:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* maintainers: twada <takuto.wada@gmail.com>
* homepage: https://github.com/twada/power-assert-runtime
* version: 1.0.6
*
* power-assert-renderer-diagram:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* maintainers: twada <takuto.wada@gmail.com>
* homepage: https://github.com/twada/power-assert-runtime
* version: 1.0.6
*
* power-assert-renderer-file:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* maintainers: twada <takuto.wada@gmail.com>
* homepage: https://github.com/twada/power-assert-runtime
* version: 1.0.1
*
* power-assert-renderer-succinct:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* maintainers: twada <takuto.wada@gmail.com>
* homepage: https://github.com/twada/power-assert-runtime
* version: 1.0.1
*
* process:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Roman Shtylman <shtylman@gmail.com>
* maintainers: coolaj86 <coolaj86@gmail.com>, cwmma <calvin.metcalf@gmail.com>, defunctzombie <shtylman@gmail.com>
* homepage: https://github.com/shtylman/node-process#readme
* version: 0.11.3
*
* stringifier:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* maintainers: twada <takuto.wada@gmail.com>
* homepage: https://github.com/twada/stringifier
* version: 1.3.0
*
* traverse:
* license: MIT (http://opensource.org/licenses/MIT)
* author: James Halliday <mail@substack.net>
* maintainers: substack <mail@substack.net>
* homepage: https://github.com/substack/js-traverse
* version: 0.6.6
*
* type-name:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Takuto Wada <takuto.wada@gmail.com>
* maintainers: twada <takuto.wada@gmail.com>
* contributors: azu, Yosuke Furukawa
* homepage: https://github.com/twada/type-name
* version: 2.0.1
*
* util:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Joyent
* maintainers: shtylman <shtylman@gmail.com>
* homepage: https://github.com/defunctzombie/node-util
* version: 0.10.3
*
* This header is generated by licensify (https://github.com/twada/licensify)
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.powerAssertRenderers = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* power-assert-renderers.js - Power Assert output renderers
*
* https://github.com/twada/power-assert-renderers
*
* Copyright (c) 2015-2016 Takuto Wada
* Licensed under the MIT license.
* https://github.com/twada/power-assert-renderers/blob/master/MIT-LICENSE.txt
*/
'use strict';
module.exports = {
FileRenderer: _dereq_('power-assert-renderer-file'),
AssertionRenderer: _dereq_('power-assert-renderer-assertion'),
DiagramRenderer: _dereq_('power-assert-renderer-diagram'),
BinaryExpressionRenderer: _dereq_('power-assert-renderer-comparison'),
SuccinctRenderer: _dereq_('power-assert-renderer-succinct')
};
},{"power-assert-renderer-assertion":62,"power-assert-renderer-comparison":64,"power-assert-renderer-diagram":67,"power-assert-renderer-file":70,"power-assert-renderer-succinct":71}],2:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.array.filter');
module.exports = _dereq_('../../modules/_core').Array.filter;
},{"../../modules/_core":17,"../../modules/es6.array.filter":51}],3:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.array.for-each');
module.exports = _dereq_('../../modules/_core').Array.forEach;
},{"../../modules/_core":17,"../../modules/es6.array.for-each":52}],4:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.array.index-of');
module.exports = _dereq_('../../modules/_core').Array.indexOf;
},{"../../modules/_core":17,"../../modules/es6.array.index-of":53}],5:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.array.reduce-right');
module.exports = _dereq_('../../modules/_core').Array.reduceRight;
},{"../../modules/_core":17,"../../modules/es6.array.reduce-right":54}],6:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.array.some');
module.exports = _dereq_('../../modules/_core').Array.some;
},{"../../modules/_core":17,"../../modules/es6.array.some":55}],7:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.assign');
module.exports = _dereq_('../../modules/_core').Object.assign;
},{"../../modules/_core":17,"../../modules/es6.object.assign":56}],8:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.keys');
module.exports = _dereq_('../../modules/_core').Object.keys;
},{"../../modules/_core":17,"../../modules/es6.object.keys":57}],9:[function(_dereq_,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],10:[function(_dereq_,module,exports){
var isObject = _dereq_('./_is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./_is-object":31}],11:[function(_dereq_,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = _dereq_('./_to-iobject')
, toLength = _dereq_('./_to-length')
, toIndex = _dereq_('./_to-index');
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"./_to-index":43,"./_to-iobject":45,"./_to-length":46}],12:[function(_dereq_,module,exports){
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = _dereq_('./_ctx')
, IObject = _dereq_('./_iobject')
, toObject = _dereq_('./_to-object')
, toLength = _dereq_('./_to-length')
, asc = _dereq_('./_array-species-create');
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
},{"./_array-species-create":15,"./_ctx":18,"./_iobject":29,"./_to-length":46,"./_to-object":47}],13:[function(_dereq_,module,exports){
var aFunction = _dereq_('./_a-function')
, toObject = _dereq_('./_to-object')
, IObject = _dereq_('./_iobject')
, toLength = _dereq_('./_to-length');
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
},{"./_a-function":9,"./_iobject":29,"./_to-length":46,"./_to-object":47}],14:[function(_dereq_,module,exports){
var isObject = _dereq_('./_is-object')
, isArray = _dereq_('./_is-array')
, SPECIES = _dereq_('./_wks')('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
},{"./_is-array":30,"./_is-object":31,"./_wks":50}],15:[function(_dereq_,module,exports){
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = _dereq_('./_array-species-constructor');
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
},{"./_array-species-constructor":14}],16:[function(_dereq_,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],17:[function(_dereq_,module,exports){
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],18:[function(_dereq_,module,exports){
// optional / simple context binding
var aFunction = _dereq_('./_a-function');
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"./_a-function":9}],19:[function(_dereq_,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],20:[function(_dereq_,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !_dereq_('./_fails')(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_fails":24}],21:[function(_dereq_,module,exports){
var isObject = _dereq_('./_is-object')
, document = _dereq_('./_global').document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"./_global":25,"./_is-object":31}],22:[function(_dereq_,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],23:[function(_dereq_,module,exports){
var global = _dereq_('./_global')
, core = _dereq_('./_core')
, ctx = _dereq_('./_ctx')
, hide = _dereq_('./_hide')
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"./_core":17,"./_ctx":18,"./_global":25,"./_hide":27}],24:[function(_dereq_,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],25:[function(_dereq_,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],26:[function(_dereq_,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],27:[function(_dereq_,module,exports){
var dP = _dereq_('./_object-dp')
, createDesc = _dereq_('./_property-desc');
module.exports = _dereq_('./_descriptors') ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"./_descriptors":20,"./_object-dp":33,"./_property-desc":39}],28:[function(_dereq_,module,exports){
module.exports = !_dereq_('./_descriptors') && !_dereq_('./_fails')(function(){
return Object.defineProperty(_dereq_('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_descriptors":20,"./_dom-create":21,"./_fails":24}],29:[function(_dereq_,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = _dereq_('./_cof');
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./_cof":16}],30:[function(_dereq_,module,exports){
// 7.2.2 IsArray(argument)
var cof = _dereq_('./_cof');
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
},{"./_cof":16}],31:[function(_dereq_,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],32:[function(_dereq_,module,exports){
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = _dereq_('./_object-keys')
, gOPS = _dereq_('./_object-gops')
, pIE = _dereq_('./_object-pie')
, toObject = _dereq_('./_to-object')
, IObject = _dereq_('./_iobject')
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || _dereq_('./_fails')(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
},{"./_fails":24,"./_iobject":29,"./_object-gops":34,"./_object-keys":36,"./_object-pie":37,"./_to-object":47}],33:[function(_dereq_,module,exports){
var anObject = _dereq_('./_an-object')
, IE8_DOM_DEFINE = _dereq_('./_ie8-dom-define')
, toPrimitive = _dereq_('./_to-primitive')
, dP = Object.defineProperty;
exports.f = _dereq_('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
},{"./_an-object":10,"./_descriptors":20,"./_ie8-dom-define":28,"./_to-primitive":48}],34:[function(_dereq_,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],35:[function(_dereq_,module,exports){
var has = _dereq_('./_has')
, toIObject = _dereq_('./_to-iobject')
, arrayIndexOf = _dereq_('./_array-includes')(false)
, IE_PROTO = _dereq_('./_shared-key')('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"./_array-includes":11,"./_has":26,"./_shared-key":40,"./_to-iobject":45}],36:[function(_dereq_,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = _dereq_('./_object-keys-internal')
, enumBugKeys = _dereq_('./_enum-bug-keys');
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
},{"./_enum-bug-keys":22,"./_object-keys-internal":35}],37:[function(_dereq_,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],38:[function(_dereq_,module,exports){
// most Object methods by ES6 should accept primitives
var $export = _dereq_('./_export')
, core = _dereq_('./_core')
, fails = _dereq_('./_fails');
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
},{"./_core":17,"./_export":23,"./_fails":24}],39:[function(_dereq_,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],40:[function(_dereq_,module,exports){
var shared = _dereq_('./_shared')('keys')
, uid = _dereq_('./_uid');
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
},{"./_shared":41,"./_uid":49}],41:[function(_dereq_,module,exports){
var global = _dereq_('./_global')
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"./_global":25}],42:[function(_dereq_,module,exports){
var fails = _dereq_('./_fails');
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
},{"./_fails":24}],43:[function(_dereq_,module,exports){
var toInteger = _dereq_('./_to-integer')
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./_to-integer":44}],44:[function(_dereq_,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],45:[function(_dereq_,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = _dereq_('./_iobject')
, defined = _dereq_('./_defined');
module.exports = function(it){
return IObject(defined(it));
};
},{"./_defined":19,"./_iobject":29}],46:[function(_dereq_,module,exports){
// 7.1.15 ToLength
var toInteger = _dereq_('./_to-integer')
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./_to-integer":44}],47:[function(_dereq_,module,exports){
// 7.1.13 ToObject(argument)
var defined = _dereq_('./_defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./_defined":19}],48:[function(_dereq_,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = _dereq_('./_is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"./_is-object":31}],49:[function(_dereq_,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],50:[function(_dereq_,module,exports){
var store = _dereq_('./_shared')('wks')
, uid = _dereq_('./_uid')
, Symbol = _dereq_('./_global').Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"./_global":25,"./_shared":41,"./_uid":49}],51:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_('./_export')
, $filter = _dereq_('./_array-methods')(2);
$export($export.P + $export.F * !_dereq_('./_strict-method')([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":12,"./_export":23,"./_strict-method":42}],52:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_('./_export')
, $forEach = _dereq_('./_array-methods')(0)
, STRICT = _dereq_('./_strict-method')([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":12,"./_export":23,"./_strict-method":42}],53:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_('./_export')
, $indexOf = _dereq_('./_array-includes')(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !_dereq_('./_strict-method')($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
},{"./_array-includes":11,"./_export":23,"./_strict-method":42}],54:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_('./_export')
, $reduce = _dereq_('./_array-reduce');
$export($export.P + $export.F * !_dereq_('./_strict-method')([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
},{"./_array-reduce":13,"./_export":23,"./_strict-method":42}],55:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_('./_export')
, $some = _dereq_('./_array-methods')(3);
$export($export.P + $export.F * !_dereq_('./_strict-method')([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":12,"./_export":23,"./_strict-method":42}],56:[function(_dereq_,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = _dereq_('./_export');
$export($export.S + $export.F, 'Object', {assign: _dereq_('./_object-assign')});
},{"./_export":23,"./_object-assign":32}],57:[function(_dereq_,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = _dereq_('./_to-object')
, $keys = _dereq_('./_object-keys');
_dereq_('./_object-sap')('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
},{"./_object-keys":36,"./_object-sap":38,"./_to-object":47}],58:[function(_dereq_,module,exports){
var eaw = {};
if ('undefined' == typeof module) {
window.eastasianwidth = eaw;
} else {
module.exports = eaw;
}
eaw.eastAsianWidth = function(character) {
var x = character.charCodeAt(0);
var y = (character.length == 2) ? character.charCodeAt(1) : 0;
var codePoint = x;
if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) {
x &= 0x3FF;
y &= 0x3FF;
codePoint = (x << 10) | y;
codePoint += 0x10000;
}
if ((0x3000 == codePoint) ||
(0xFF01 <= codePoint && codePoint <= 0xFF60) ||
(0xFFE0 <= codePoint && codePoint <= 0xFFE6)) {
return 'F';
}
if ((0x20A9 == codePoint) ||
(0xFF61 <= codePoint && codePoint <= 0xFFBE) ||
(0xFFC2 <= codePoint && codePoint <= 0xFFC7) ||
(0xFFCA <= codePoint && codePoint <= 0xFFCF) ||
(0xFFD2 <= codePoint && codePoint <= 0xFFD7) ||
(0xFFDA <= codePoint && codePoint <= 0xFFDC) ||
(0xFFE8 <= codePoint && codePoint <= 0xFFEE)) {
return 'H';
}
if ((0x1100 <= codePoint && codePoint <= 0x115F) ||
(0x11A3 <= codePoint && codePoint <= 0x11A7) ||
(0x11FA <= codePoint && codePoint <= 0x11FF) ||
(0x2329 <= codePoint && codePoint <= 0x232A) ||
(0x2E80 <= codePoint && codePoint <= 0x2E99) ||
(0x2E9B <= codePoint && codePoint <= 0x2EF3) ||
(0x2F00 <= codePoint && codePoint <= 0x2FD5) ||
(0x2FF0 <= codePoint && codePoint <= 0x2FFB) ||
(0x3001 <= codePoint && codePoint <= 0x303E) ||
(0x3041 <= codePoint && codePoint <= 0x3096) ||
(0x3099 <= codePoint && codePoint <= 0x30FF) ||
(0x3105 <= codePoint && codePoint <= 0x312D) ||
(0x3131 <= codePoint && codePoint <= 0x318E) ||
(0x3190 <= codePoint && codePoint <= 0x31BA) ||
(0x31C0 <= codePoint && codePoint <= 0x31E3) ||
(0x31F0 <= codePoint && codePoint <= 0x321E) ||
(0x3220 <= codePoint && codePoint <= 0x3247) ||
(0x3250 <= codePoint && codePoint <= 0x32FE) ||
(0x3300 <= codePoint && codePoint <= 0x4DBF) ||
(0x4E00 <= codePoint && codePoint <= 0xA48C) ||
(0xA490 <= codePoint && codePoint <= 0xA4C6) ||
(0xA960 <= codePoint && codePoint <= 0xA97C) ||
(0xAC00 <= codePoint && codePoint <= 0xD7A3) ||
(0xD7B0 <= codePoint && codePoint <= 0xD7C6) ||
(0xD7CB <= codePoint && codePoint <= 0xD7FB) ||
(0xF900 <= codePoint && codePoint <= 0xFAFF) ||
(0xFE10 <= codePoint && codePoint <= 0xFE19) ||
(0xFE30 <= codePoint && codePoint <= 0xFE52) ||
(0xFE54 <= codePoint && codePoint <= 0xFE66) ||
(0xFE68 <= codePoint && codePoint <= 0xFE6B) ||
(0x1B000 <= codePoint && codePoint <= 0x1B001) ||
(0x1F200 <= codePoint && codePoint <= 0x1F202) ||
(0x1F210 <= codePoint && codePoint <= 0x1F23A) ||
(0x1F240 <= codePoint && codePoint <= 0x1F248) ||
(0x1F250 <= codePoint && codePoint <= 0x1F251) ||
(0x20000 <= codePoint && codePoint <= 0x2F73F) ||
(0x2B740 <= codePoint && codePoint <= 0x2FFFD) ||
(0x30000 <= codePoint && codePoint <= 0x3FFFD)) {
return 'W';
}
if ((0x0020 <= codePoint && codePoint <= 0x007E) ||
(0x00A2 <= codePoint && codePoint <= 0x00A3) ||
(0x00A5 <= codePoint && codePoint <= 0x00A6) ||
(0x00AC == codePoint) ||
(0x00AF == codePoint) ||
(0x27E6 <= codePoint && codePoint <= 0x27ED) ||
(0x2985 <= codePoint && codePoint <= 0x2986)) {
return 'Na';
}
if ((0x00A1 == codePoint) ||
(0x00A4 == codePoint) ||
(0x00A7 <= codePoint && codePoint <= 0x00A8) ||
(0x00AA == codePoint) ||
(0x00AD <= codePoint && codePoint <= 0x00AE) ||
(0x00B0 <= codePoint && codePoint <= 0x00B4) ||
(0x00B6 <= codePoint && codePoint <= 0x00BA) ||
(0x00BC <= codePoint && codePoint <= 0x00BF) ||
(0x00C6 == codePoint) ||
(0x00D0 == codePoint) ||
(0x00D7 <= codePoint && codePoint <= 0x00D8) ||
(0x00DE <= codePoint && codePoint <= 0x00E1) ||
(0x00E6 == codePoint) ||
(0x00E8 <= codePoint && codePoint <= 0x00EA) ||
(0x00EC <= codePoint && codePoint <= 0x00ED) ||
(0x00F0 == codePoint) ||
(0x00F2 <= codePoint && codePoint <= 0x00F3) ||
(0x00F7 <= codePoint && codePoint <= 0x00FA) ||
(0x00FC == codePoint) ||
(0x00FE == codePoint) ||
(0x0101 == codePoint) ||
(0x0111 == codePoint) ||
(0x0113 == codePoint) ||
(0x011B == codePoint) ||
(0x0126 <= codePoint && codePoint <= 0x0127) ||
(0x012B == codePoint) ||
(0x0131 <= codePoint && codePoint <= 0x0133) ||
(0x0138 == codePoint) ||
(0x013F <= codePoint && codePoint <= 0x0142) ||
(0x0144 == codePoint) ||
(0x0148 <= codePoint && codePoint <= 0x014B) ||
(0x014D == codePoint) ||
(0x0152 <= codePoint && codePoint <= 0x0153) ||
(0x0166 <= codePoint && codePoint <= 0x0167) ||
(0x016B == codePoint) ||
(0x01CE == codePoint) ||
(0x01D0 == codePoint) ||
(0x01D2 == codePoint) ||
(0x01D4 == codePoint) ||
(0x01D6 == codePoint) ||
(0x01D8 == codePoint) ||
(0x01DA == codePoint) ||
(0x01DC == codePoint) ||
(0x0251 == codePoint) ||
(0x0261 == codePoint) ||
(0x02C4 == codePoint) ||
(0x02C7 == codePoint) ||
(0x02C9 <= codePoint && codePoint <= 0x02CB) ||
(0x02CD == codePoint) ||
(0x02D0 == codePoint) ||
(0x02D8 <= codePoint && codePoint <= 0x02DB) ||
(0x02DD == codePoint) ||
(0x02DF == codePoint) ||
(0x0300 <= codePoint && codePoint <= 0x036F) ||
(0x0391 <= codePoint && codePoint <= 0x03A1) ||
(0x03A3 <= codePoint && codePoint <= 0x03A9) ||
(0x03B1 <= codePoint && codePoint <= 0x03C1) ||
(0x03C3 <= codePoint && codePoint <= 0x03C9) ||
(0x0401 == codePoint) ||
(0x0410 <= codePoint && codePoint <= 0x044F) ||
(0x0451 == codePoint) ||
(0x2010 == codePoint) ||
(0x2013 <= codePoint && codePoint <= 0x2016) ||
(0x2018 <= codePoint && codePoint <= 0x2019) ||
(0x201C <= codePoint && codePoint <= 0x201D) ||
(0x2020 <= codePoint && codePoint <= 0x2022) ||
(0x2024 <= codePoint && codePoint <= 0x2027) ||
(0x2030 == codePoint) ||
(0x2032 <= codePoint && codePoint <= 0x2033) ||
(0x2035 == codePoint) ||
(0x203B == codePoint) ||
(0x203E == codePoint) ||
(0x2074 == codePoint) ||
(0x207F == codePoint) ||
(0x2081 <= codePoint && codePoint <= 0x2084) ||
(0x20AC == codePoint) ||
(0x2103 == codePoint) ||
(0x2105 == codePoint) ||
(0x2109 == codePoint) ||
(0x2113 == codePoint) ||
(0x2116 == codePoint) ||
(0x2121 <= codePoint && codePoint <= 0x2122) ||
(0x2126 == codePoint) ||
(0x212B == codePoint) ||
(0x2153 <= codePoint && codePoint <= 0x2154) ||
(0x215B <= codePoint && codePoint <= 0x215E) ||
(0x2160 <= codePoint && codePoint <= 0x216B) ||
(0x2170 <= codePoint && codePoint <= 0x2179) ||
(0x2189 == codePoint) ||
(0x2190 <= codePoint && codePoint <= 0x2199) ||
(0x21B8 <= codePoint && codePoint <= 0x21B9) ||
(0x21D2 == codePoint) ||
(0x21D4 == codePoint) ||
(0x21E7 == codePoint) ||
(0x2200 == codePoint) ||
(0x2202 <= codePoint && codePoint <= 0x2203) ||
(0x2207 <= codePoint && codePoint <= 0x2208) ||
(0x220B == codePoint) ||
(0x220F == codePoint) ||
(0x2211 == codePoint) ||
(0x2215 == codePoint) ||
(0x221A == codePoint) ||
(0x221D <= codePoint && codePoint <= 0x2220) ||
(0x2223 == codePoint) ||
(0x2225 == codePoint) ||
(0x2227 <= codePoint && codePoint <= 0x222C) ||
(0x222E == codePoint) ||
(0x2234 <= codePoint && codePoint <= 0x2237) ||
(0x223C <= codePoint && codePoint <= 0x223D) ||
(0x2248 == codePoint) ||
(0x224C == codePoint) ||
(0x2252 == codePoint) ||
(0x2260 <= codePoint && codePoint <= 0x2261) ||
(0x2264 <= codePoint && codePoint <= 0x2267) ||
(0x226A <= codePoint && codePoint <= 0x226B) ||
(0x226E <= codePoint && codePoint <= 0x226F) ||
(0x2282 <= codePoint && codePoint <= 0x2283) ||
(0x2286 <= codePoint && codePoint <= 0x2287) ||
(0x2295 == codePoint) ||
(0x2299 == codePoint) ||
(0x22A5 == codePoint) ||
(0x22BF == codePoint) ||
(0x2312 == codePoint) ||
(0x2460 <= codePoint && codePoint <= 0x24E9) ||
(0x24EB <= codePoint && codePoint <= 0x254B) ||
(0x2550 <= codePoint && codePoint <= 0x2573) ||
(0x2580 <= codePoint && codePoint <= 0x258F) ||
(0x2592 <= codePoint && codePoint <= 0x2595) ||
(0x25A0 <= codePoint && codePoint <= 0x25A1) ||
(0x25A3 <= codePoint && codePoint <= 0x25A9) ||
(0x25B2 <= codePoint && codePoint <= 0x25B3) ||
(0x25B6 <= codePoint && codePoint <= 0x25B7) ||
(0x25BC <= codePoint && codePoint <= 0x25BD) ||
(0x25C0 <= codePoint && codePoint <= 0x25C1) ||
(0x25C6 <= codePoint && codePoint <= 0x25C8) ||
(0x25CB == codePoint) ||
(0x25CE <= codePoint && codePoint <= 0x25D1) ||
(0x25E2 <= codePoint && codePoint <= 0x25E5) ||
(0x25EF == codePoint) ||
(0x2605 <= codePoint && codePoint <= 0x2606) ||
(0x2609 == codePoint) ||
(0x260E <= codePoint && codePoint <= 0x260F) ||
(0x2614 <= codePoint && codePoint <= 0x2615) ||
(0x261C == codePoint) ||
(0x261E == codePoint) ||
(0x2640 == codePoint) ||
(0x2642 == codePoint) ||
(0x2660 <= codePoint && codePoint <= 0x2661) ||
(0x2663 <= codePoint && codePoint <= 0x2665) ||
(0x2667 <= codePoint && codePoint <= 0x266A) ||
(0x266C <= codePoint && codePoint <= 0x266D) ||
(0x266F == codePoint) ||
(0x269E <= codePoint && codePoint <= 0x269F) ||
(0x26BE <= codePoint && codePoint <= 0x26BF) ||
(0x26C4 <= codePoint && codePoint <= 0x26CD) ||
(0x26CF <= codePoint && codePoint <= 0x26E1) ||
(0x26E3 == codePoint) ||
(0x26E8 <= codePoint && codePoint <= 0x26FF) ||
(0x273D == codePoint) ||
(0x2757 == codePoint) ||
(0x2776 <= codePoint && codePoint <= 0x277F) ||
(0x2B55 <= codePoint && codePoint <= 0x2B59) ||
(0x3248 <= codePoint && codePoint <= 0x324F) ||
(0xE000 <= codePoint && codePoint <= 0xF8FF) ||
(0xFE00 <= codePoint && codePoint <= 0xFE0F) ||
(0xFFFD == codePoint) ||
(0x1F100 <= codePoint && codePoint <= 0x1F10A) ||
(0x1F110 <= codePoint && codePoint <= 0x1F12D) ||
(0x1F130 <= codePoint && codePoint <= 0x1F169) ||
(0x1F170 <= codePoint && codePoint <= 0x1F19A) ||
(0xE0100 <= codePoint && codePoint <= 0xE01EF) ||
(0xF0000 <= codePoint && codePoint <= 0xFFFFD) ||
(0x100000 <= codePoint && codePoint <= 0x10FFFD)) {
return 'A';
}
return 'N';
};
eaw.characterLength = function(character) {
var code = this.eastAsianWidth(character);
if (code == 'F' || code == 'W' || code == 'A') {
return 2;
} else {
return 1;
}
};
eaw.length = function(string) {
var len = 0;
for (var i = 0; i < string.length; i++) {
len = len + this.characterLength(string.charAt(i));
}
return len;
};
eaw.slice = function(text, start, end) {
start = start ? start : 0;
end = end ? end : 1;
var result = '';
for (var i = 0; i < text.length; i++) {
var char = text.charAt(i);
var eawLen = eaw.length(result + char);
if (eawLen >= 1 + start && eawLen < 1 + end) {
result += char
}
}
return result;
};
},{}],59:[function(_dereq_,module,exports){
module.exports = _dereq_('./javascript/diff_match_patch_uncompressed.js').diff_match_patch;
},{"./javascript/diff_match_patch_uncompressed.js":60}],60:[function(_dereq_,module,exports){
/**
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Computes the difference between two texts to create a patch.
* Applies the patch onto another text, allowing for errors.
* @author fraser@google.com (Neil Fraser)
*/
/**
* Class containing the diff, match and patch methods.
* @constructor
*/
function diff_match_patch() {
// Defaults.
// Redefine these in your program to override the defaults.
// Number of seconds to map a diff before giving up (0 for infinity).
this.Diff_Timeout = 1.0;
// Cost of an empty edit operation in terms of edit characters.
this.Diff_EditCost = 4;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose).
this.Match_Threshold = 0.5;
// How far to search for a match (0 = exact location, 1000+ = broad match).
// A match this many characters away from the expected location will add
// 1.0 to the score (0.0 is a perfect match).
this.Match_Distance = 1000;
// When deleting a large block of text (over ~64 characters), how close do
// the contents have to be to match the expected contents. (0.0 = perfection,
// 1.0 = very loose). Note that Match_Threshold controls how closely the
// end points of a delete need to match.
this.Patch_DeleteThreshold = 0.5;
// Chunk size for context length.
this.Patch_Margin = 4;
// The number of bits in an int.
this.Match_MaxBits = 32;
}
// DIFF FUNCTIONS
/**
* The data structure representing a diff is an array of tuples:
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
*/
var DIFF_DELETE = -1;
var DIFF_INSERT = 1;
var DIFF_EQUAL = 0;
/** @typedef {{0: number, 1: string}} */
diff_match_patch.Diff;
/**
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean=} opt_checklines Optional speedup flag. If present and false,
* then don't run a line-level diff first to identify the changed areas.
* Defaults to true, which does a faster, slightly less optimal diff.
* @param {number} opt_deadline Optional time when the diff should be complete
* by. Used internally for recursive calls. Users should set DiffTimeout
* instead.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
*/
diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,
opt_deadline) {
// Set a deadline by which time the diff must be complete.
if (typeof opt_deadline == 'undefined') {
if (this.Diff_Timeout <= 0) {
opt_deadline = Number.MAX_VALUE;
} else {
opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;
}
}
var deadline = opt_deadline;
// Check for null inputs.
if (text1 == null || text2 == null) {
throw new Error('Null input. (diff_main)');
}
// Check for equality (speedup).
if (text1 == text2) {
if (text1) {
return [[DIFF_EQUAL, text1]];
}
return [];
}
if (typeof opt_checklines == 'undefined') {
opt_checklines = true;
}
var checklines = opt_checklines;
// Trim off common prefix (speedup).
var commonlength = this.diff_commonPrefix(text1, text2);
var commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = this.diff_commonSuffix(text1, text2);
var commonsuffix = text1.substring(text1.length - commonlength);
text1 = text1.substring(0, text1.length - commonlength);
text2 = text2.substring(0, text2.length - commonlength);
// Compute the diff on the middle block.
var diffs = this.diff_compute_(text1, text2, checklines, deadline);
// Restore the prefix and suffix.
if (commonprefix) {
diffs.unshift([DIFF_EQUAL, commonprefix]);
}
if (commonsuffix) {
diffs.push([DIFF_EQUAL, commonsuffix]);
}
this.diff_cleanupMerge(diffs);
return diffs;
};
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster, slightly less optimal diff.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @private
*/
diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,
deadline) {
var diffs;
if (!text1) {
// Just add some text (speedup).
return [[DIFF_INSERT, text2]];
}
if (!text2) {
// Just delete some text (speedup).
return [[DIFF_DELETE, text1]];
}
var longtext = text1.length > text2.length ? text1 : text2;
var shorttext = text1.length > text2.length ? text2 : text1;
var i = longtext.indexOf(shorttext);
if (i != -1) {
// Shorter text is inside the longer text (speedup).
diffs = [[DIFF_INSERT, longtext.substring(0, i)],
[DIFF_EQUAL, shorttext],
[DIFF_INSERT, longtext.substring(i + shorttext.length)]];
// Swap insertions for deletions if diff is reversed.
if (text1.length > text2.length) {
diffs[0][0] = diffs[2][0] = DIFF_DELETE;
}
return diffs;
}
if (shorttext.length == 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
}
// Check to see if the problem can be split in two.
var hm = this.diff_halfMatch_(text1, text2);
if (hm) {
// A half-match was found, sort out the return data.
var text1_a = hm[0];
var text1_b = hm[1];
var text2_a = hm[2];
var text2_b = hm[3];
var mid_common = hm[4];
// Send both pairs off for separate processing.
var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);
var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);
// Merge the results.
return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);
}
if (checklines && text1.length > 100 && text2.length > 100) {
return this.diff_lineMode_(text1, text2, deadline);
}
return this.diff_bisect_(text1, text2, deadline);
};
/**
* Do a quick line-level diff on both strings, then rediff the parts for
* greater accuracy.
* This speedup can produce non-minimal diffs.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @private
*/
diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {
// Scan the text on a line-by-line basis first.
var a = this.diff_linesToChars_(text1, text2);
text1 = a.chars1;
text2 = a.chars2;
var linearray = a.lineArray;
var diffs = this.diff_main(text1, text2, false, deadline);
// Convert the diff back to original text.
this.diff_charsToLines_(diffs, linearray);
// Eliminate freak matches (e.g. blank lines)
this.diff_cleanupSemantic(diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
diffs.push([DIFF_EQUAL, '']);
var pointer = 0;
var count_delete = 0;
var count_insert = 0;
var text_delete = '';
var text_insert = '';
while (pointer < diffs.length) {
switch (diffs[pointer][0]) {
case DIFF_INSERT:
count_insert++;
text_insert += diffs[pointer][1];
break;
case DIFF_DELETE:
count_delete++;
text_delete += diffs[pointer][1];
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (count_delete >= 1 && count_insert >= 1) {
// Delete the offending records and add the merged ones.
diffs.splice(pointer - count_delete - count_insert,
count_delete + count_insert);
pointer = pointer - count_delete - count_insert;
var a = this.diff_main(text_delete, text_insert, false, deadline);
for (var j = a.length - 1; j >= 0; j--) {
diffs.splice(pointer, 0, a[j]);
}
pointer = pointer + a.length;
}
count_insert = 0;
count_delete = 0;
text_delete = '';
text_insert = '';
break;
}
pointer++;
}
diffs.pop(); // Remove the dummy entry at the end.
return diffs;
};
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @private
*/
diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {
// Cache the text lengths to prevent multiple calls.
var text1_length = text1.length;
var text2_length = text2.length;
var max_d = Math.ceil((text1_length + text2_length) / 2);
var v_offset = max_d;
var v_length = 2 * max_d;
var v1 = new Array(v_length);
var v2 = new Array(v_length);
// Setting all elements to -1 is faster in Chrome & Firefox than mixing
// integers and undefined.
for (var x = 0; x < v_length; x++) {
v1[x] = -1;
v2[x] = -1;
}
v1[v_offset + 1] = 0;
v2[v_offset + 1] = 0;
var delta = text1_length - text2_length;
// If the total number of characters is odd, then the front path will collide
// with the reverse path.
var front = (delta % 2 != 0);
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
var k1start = 0;
var k1end = 0;
var k2start = 0;
var k2end = 0;
for (var d = 0; d < max_d; d++) {
// Bail out if deadline is reached.
if ((new Date()).getTime() > deadline) {
break;
}
// Walk the front path one step.
for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
var k1_offset = v_offset + k1;
var x1;
if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
x1 = v1[k1_offset + 1];
} else {
x1 = v1[k1_offset - 1] + 1;
}
var y1 = x1 - k1;
while (x1 < text1_length && y1 < text2_length &&
text1.charAt(x1) == text2.charAt(y1)) {
x1++;
y1++;
}
v1[k1_offset] = x1;
if (x1 > text1_length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > text2_length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
var k2_offset = v_offset + delta - k1;
if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
// Mirror x2 onto top-left coordinate system.
var x2 = text1_length - v2[k2_offset];
if (x1 >= x2) {
// Overlap detected.
return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
}
}
}
}
// Walk the reverse path one step.
for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
var k2_offset = v_offset + k2;
var x2;
if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
x2 = v2[k2_offset + 1];
} else {
x2 = v2[k2_offset - 1] + 1;
}
var y2 = x2 - k2;
while (x2 < text1_length && y2 < text2_length &&
text1.charAt(text1_length - x2 - 1) ==
text2.charAt(text2_length - y2 - 1)) {
x2++;
y2++;
}
v2[k2_offset] = x2;
if (x2 > text1_length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > text2_length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
var k1_offset = v_offset + delta - k2;
if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
var x1 = v1[k1_offset];
var y1 = v_offset + x1 - k1_offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2;
if (x1 >= x2) {
// Overlap detected.
return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
};
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @private
*/
diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,
deadline) {
var text1a = text1.substring(0, x);
var text2a = text2.substring(0, y);
var text1b = text1.substring(x);
var text2b = text2.substring(y);
// Compute both diffs serially.
var diffs = this.diff_main(text1a, text2a, false, deadline);
var diffsb = this.diff_main(text1b, text2b, false, deadline);
return diffs.concat(diffsb);
};
/**
* Split two texts into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
* An object containing the encoded text1, the encoded text2 and
* the array of unique strings.
* The zeroth element of the array of unique strings is intentionally blank.
* @private
*/
diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {
var lineArray = []; // e.g. lineArray[4] == 'Hello\n'
var lineHash = {}; // e.g. lineHash['Hello\n'] == 4
// '\x00' is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
lineArray[0] = '';
/**
* Split a text into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* Modifies linearray and linehash through being a closure.
* @param {string} text String to encode.
* @return {string} Encoded string.
* @private
*/
function diff_linesToCharsMunge_(text) {
var chars = '';
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
var lineStart = 0;
var lineEnd = -1;
// Keeping our own length variable is faster than looking it up.
var lineArrayLength = lineArray.length;
while (lineEnd < text.length - 1) {
lineEnd = text.indexOf('\n', lineStart);
if (lineEnd == -1) {
lineEnd = text.length - 1;
}
var line = text.substring(lineStart, lineEnd + 1);
lineStart = lineEnd + 1;
if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
(lineHash[line] !== undefined)) {
chars += String.fromCharCode(lineHash[line]);
} else {
chars += String.fromCharCode(lineArrayLength);
lineHash[line] = lineArrayLength;
lineArray[lineArrayLength++] = line;
}
}
return chars;
}
var chars1 = diff_linesToCharsMunge_(text1);
var chars2 = diff_linesToCharsMunge_(text2);
return {chars1: chars1, chars2: chars2, lineArray: lineArray};
};
/**
* Rehydrate the text in a diff from a string of line hashes to real lines of
* text.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @param {!Array.<string>} lineArray Array of unique strings.
* @private
*/
diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {
for (var x = 0; x < diffs.length; x++) {
var chars = diffs[x][1];
var text = [];
for (var y = 0; y < chars.length; y++) {
text[y] = lineArray[chars.charCodeAt(y)];
}
diffs[x][1] = text.join('');
}
};
/**
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
*/
diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {
// Quick check for common null cases.
if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var pointermin = 0;
var pointermax = Math.min(text1.length, text2.length);
var pointermid = pointermax;
var pointerstart = 0;
while (pointermin < pointermid) {
if (text1.substring(pointerstart, pointermid) ==
text2.substring(pointerstart, pointermid)) {
pointermin = pointermid;
pointerstart = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
return pointermid;
};
/**
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
*/
diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {
// Quick check for common null cases.
if (!text1 || !text2 ||
text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var pointermin = 0;
var pointermax = Math.min(text1.length, text2.length);
var pointermid = pointermax;
var pointerend = 0;
while (pointermin < pointermid) {
if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==
text2.substring(text2.length - pointermid, text2.length - pointerend)) {
pointermin = pointermid;
pointerend = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
return pointermid;
};
/**
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
*/
diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {
// Cache the text lengths to prevent multiple calls.
var text1_length = text1.length;
var text2_length = text2.length;
// Eliminate the null case.
if (text1_length == 0 || text2_length == 0) {
return 0;
}
// Truncate the longer string.
if (text1_length > text2_length) {
text1 = text1.substring(text1_length - text2_length);
} else if (text1_length < text2_length) {
text2 = text2.substring(0, text1_length);
}
var text_length = Math.min(text1_length, text2_length);
// Quick check for the worst case.
if (text1 == text2) {
return text_length;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
var best = 0;
var length = 1;
while (true) {
var pattern = text1.substring(text_length - length);
var found = text2.indexOf(pattern);
if (found == -1) {
return best;
}
length += found;
if (found == 0 || text1.substring(text_length - length) ==
text2.substring(0, length)) {
best = length;
length++;
}
}
};
/**
* Do the two texts share a substring which is at least half the length of the
* longer text?
* This speedup can produce non-minimal diffs.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or null if there was no match.
* @private
*/
diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) {
if (this.Diff_Timeout <= 0) {
// Don't risk returning a non-optimal diff if we have unlimited time.
return null;
}
var longtext = text1.length > text2.length ? text1 : text2;
var shorttext = text1.length > text2.length ? text2 : text1;
if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
return null; // Pointless.
}
var dmp = this; // 'this' becomes 'window' in a closure.
/**
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or null if there was no match.
* @private
*/
function diff_halfMatchI_(longtext, shorttext, i) {
// Start with a 1/4 length substring at position i as a seed.
var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
var j = -1;
var best_common = '';
var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),
shorttext.substring(j));
var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),
shorttext.substring(0, j));
if (best_common.length < suffixLength + prefixLength) {
best_common = shorttext.substring(j - suffixLength, j) +
shorttext.substring(j, j + prefixLength);
best_longtext_a = longtext.substring(0, i - suffixLength);
best_longtext_b = longtext.substring(i + prefixLength);
best_shorttext_a = shorttext.substring(0, j - suffixLength);
best_shorttext_b = shorttext.substring(j + prefixLength);
}
}
if (best_common.length * 2 >= longtext.length) {
return [best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common];
} else {
return null;
}
}
// First check if the second quarter is the seed for a half-match.
var hm1 = diff_halfMatchI_(longtext, shorttext,
Math.ceil(longtext.length / 4));
// Check again based on the third quarter.
var hm2 = diff_halfMatchI_(longtext, shorttext,
Math.ceil(longtext.length / 2));
var hm;
if (!hm1 && !hm2) {
return null;
} else if (!hm2) {
hm = hm1;
} else if (!hm1) {
hm = hm2;
} else {
// Both matched. Select the longest.
hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
}
// A half-match was found, sort out the return data.
var text1_a, text1_b, text2_a, text2_b;
if (text1.length > text2.length) {
text1_a = hm[0];
text1_b = hm[1];
text2_a = hm[2];
text2_b = hm[3];
} else {
text2_a = hm[0];
text2_b = hm[1];
text1_a = hm[2];
text1_b = hm[3];
}
var mid_common = hm[4];
return [text1_a, text1_b, text2_a, text2_b, mid_common];
};
/**
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {
var changes = false;
var equalities = []; // Stack of indices where equalities are found.
var equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
var lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
var pointer = 0; // Index of current position.
// Number of characters that changed prior to the equality.
var length_insertions1 = 0;
var length_deletions1 = 0;
// Number of characters that changed after the equality.
var length_insertions2 = 0;
var length_deletions2 = 0;
while (pointer < diffs.length) {
if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
equalities[equalitiesLength++] = pointer;
length_insertions1 = length_insertions2;
length_deletions1 = length_deletions2;
length_insertions2 = 0;
length_deletions2 = 0;
lastequality = diffs[pointer][1];
} else { // An insertion or deletion.
if (diffs[pointer][0] == DIFF_INSERT) {
length_insertions2 += diffs[pointer][1].length;
} else {
length_deletions2 += diffs[pointer][1].length;
}
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if (lastequality && (lastequality.length <=
Math.max(length_insertions1, length_deletions1)) &&
(lastequality.length <= Math.max(length_insertions2,
length_deletions2))) {
// Duplicate record.
diffs.splice(equalities[equalitiesLength - 1], 0,
[DIFF_DELETE, lastequality]);
// Change second copy to insert.
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
// Throw away the equality we just deleted.
equalitiesLength--;
// Throw away the previous equality (it needs to be reevaluated).
equalitiesLength--;
pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
length_insertions1 = 0; // Reset the counters.
length_deletions1 = 0;
length_insertions2 = 0;
length_deletions2 = 0;
lastequality = null;
changes = true;
}
}
pointer++;
}
// Normalize the diff.
if (changes) {
this.diff_cleanupMerge(diffs);
}
this.diff_cleanupSemanticLossless(diffs);
// Find any overlaps between deletions and insertions.
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
// -> <del>abc</del>xxx<ins>def</ins>
// e.g: <del>xxxabc</del><ins>defxxx</ins>
// -> <ins>def</ins>xxx<del>abc</del>
// Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 1;
while (pointer < diffs.length) {
if (diffs[pointer - 1][0] == DIFF_DELETE &&
diffs[pointer][0] == DIFF_INSERT) {
var deletion = diffs[pointer - 1][1];
var insertion = diffs[pointer][1];
var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);
var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);
if (overlap_length1 >= overlap_length2) {
if (overlap_length1 >= deletion.length / 2 ||
overlap_length1 >= insertion.length / 2) {
// Overlap found. Insert an equality and trim the surrounding edits.
diffs.splice(pointer, 0,
[DIFF_EQUAL, insertion.substring(0, overlap_length1)]);
diffs[pointer - 1][1] =
deletion.substring(0, deletion.length - overlap_length1);
diffs[pointer + 1][1] = insertion.substring(overlap_length1);
pointer++;
}
} else {
if (overlap_length2 >= deletion.length / 2 ||
overlap_length2 >= insertion.length / 2) {
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
diffs.splice(pointer, 0,
[DIFF_EQUAL, deletion.substring(0, overlap_length2)]);
diffs[pointer - 1][0] = DIFF_INSERT;
diffs[pointer - 1][1] =
insertion.substring(0, insertion.length - overlap_length2);
diffs[pointer + 1][0] = DIFF_DELETE;
diffs[pointer + 1][1] =
deletion.substring(overlap_length2);
pointer++;
}
}
pointer++;
}
pointer++;
}
};
/**
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {
/**
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
* Closure, but does not reference any external variables.
* @param {string} one First string.
* @param {string} two Second string.
* @return {number} The score.
* @private
*/
function diff_cleanupSemanticScore_(one, two) {
if (!one || !two) {
// Edges are the best.
return 6;
}
// Each port of this function behaves slightly differently due to
// subtle differences in each language's definition of things like
// 'whitespace'. Since this function's purpose is largely cosmetic,
// the choice has been made to use each language's native features
// rather than force total conformity.
var char1 = one.charAt(one.length - 1);
var char2 = two.charAt(0);
var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);
var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);
var whitespace1 = nonAlphaNumeric1 &&
char1.match(diff_match_patch.whitespaceRegex_);
var whitespace2 = nonAlphaNumeric2 &&
char2.match(diff_match_patch.whitespaceRegex_);
var lineBreak1 = whitespace1 &&
char1.match(diff_match_patch.linebreakRegex_);
var lineBreak2 = whitespace2 &&
char2.match(diff_match_patch.linebreakRegex_);
var blankLine1 = lineBreak1 &&
one.match(diff_match_patch.blanklineEndRegex_);
var blankLine2 = lineBreak2 &&
two.match(diff_match_patch.blanklineStartRegex_);
if (blankLine1 || blankLine2) {
// Five points for blank lines.
return 5;
} else if (lineBreak1 || lineBreak2) {
// Four points for line breaks.
return 4;
} else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
// Three points for end of sentences.
return 3;
} else if (whitespace1 || whitespace2) {
// Two points for whitespace.
return 2;
} else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
// One point for non-alphanumeric.
return 1;
}
return 0;
}
var pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while (pointer < diffs.length - 1) {
if (diffs[pointer - 1][0] == DIFF_EQUAL &&
diffs[pointer + 1][0] == DIFF_EQUAL) {
// This is a single edit surrounded by equalities.
var equality1 = diffs[pointer - 1][1];
var edit = diffs[pointer][1];
var equality2 = diffs[pointer + 1][1];
// First, shift the edit as far left as possible.
var commonOffset = this.diff_commonSuffix(equality1, edit);
if (commonOffset) {
var commonString = edit.substring(edit.length - commonOffset);
equality1 = equality1.substring(0, equality1.length - commonOffset);
edit = commonString + edit.substring(0, edit.length - commonOffset);
equality2 = commonString + equality2;
}
// Second, step character by character right, looking for the best fit.
var bestEquality1 = equality1;
var bestEdit = edit;
var bestEquality2 = equality2;
var bestScore = diff_cleanupSemanticScore_(equality1, edit) +
diff_cleanupSemanticScore_(edit, equality2);
while (edit.charAt(0) === equality2.charAt(0)) {
equality1 += edit.charAt(0);
edit = edit.substring(1) + equality2.charAt(0);
equality2 = equality2.substring(1);
var score = diff_cleanupSemanticScore_(equality1, edit) +
diff_cleanupSemanticScore_(edit, equality2);
// The >= encourages trailing rather than leading whitespace on edits.
if (score >= bestScore) {
bestScore = score;
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
}
}
if (diffs[pointer - 1][1] != bestEquality1) {
// We have an improvement, save it back to the diff.
if (bestEquality1) {
diffs[pointer - 1][1] = bestEquality1;
} else {
diffs.splice(pointer - 1, 1);
pointer--;
}
diffs[pointer][1] = bestEdit;
if (bestEquality2) {
diffs[pointer + 1][1] = bestEquality2;
} else {
diffs.splice(pointer + 1, 1);
pointer--;
}
}
}
pointer++;
}
};
// Define some regex patterns for matching boundaries.
diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;
diff_match_patch.whitespaceRegex_ = /\s/;
diff_match_patch.linebreakRegex_ = /[\r\n]/;
diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/;
diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/;
/**
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {
var changes = false;
var equalities = []; // Stack of indices where equalities are found.
var equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
var lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
var pointer = 0; // Index of current position.
// Is there an insertion operation before the last equality.
var pre_ins = false;
// Is there a deletion operation before the last equality.
var pre_del = false;
// Is there an insertion operation after the last equality.
var post_ins = false;
// Is there a deletion operation after the last equality.
var post_del = false;
while (pointer < diffs.length) {
if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
if (diffs[pointer][1].length < this.Diff_EditCost &&
(post_ins || post_del)) {
// Candidate found.
equalities[equalitiesLength++] = pointer;
pre_ins = post_ins;
pre_del = post_del;
lastequality = diffs[pointer][1];
} else {
// Not a candidate, and can never become one.
equalitiesLength = 0;
lastequality = null;
}
post_ins = post_del = false;
} else { // An insertion or deletion.
if (diffs[pointer][0] == DIFF_DELETE) {
post_del = true;
} else {
post_ins = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if (lastequality && ((pre_ins && pre_del && post_ins && post_del) ||
((lastequality.length < this.Diff_EditCost / 2) &&
(pre_ins + pre_del + post_ins + post_del) == 3))) {
// Duplicate record.
diffs.splice(equalities[equalitiesLength - 1], 0,
[DIFF_DELETE, lastequality]);
// Change second copy to insert.
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
equalitiesLength--; // Throw away the equality we just deleted;
lastequality = null;
if (pre_ins && pre_del) {
// No changes made which could affect previous entry, keep going.
post_ins = post_del = true;
equalitiesLength = 0;
} else {
equalitiesLength--; // Throw away the previous equality.
pointer = equalitiesLength > 0 ?
equalities[equalitiesLength - 1] : -1;
post_ins = post_del = false;
}
changes = true;
}
}
pointer++;
}
if (changes) {
this.diff_cleanupMerge(diffs);
}
};
/**
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
diff_match_patch.prototype.diff_cleanupMerge = function(diffs) {
diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end.
var pointer = 0;
var count_delete = 0;
var count_insert = 0;
var text_delete = '';
var text_insert = '';
var commonlength;
while (pointer < diffs.length) {
switch (diffs[pointer][0]) {
case DIFF_INSERT:
count_insert++;
text_insert += diffs[pointer][1];
pointer++;
break;
case DIFF_DELETE:
count_delete++;
text_delete += diffs[pointer][1];
pointer++;
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (count_delete + count_insert > 1) {
if (count_delete !== 0 && count_insert !== 0) {
// Factor out any common prefixies.
commonlength = this.diff_commonPrefix(text_insert, text_delete);
if (commonlength !== 0) {
if ((pointer - count_delete - count_insert) > 0 &&
diffs[pointer - count_delete - count_insert - 1][0] ==
DIFF_EQUAL) {
diffs[pointer - count_delete - count_insert - 1][1] +=
text_insert.substring(0, commonlength);
} else {
diffs.splice(0, 0, [DIFF_EQUAL,
text_insert.substring(0, commonlength)]);
pointer++;
}
text_insert = text_insert.substring(commonlength);
text_delete = text_delete.substring(commonlength);
}
// Factor out any common suffixies.
commonlength = this.diff_commonSuffix(text_insert, text_delete);
if (commonlength !== 0) {
diffs[pointer][1] = text_insert.substring(text_insert.length -
commonlength) + diffs[pointer][1];
text_insert = text_insert.substring(0, text_insert.length -
commonlength);
text_delete = text_delete.substring(0, text_delete.length -
commonlength);
}
}
// Delete the offending records and add the merged ones.
if (count_delete === 0) {
diffs.splice(pointer - count_insert,
count_delete + count_insert, [DIFF_INSERT, text_insert]);
} else if (count_insert === 0) {
diffs.splice(pointer - count_delete,
count_delete + count_insert, [DIFF_DELETE, text_delete]);
} else {
diffs.splice(pointer - count_delete - count_insert,
count_delete + count_insert, [DIFF_DELETE, text_delete],
[DIFF_INSERT, text_insert]);
}
pointer = pointer - count_delete - count_insert +
(count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1;
} else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {
// Merge this equality with the previous one.
diffs[pointer - 1][1] += diffs[pointer][1];
diffs.splice(pointer, 1);
} else {
pointer++;
}
count_insert = 0;
count_delete = 0;
text_delete = '';
text_insert = '';
break;
}
}
if (diffs[diffs.length - 1][1] === '') {
diffs.pop(); // Remove the dummy entry at the end.
}
// Second pass: look for single edits surrounded on both sides by equalities
// which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
var changes = false;
pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while (pointer < diffs.length - 1) {
if (diffs[pointer - 1][0] == DIFF_EQUAL &&
diffs[pointer + 1][0] == DIFF_EQUAL) {
// This is a single edit surrounded by equalities.
if (diffs[pointer][1].substring(diffs[pointer][1].length -
diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {
// Shift the edit over the previous equality.
diffs[pointer][1] = diffs[pointer - 1][1] +
diffs[pointer][1].substring(0, diffs[pointer][1].length -
diffs[pointer - 1][1].length);
diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
diffs.splice(pointer - 1, 1);
changes = true;
} else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
diffs[pointer + 1][1]) {
// Shift the edit over the next equality.
diffs[pointer - 1][1] += diffs[pointer + 1][1];
diffs[pointer][1] =
diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
diffs[pointer + 1][1];
diffs.splice(pointer + 1, 1);
changes = true;
}
}
pointer++;
}
// If shifts were made, the diff needs reordering and another shift sweep.
if (changes) {
this.diff_cleanupMerge(diffs);
}
};
/**
* loc is a location in text1, compute and return the equivalent location in
* text2.
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @param {number} loc Location within text1.
* @return {number} Location within text2.
*/
diff_match_patch.prototype.diff_xIndex = function(diffs, loc) {
var chars1 = 0;
var chars2 = 0;
var last_chars1 = 0;
var last_chars2 = 0;
var x;
for (x = 0; x < diffs.length; x++) {
if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion.
chars1 += diffs[x][1].length;
}
if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion.
chars2 += diffs[x][1].length;
}
if (chars1 > loc) { // Overshot the location.
break;
}
last_chars1 = chars1;
last_chars2 = chars2;
}
// Was the location was deleted?
if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {
return last_chars2;
}
// Add the remaining character length.
return last_chars2 + (loc - last_chars1);
};
/**
* Convert a diff array into a pretty HTML report.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {string} HTML representation.
*/
diff_match_patch.prototype.diff_prettyHtml = function(diffs) {
var html = [];
var pattern_amp = /&/g;
var pattern_lt = /</g;
var pattern_gt = />/g;
var pattern_para = /\n/g;
for (var x = 0; x < diffs.length; x++) {
var op = diffs[x][0]; // Operation (insert, delete, equal)
var data = diffs[x][1]; // Text of change.
var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')
.replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');
switch (op) {
case DIFF_INSERT:
html[x] = '<ins style="background:#e6ffe6;">' + text + '</ins>';
break;
case DIFF_DELETE:
html[x] = '<del style="background:#ffe6e6;">' + text + '</del>';
break;
case DIFF_EQUAL:
html[x] = '<span>' + text + '</span>';
break;
}
}
return html.join('');
};
/**
* Compute and return the source text (all equalities and deletions).
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {string} Source text.
*/
diff_match_patch.prototype.diff_text1 = function(diffs) {
var text = [];
for (var x = 0; x < diffs.length; x++) {
if (diffs[x][0] !== DIFF_INSERT) {
text[x] = diffs[x][1];
}
}
return text.join('');
};
/**
* Compute and return the destination text (all equalities and insertions).
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {string} Destination text.
*/
diff_match_patch.prototype.diff_text2 = function(diffs) {
var text = [];
for (var x = 0; x < diffs.length; x++) {
if (diffs[x][0] !== DIFF_DELETE) {
text[x] = diffs[x][1];
}
}
return text.join('');
};
/**
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {number} Number of changes.
*/
diff_match_patch.prototype.diff_levenshtein = function(diffs) {
var levenshtein = 0;
var insertions = 0;
var deletions = 0;
for (var x = 0; x < diffs.length; x++) {
var op = diffs[x][0];
var data = diffs[x][1];
switch (op) {
case DIFF_INSERT:
insertions += data.length;
break;
case DIFF_DELETE:
deletions += data.length;
break;
case DIFF_EQUAL:
// A deletion and an insertion is one substitution.
levenshtein += Math.max(insertions, deletions);
insertions = 0;
deletions = 0;
break;
}
}
levenshtein += Math.max(insertions, deletions);
return levenshtein;
};
/**
* Crush the diff into an encoded string which describes the operations
* required to transform text1 into text2.
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
* Operations are tab-separated. Inserted text is escaped using %xx notation.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {string} Delta text.
*/
diff_match_patch.prototype.diff_toDelta = function(diffs) {
var text = [];
for (var x = 0; x < diffs.length; x++) {
switch (diffs[x][0]) {
case DIFF_INSERT:
text[x] = '+' + encodeURI(diffs[x][1]);
break;
case DIFF_DELETE:
text[x] = '-' + diffs[x][1].length;
break;
case DIFF_EQUAL:
text[x] = '=' + diffs[x][1].length;
break;
}
}
return text.join('\t').replace(/%20/g, ' ');
};
/**
* Given the original text1, and an encoded string which describes the
* operations required to transform text1 into text2, compute the full diff.
* @param {string} text1 Source string for the diff.
* @param {string} delta Delta text.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @throws {!Error} If invalid input.
*/
diff_match_patch.prototype.diff_fromDelta = function(text1, delta) {
var diffs = [];
var diffsLength = 0; // Keeping our own length var is faster in JS.
var pointer = 0; // Cursor in text1
var tokens = delta.split(/\t/g);
for (var x = 0; x < tokens.length; x++) {
// Each token begins with a one character parameter which specifies the
// operation of this token (delete, insert, equality).
var param = tokens[x].substring(1);
switch (tokens[x].charAt(0)) {
case '+':
try {
diffs[diffsLength++] = [DIFF_INSERT, decodeURI(param)];
} catch (ex) {
// Malformed URI sequence.
throw new Error('Illegal escape in diff_fromDelta: ' + param);
}
break;
case '-':
// Fall through.
case '=':
var n = parseInt(param, 10);
if (isNaN(n) || n < 0) {
throw new Error('Invalid number in diff_fromDelta: ' + param);
}
var text = text1.substring(pointer, pointer += n);
if (tokens[x].charAt(0) == '=') {
diffs[diffsLength++] = [DIFF_EQUAL, text];
} else {
diffs[diffsLength++] = [DIFF_DELETE, text];
}
break;
default:
// Blank tokens are ok (from a trailing \t).
// Anything else is an error.
if (tokens[x]) {
throw new Error('Invalid diff operation in diff_fromDelta: ' +
tokens[x]);
}
}
}
if (pointer != text1.length) {
throw new Error('Delta length (' + pointer +
') does not equal source text length (' + text1.length + ').');
}
return diffs;
};
// MATCH FUNCTIONS
/**
* Locate the best instance of 'pattern' in 'text' near 'loc'.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
*/
diff_match_patch.prototype.match_main = function(text, pattern, loc) {
// Check for null inputs.
if (text == null || pattern == null || loc == null) {
throw new Error('Null input. (match_main)');
}
loc = Math.max(0, Math.min(loc, text.length));
if (text == pattern) {
// Shortcut (potentially not guaranteed by the algorithm)
return 0;
} else if (!text.length) {
// Nothing to match.
return -1;
} else if (text.substring(loc, loc + pattern.length) == pattern) {
// Perfect match at the perfect spot! (Includes case of null pattern)
return loc;
} else {
// Do a fuzzy compare.
return this.match_bitap_(text, pattern, loc);
}
};
/**
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
* Bitap algorithm.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
* @private
*/
diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {
if (pattern.length > this.Match_MaxBits) {
throw new Error('Pattern too long for this browser.');
}
// Initialise the alphabet.
var s = this.match_alphabet_(pattern);
var dmp = this; // 'this' becomes 'window' in a closure.
/**
* Compute and return the score for a match with e errors and x location.
* Accesses loc and pattern through being a closure.
* @param {number} e Number of errors in match.
* @param {number} x Location of match.
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
* @private
*/
function match_bitapScore_(e, x) {
var accuracy = e / pattern.length;
var proximity = Math.abs(loc - x);
if (!dmp.Match_Distance) {
// Dodge divide by zero error.
return proximity ? 1.0 : accuracy;
}
return accuracy + (proximity / dmp.Match_Distance);
}
// Highest score beyond which we give up.
var score_threshold = this.Match_Threshold;
// Is there a nearby exact match? (speedup)
var best_loc = text.indexOf(pattern, loc);
if (best_loc != -1) {
score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);
// What about in the other direction? (speedup)
best_loc = text.lastIndexOf(pattern, loc + pattern.length);
if (best_loc != -1) {
score_threshold =
Math.min(match_bitapScore_(0, best_loc), score_threshold);
}
}
// Initialise the bit arrays.
var matchmask = 1 << (pattern.length - 1);
best_loc = -1;
var bin_min, bin_mid;
var bin_max = pattern.length + text.length;
var last_rd;
for (var d = 0; d < pattern.length; d++) {
// Scan for the best match; each iteration allows for one more error.
// Run a binary search to determine how far from 'loc' we can stray at this
// error level.
bin_min = 0;
bin_mid = bin_max;
while (bin_min < bin_mid) {
if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {
bin_min = bin_mid;
} else {
bin_max = bin_mid;
}
bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);
}
// Use the result from this iteration as the maximum for the next.
bin_max = bin_mid;
var start = Math.max(1, loc - bin_mid + 1);
var finish = Math.min(loc + bin_mid, text.length) + pattern.length;
var rd = Array(finish + 2);
rd[finish + 1] = (1 << d) - 1;
for (var j = finish; j >= start; j--) {
// The alphabet (s) is a sparse hash, so the following line generates
// warnings.
var charMatch = s[text.charAt(j - 1)];
if (d === 0) { // First pass: exact match.
rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;
} else { // Subsequent passes: fuzzy match.
rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |
(((last_rd[j + 1] | last_rd[j]) << 1) | 1) |
last_rd[j + 1];
}
if (rd[j] & matchmask) {
var score = match_bitapScore_(d, j - 1);
// This match will almost certainly be better than any existing match.
// But check anyway.
if (score <= score_threshold) {
// Told you so.
score_threshold = score;
best_loc = j - 1;
if (best_loc > loc) {
// When passing loc, don't exceed our current distance from loc.
start = Math.max(1, 2 * loc - best_loc);
} else {
// Already passed loc, downhill from here on in.
break;
}
}
}
}
// No hope for a (better) match at greater error levels.
if (match_bitapScore_(d + 1, loc) > score_threshold) {
break;
}
last_rd = rd;
}
return best_loc;
};
/**
* Initialise the alphabet for the Bitap algorithm.
* @param {string} pattern The text to encode.
* @return {!Object} Hash of character locations.
* @private
*/
diff_match_patch.prototype.match_alphabet_ = function(pattern) {
var s = {};
for (var i = 0; i < pattern.length; i++) {
s[pattern.charAt(i)] = 0;
}
for (var i = 0; i < pattern.length; i++) {
s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);
}
return s;
};
// PATCH FUNCTIONS
/**
* Increase the context until it is unique,
* but don't let the pattern expand beyond Match_MaxBits.
* @param {!diff_match_patch.patch_obj} patch The patch to grow.
* @param {string} text Source text.
* @private
*/
diff_match_patch.prototype.patch_addContext_ = function(patch, text) {
if (text.length == 0) {
return;
}
var pattern = text.substring(patch.start2, patch.start2 + patch.length1);
var padding = 0;
// Look for the first and last matches of pattern in text. If two different
// matches are found, increase the pattern length.
while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&
pattern.length < this.Match_MaxBits - this.Patch_Margin -
this.Patch_Margin) {
padding += this.Patch_Margin;
pattern = text.substring(patch.start2 - padding,
patch.start2 + patch.length1 + padding);
}
// Add one chunk for good luck.
padding += this.Patch_Margin;
// Add the prefix.
var prefix = text.substring(patch.start2 - padding, patch.start2);
if (prefix) {
patch.diffs.unshift([DIFF_EQUAL, prefix]);
}
// Add the suffix.
var suffix = text.substring(patch.start2 + patch.length1,
patch.start2 + patch.length1 + padding);
if (suffix) {
patch.diffs.push([DIFF_EQUAL, suffix]);
}
// Roll back the start points.
patch.start1 -= prefix.length;
patch.start2 -= prefix.length;
// Extend the lengths.
patch.length1 += prefix.length + suffix.length;
patch.length2 += prefix.length + suffix.length;
};
/**
* Compute a list of patches to turn text1 into text2.
* Use diffs if provided, otherwise compute it ourselves.
* There are four ways to call this function, depending on what data is
* available to the caller:
* Method 1:
* a = text1, b = text2
* Method 2:
* a = diffs
* Method 3 (optimal):
* a = text1, b = diffs
* Method 4 (deprecated, use method 3):
* a = text1, b = text2, c = diffs
*
* @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or
* Array of diff tuples for text1 to text2 (method 2).
* @param {string|!Array.<!diff_match_patch.Diff>} opt_b text2 (methods 1,4) or
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
* @param {string|!Array.<!diff_match_patch.Diff>} opt_c Array of diff tuples
* for text1 to text2 (method 4) or undefined (methods 1,2,3).
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
*/
diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {
var text1, diffs;
if (typeof a == 'string' && typeof opt_b == 'string' &&
typeof opt_c == 'undefined') {
// Method 1: text1, text2
// Compute diffs from text1 and text2.
text1 = /** @type {string} */(a);
diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);
if (diffs.length > 2) {
this.diff_cleanupSemantic(diffs);
this.diff_cleanupEfficiency(diffs);
}
} else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&
typeof opt_c == 'undefined') {
// Method 2: diffs
// Compute text1 from diffs.
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a);
text1 = this.diff_text1(diffs);
} else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&
typeof opt_c == 'undefined') {
// Method 3: text1, diffs
text1 = /** @type {string} */(a);
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b);
} else if (typeof a == 'string' && typeof opt_b == 'string' &&
opt_c && typeof opt_c == 'object') {
// Method 4: text1, text2, diffs
// text2 is not used.
text1 = /** @type {string} */(a);
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c);
} else {
throw new Error('Unknown call format to patch_make.');
}
if (diffs.length === 0) {
return []; // Get rid of the null case.
}
var patches = [];
var patch = new diff_match_patch.patch_obj();
var patchDiffLength = 0; // Keeping our own length var is faster in JS.
var char_count1 = 0; // Number of characters into the text1 string.
var char_count2 = 0; // Number of characters into the text2 string.
// Start with text1 (prepatch_text) and apply the diffs until we arrive at
// text2 (postpatch_text). We recreate the patches one by one to determine
// context info.
var prepatch_text = text1;
var postpatch_text = text1;
for (var x = 0; x < diffs.length; x++) {
var diff_type = diffs[x][0];
var diff_text = diffs[x][1];
if (!patchDiffLength && diff_type !== DIFF_EQUAL) {
// A new patch starts here.
patch.start1 = char_count1;
patch.start2 = char_count2;
}
switch (diff_type) {
case DIFF_INSERT:
patch.diffs[patchDiffLength++] = diffs[x];
patch.length2 += diff_text.length;
postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +
postpatch_text.substring(char_count2);
break;
case DIFF_DELETE:
patch.length1 += diff_text.length;
patch.diffs[patchDiffLength++] = diffs[x];
postpatch_text = postpatch_text.substring(0, char_count2) +
postpatch_text.substring(char_count2 +
diff_text.length);
break;
case DIFF_EQUAL:
if (diff_text.length <= 2 * this.Patch_Margin &&
patchDiffLength && diffs.length != x + 1) {
// Small equality inside a patch.
patch.diffs[patchDiffLength++] = diffs[x];
patch.length1 += diff_text.length;
patch.length2 += diff_text.length;
} else if (diff_text.length >= 2 * this.Patch_Margin) {
// Time for a new patch.
if (patchDiffLength) {
this.patch_addContext_(patch, prepatch_text);
patches.push(patch);
patch = new diff_match_patch.patch_obj();
patchDiffLength = 0;
// Unlike Unidiff, our patch lists have a rolling context.
// http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
// Update prepatch text & pos to reflect the application of the
// just completed patch.
prepatch_text = postpatch_text;
char_count1 = char_count2;
}
}
break;
}
// Update the current character count.
if (diff_type !== DIFF_INSERT) {
char_count1 += diff_text.length;
}
if (diff_type !== DIFF_DELETE) {
char_count2 += diff_text.length;
}
}
// Pick up the leftover patch if not empty.
if (patchDiffLength) {
this.patch_addContext_(patch, prepatch_text);
patches.push(patch);
}
return patches;
};
/**
* Given an array of patches, return another array that is identical.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
*/
diff_match_patch.prototype.patch_deepCopy = function(patches) {
// Making deep copies is hard in JavaScript.
var patchesCopy = [];
for (var x = 0; x < patches.length; x++) {
var patch = patches[x];
var patchCopy = new diff_match_patch.patch_obj();
patchCopy.diffs = [];
for (var y = 0; y < patch.diffs.length; y++) {
patchCopy.diffs[y] = patch.diffs[y].slice();
}
patchCopy.start1 = patch.start1;
patchCopy.start2 = patch.start2;
patchCopy.length1 = patch.length1;
patchCopy.length2 = patch.length2;
patchesCopy[x] = patchCopy;
}
return patchesCopy;
};
/**
* Merge a set of patches onto the text. Return a patched text, as well
* as a list of true/false values indicating which patches were applied.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
* @param {string} text Old text.
* @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the
* new text and an array of boolean values.
*/
diff_match_patch.prototype.patch_apply = function(patches, text) {
if (patches.length == 0) {
return [text, []];
}
// Deep copy the patches so that no changes are made to originals.
patches = this.patch_deepCopy(patches);
var nullPadding = this.patch_addPadding(patches);
text = nullPadding + text + nullPadding;
this.patch_splitMax(patches);
// delta keeps track of the offset between the expected and actual location
// of the previous patch. If there are patches expected at positions 10 and
// 20, but the first patch was found at 12, delta is 2 and the second patch
// has an effective expected position of 22.
var delta = 0;
var results = [];
for (var x = 0; x < patches.length; x++) {
var expected_loc = patches[x].start2 + delta;
var text1 = this.diff_text1(patches[x].diffs);
var start_loc;
var end_loc = -1;
if (text1.length > this.Match_MaxBits) {
// patch_splitMax will only provide an oversized pattern in the case of
// a monster delete.
start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),
expected_loc);
if (start_loc != -1) {
end_loc = this.match_main(text,
text1.substring(text1.length - this.Match_MaxBits),
expected_loc + text1.length - this.Match_MaxBits);
if (end_loc == -1 || start_loc >= end_loc) {
// Can't find valid trailing context. Drop this patch.
start_loc = -1;
}
}
} else {
start_loc = this.match_main(text, text1, expected_loc);
}
if (start_loc == -1) {
// No match found. :(
results[x] = false;
// Subtract the delta for this failed patch from subsequent patches.
delta -= patches[x].length2 - patches[x].length1;
} else {
// Found a match. :)
results[x] = true;
delta = start_loc - expected_loc;
var text2;
if (end_loc == -1) {
text2 = text.substring(start_loc, start_loc + text1.length);
} else {
text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);
}
if (text1 == text2) {
// Perfect match, just shove the replacement text in.
text = text.substring(0, start_loc) +
this.diff_text2(patches[x].diffs) +
text.substring(start_loc + text1.length);
} else {
// Imperfect match. Run a diff to get a framework of equivalent
// indices.
var diffs = this.diff_main(text1, text2, false);
if (text1.length > this.Match_MaxBits &&
this.diff_levenshtein(diffs) / text1.length >
this.Patch_DeleteThreshold) {
// The end points match, but the content is unacceptably bad.
results[x] = false;
} else {
this.diff_cleanupSemanticLossless(diffs);
var index1 = 0;
var index2;
for (var y = 0; y < patches[x].diffs.length; y++) {
var mod = patches[x].diffs[y];
if (mod[0] !== DIFF_EQUAL) {
index2 = this.diff_xIndex(diffs, index1);
}
if (mod[0] === DIFF_INSERT) { // Insertion
text = text.substring(0, start_loc + index2) + mod[1] +
text.substring(start_loc + index2);
} else if (mod[0] === DIFF_DELETE) { // Deletion
text = text.substring(0, start_loc + index2) +
text.substring(start_loc + this.diff_xIndex(diffs,
index1 + mod[1].length));
}
if (mod[0] !== DIFF_DELETE) {
index1 += mod[1].length;
}
}
}
}
}
}
// Strip the padding off.
text = text.substring(nullPadding.length, text.length - nullPadding.length);
return [text, results];
};
/**
* Add some padding on text start and end so that edges can match something.
* Intended to be called only from within patch_apply.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
* @return {string} The padding string added to each side.
*/
diff_match_patch.prototype.patch_addPadding = function(patches) {
var paddingLength = this.Patch_Margin;
var nullPadding = '';
for (var x = 1; x <= paddingLength; x++) {
nullPadding += String.fromCharCode(x);
}
// Bump all the patches forward.
for (var x = 0; x < patches.length; x++) {
patches[x].start1 += paddingLength;
patches[x].start2 += paddingLength;
}
// Add some padding on start of first diff.
var patch = patches[0];
var diffs = patch.diffs;
if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {
// Add nullPadding equality.
diffs.unshift([DIFF_EQUAL, nullPadding]);
patch.start1 -= paddingLength; // Should be 0.
patch.start2 -= paddingLength; // Should be 0.
patch.length1 += paddingLength;
patch.length2 += paddingLength;
} else if (paddingLength > diffs[0][1].length) {
// Grow first equality.
var extraLength = paddingLength - diffs[0][1].length;
diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];
patch.start1 -= extraLength;
patch.start2 -= extraLength;
patch.length1 += extraLength;
patch.length2 += extraLength;
}
// Add some padding on end of last diff.
patch = patches[patches.length - 1];
diffs = patch.diffs;
if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {
// Add nullPadding equality.
diffs.push([DIFF_EQUAL, nullPadding]);
patch.length1 += paddingLength;
patch.length2 += paddingLength;
} else if (paddingLength > diffs[diffs.length - 1][1].length) {
// Grow last equality.
var extraLength = paddingLength - diffs[diffs.length - 1][1].length;
diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);
patch.length1 += extraLength;
patch.length2 += extraLength;
}
return nullPadding;
};
/**
* Look through the patches and break up any which are longer than the maximum
* limit of the match algorithm.
* Intended to be called only from within patch_apply.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
*/
diff_match_patch.prototype.patch_splitMax = function(patches) {
var patch_size = this.Match_MaxBits;
for (var x = 0; x < patches.length; x++) {
if (patches[x].length1 <= patch_size) {
continue;
}
var bigpatch = patches[x];
// Remove the big old patch.
patches.splice(x--, 1);
var start1 = bigpatch.start1;
var start2 = bigpatch.start2;
var precontext = '';
while (bigpatch.diffs.length !== 0) {
// Create one of several smaller patches.
var patch = new diff_match_patch.patch_obj();
var empty = true;
patch.start1 = start1 - precontext.length;
patch.start2 = start2 - precontext.length;
if (precontext !== '') {
patch.length1 = patch.length2 = precontext.length;
patch.diffs.push([DIFF_EQUAL, precontext]);
}
while (bigpatch.diffs.length !== 0 &&
patch.length1 < patch_size - this.Patch_Margin) {
var diff_type = bigpatch.diffs[0][0];
var diff_text = bigpatch.diffs[0][1];
if (diff_type === DIFF_INSERT) {
// Insertions are harmless.
patch.length2 += diff_text.length;
start2 += diff_text.length;
patch.diffs.push(bigpatch.diffs.shift());
empty = false;
} else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&
patch.diffs[0][0] == DIFF_EQUAL &&
diff_text.length > 2 * patch_size) {
// This is a large deletion. Let it pass in one chunk.
patch.length1 += diff_text.length;
start1 += diff_text.length;
empty = false;
patch.diffs.push([diff_type, diff_text]);
bigpatch.diffs.shift();
} else {
// Deletion or equality. Only take as much as we can stomach.
diff_text = diff_text.substring(0,
patch_size - patch.length1 - this.Patch_Margin);
patch.length1 += diff_text.length;
start1 += diff_text.length;
if (diff_type === DIFF_EQUAL) {
patch.length2 += diff_text.length;
start2 += diff_text.length;
} else {
empty = false;
}
patch.diffs.push([diff_type, diff_text]);
if (diff_text == bigpatch.diffs[0][1]) {
bigpatch.diffs.shift();
} else {
bigpatch.diffs[0][1] =
bigpatch.diffs[0][1].substring(diff_text.length);
}
}
}
// Compute the head context for the next patch.
precontext = this.diff_text2(patch.diffs);
precontext =
precontext.substring(precontext.length - this.Patch_Margin);
// Append the end context for this patch.
var postcontext = this.diff_text1(bigpatch.diffs)
.substring(0, this.Patch_Margin);
if (postcontext !== '') {
patch.length1 += postcontext.length;
patch.length2 += postcontext.length;
if (patch.diffs.length !== 0 &&
patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {
patch.diffs[patch.diffs.length - 1][1] += postcontext;
} else {
patch.diffs.push([DIFF_EQUAL, postcontext]);
}
}
if (!empty) {
patches.splice(++x, 0, patch);
}
}
}
};
/**
* Take a list of patches and return a textual representation.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
* @return {string} Text representation of patches.
*/
diff_match_patch.prototype.patch_toText = function(patches) {
var text = [];
for (var x = 0; x < patches.length; x++) {
text[x] = patches[x];
}
return text.join('');
};
/**
* Parse a textual representation of patches and return a list of Patch objects.
* @param {string} textline Text representation of patches.
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
* @throws {!Error} If invalid input.
*/
diff_match_patch.prototype.patch_fromText = function(textline) {
var patches = [];
if (!textline) {
return patches;
}
var text = textline.split('\n');
var textPointer = 0;
var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
while (textPointer < text.length) {
var m = text[textPointer].match(patchHeader);
if (!m) {
throw new Error('Invalid patch string: ' + text[textPointer]);
}
var patch = new diff_match_patch.patch_obj();
patches.push(patch);
patch.start1 = parseInt(m[1], 10);
if (m[2] === '') {
patch.start1--;
patch.length1 = 1;
} else if (m[2] == '0') {
patch.length1 = 0;
} else {
patch.start1--;
patch.length1 = parseInt(m[2], 10);
}
patch.start2 = parseInt(m[3], 10);
if (m[4] === '') {
patch.start2--;
patch.length2 = 1;
} else if (m[4] == '0') {
patch.length2 = 0;
} else {
patch.start2--;
patch.length2 = parseInt(m[4], 10);
}
textPointer++;
while (textPointer < text.length) {
var sign = text[textPointer].charAt(0);
try {
var line = decodeURI(text[textPointer].substring(1));
} catch (ex) {
// Malformed URI sequence.
throw new Error('Illegal escape in patch_fromText: ' + line);
}
if (sign == '-') {
// Deletion.
patch.diffs.push([DIFF_DELETE, line]);
} else if (sign == '+') {
// Insertion.
patch.diffs.push([DIFF_INSERT, line]);
} else if (sign == ' ') {
// Minor equality.
patch.diffs.push([DIFF_EQUAL, line]);
} else if (sign == '@') {
// Start of next patch.
break;
} else if (sign === '') {
// Blank line? Whatever.
} else {
// WTF?
throw new Error('Invalid patch mode "' + sign + '" in: ' + line);
}
textPointer++;
}
}
return patches;
};
/**
* Class representing one patch operation.
* @constructor
*/
diff_match_patch.patch_obj = function() {
/** @type {!Array.<!diff_match_patch.Diff>} */
this.diffs = [];
/** @type {?number} */
this.start1 = null;
/** @type {?number} */
this.start2 = null;
/** @type {number} */
this.length1 = 0;
/** @type {number} */
this.length2 = 0;
};
/**
* Emmulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* Indicies are printed as 1-based, not 0-based.
* @return {string} The GNU diff string.
*/
diff_match_patch.patch_obj.prototype.toString = function() {
var coords1, coords2;
if (this.length1 === 0) {
coords1 = this.start1 + ',0';
} else if (this.length1 == 1) {
coords1 = this.start1 + 1;
} else {
coords1 = (this.start1 + 1) + ',' + this.length1;
}
if (this.length2 === 0) {
coords2 = this.start2 + ',0';
} else if (this.length2 == 1) {
coords2 = this.start2 + 1;
} else {
coords2 = (this.start2 + 1) + ',' + this.length2;
}
var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n'];
var op;
// Escape the body of the patch with %xx notation.
for (var x = 0; x < this.diffs.length; x++) {
switch (this.diffs[x][0]) {
case DIFF_INSERT:
op = '+';
break;
case DIFF_DELETE:
op = '-';
break;
case DIFF_EQUAL:
op = ' ';
break;
}
text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n';
}
return text.join('').replace(/%20/g, ' ');
};
// Export these global variables so that they survive Google's JS compiler.
// In a browser, 'this' will be 'window'.
// Users of node.js should 'require' the uncompressed version since Google's
// JS compiler may break the following exports for non-browser environments.
this['diff_match_patch'] = diff_match_patch;
this['DIFF_DELETE'] = DIFF_DELETE;
this['DIFF_INSERT'] = DIFF_INSERT;
this['DIFF_EQUAL'] = DIFF_EQUAL;
},{}],61:[function(_dereq_,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
}
}
},{}],62:[function(_dereq_,module,exports){
'use strict';
var BaseRenderer = _dereq_('power-assert-renderer-base');
var inherits = _dereq_('util').inherits;
function AssertionRenderer () {
BaseRenderer.call(this);
}
inherits(AssertionRenderer, BaseRenderer);
AssertionRenderer.prototype.onStart = function (context) {
this.assertionLine = context.source.content;
};
AssertionRenderer.prototype.onEnd = function () {
this.write('');
this.write(this.assertionLine);
};
module.exports = AssertionRenderer;
},{"power-assert-renderer-base":63,"util":78}],63:[function(_dereq_,module,exports){
'use strict';
function BaseRenderer () {
}
BaseRenderer.prototype.init = function (traversal) {
var _this = this;
traversal.on('start', function (context) {
_this.onStart(context);
});
traversal.on('data', function (esNode) {
_this.onData(esNode);
});
traversal.on('end', function () {
_this.onEnd();
});
};
BaseRenderer.prototype.setWritable = function (writable) {
this.writable = writable;
};
// API
BaseRenderer.prototype.onStart = function (context) {
};
// API
BaseRenderer.prototype.onData = function (esNode) {
};
// API
BaseRenderer.prototype.onEnd = function () {
};
// API
BaseRenderer.prototype.write = function (str) {
this.writable.write(str);
};
module.exports = BaseRenderer;
},{}],64:[function(_dereq_,module,exports){
'use strict';
var BaseRenderer = _dereq_('power-assert-renderer-base');
var inherits = _dereq_('util').inherits;
var typeName = _dereq_('type-name');
var keys = _dereq_('core-js/library/fn/object/keys');
var forEach = _dereq_('core-js/library/fn/array/for-each');
var udiff = _dereq_('./lib/udiff');
var stringifier = _dereq_('stringifier');
var assign = _dereq_('core-js/library/fn/object/assign');
var defaultOptions = _dereq_('./lib/default-options');
var literalPattern = /^(?:String|Numeric|Null|Boolean|RegExp)?Literal$/;
function isLiteral (node) {
return literalPattern.test(node.type);
}
/**
* options.stringify [function]
* options.maxDepth [number]
* options.lineSeparator [string]
* options.anonymous [string]
* options.circular [string]
*
* options.diff [function]
* options.lineDiffThreshold [number]
*/
function ComparisonRenderer (config) {
BaseRenderer.call(this);
this.config = assign({}, defaultOptions(), config);
if (typeof this.config.stringify === 'function') {
this.stringify = this.config.stringify;
} else {
this.stringify = stringifier(this.config);
}
if (typeof this.config.diff === 'function') {
this.diff = this.config.diff;
} else {
this.diff = udiff(this.config);
}
this.espathToPair = {};
}
inherits(ComparisonRenderer, BaseRenderer);
ComparisonRenderer.prototype.onData = function (esNode) {
var pair;
if (!esNode.isCaptured) {
if (isTargetBinaryExpression(esNode.parent) && isLiteral(esNode.node)) {
this.espathToPair[esNode.parent.espath][esNode.key] = {code: esNode.code, value: esNode.value};
}
return;
}
if (isTargetBinaryExpression(esNode.parent)) {
this.espathToPair[esNode.parent.espath][esNode.key] = {code: esNode.code, value: esNode.value};
}
if (isTargetBinaryExpression(esNode)) {
pair = {
operator: esNode.node.operator,
value: esNode.value
};
this.espathToPair[esNode.espath] = pair;
}
};
ComparisonRenderer.prototype.onEnd = function () {
var _this = this;
var pairs = [];
forEach(keys(this.espathToPair), function (espath) {
var pair = _this.espathToPair[espath];
if (pair.left && pair.right) {
pairs.push(pair);
}
});
forEach(pairs, function (pair) {
_this.compare(pair);
});
};
ComparisonRenderer.prototype.compare = function (pair) {
if (isStringDiffTarget(pair)) {
this.showStringDiff(pair);
} else {
this.showExpectedAndActual(pair);
}
};
ComparisonRenderer.prototype.showExpectedAndActual = function (pair) {
this.write('');
this.write('[' + typeName(pair.right.value) + '] ' + pair.right.code);
this.write('=> ' + this.stringify(pair.right.value));
this.write('[' + typeName(pair.left.value) + '] ' + pair.left.code);
this.write('=> ' + this.stringify(pair.left.value));
};
ComparisonRenderer.prototype.showStringDiff = function (pair) {
this.write('');
this.write('--- [string] ' + pair.right.code);
this.write('+++ [string] ' + pair.left.code);
this.write(this.diff(pair.right.value, pair.left.value, this.config));
};
function isTargetBinaryExpression (esNode) {
return esNode &&
esNode.node.type === 'BinaryExpression' &&
(esNode.node.operator === '===' || esNode.node.operator === '==') &&
esNode.isCaptured &&
!(esNode.value);
}
function isStringDiffTarget(pair) {
return typeof pair.left.value === 'string' && typeof pair.right.value === 'string';
}
ComparisonRenderer.udiff = udiff;
module.exports = ComparisonRenderer;
},{"./lib/default-options":65,"./lib/udiff":66,"core-js/library/fn/array/for-each":3,"core-js/library/fn/object/assign":7,"core-js/library/fn/object/keys":8,"power-assert-renderer-base":63,"stringifier":73,"type-name":76,"util":78}],65:[function(_dereq_,module,exports){
'use strict';
module.exports = function defaultOptions () {
return {
lineDiffThreshold: 5,
maxDepth: 2,
indent: null,
outputOffset: 2,
anonymous: 'Object',
circular: '#@Circular#',
lineSeparator: '\n'
};
};
},{}],66:[function(_dereq_,module,exports){
'use strict';
var DiffMatchPatch = _dereq_('googlediff');
var dmp = new DiffMatchPatch();
function udiff (config) {
return function diff (text1, text2) {
var patch;
if (config && shouldUseLineLevelDiff(text1, config)) {
patch = udiffLines(text1, text2);
} else {
patch = udiffChars(text1, text2);
}
return decodeURIComponent(patch);
};
}
function shouldUseLineLevelDiff (text, config) {
return config.lineDiffThreshold < text.split(/\r\n|\r|\n/).length;
}
function udiffLines(text1, text2) {
/*jshint camelcase: false */
var a = dmp.diff_linesToChars_(text1, text2);
var diffs = dmp.diff_main(a.chars1, a.chars2, false);
dmp.diff_charsToLines_(diffs, a.lineArray);
dmp.diff_cleanupSemantic(diffs);
return dmp.patch_toText(dmp.patch_make(text1, diffs));
}
function udiffChars (text1, text2) {
/*jshint camelcase: false */
var diffs = dmp.diff_main(text1, text2, false);
dmp.diff_cleanupSemantic(diffs);
return dmp.patch_toText(dmp.patch_make(text1, diffs));
}
module.exports = udiff;
},{"googlediff":59}],67:[function(_dereq_,module,exports){
'use strict';
var BaseRenderer = _dereq_('power-assert-renderer-base');
var inherits = _dereq_('util').inherits;
var forEach = _dereq_('core-js/library/fn/array/for-each');
var stringifier = _dereq_('stringifier');
var stringWidth = _dereq_('./lib/string-width');
var assign = _dereq_('core-js/library/fn/object/assign');
var defaultOptions = _dereq_('./lib/default-options');
/**
* options.stringify [function]
* options.maxDepth [number]
* options.lineSeparator [string]
* options.anonymous [string]
* options.circular [string]
*
* options.widthOf [function]
* options.ambiguousEastAsianCharWidth [number]
*/
function DiagramRenderer (config) {
BaseRenderer.call(this);
this.config = assign({}, defaultOptions(), config);
this.events = [];
if (typeof this.config.stringify === 'function') {
this.stringify = this.config.stringify;
} else {
this.stringify = stringifier(this.config);
}
if (typeof this.config.widthOf === 'function') {
this.widthOf = this.config.widthOf;
} else {
this.widthOf = stringWidth(this.config);
}
this.initialVertivalBarLength = 1;
}
inherits(DiagramRenderer, BaseRenderer);
DiagramRenderer.prototype.onStart = function (context) {
this.assertionLine = context.source.content;
this.initializeRows();
};
DiagramRenderer.prototype.onData = function (esNode) {
if (!esNode.isCaptured) {
return;
}
this.events.push({value: esNode.value, leftIndex: esNode.range[0]});
};
DiagramRenderer.prototype.onEnd = function () {
this.events.sort(rightToLeft);
this.constructRows(this.events);
var _this = this;
forEach(this.rows, function (columns) {
_this.write(columns.join(''));
});
};
DiagramRenderer.prototype.initializeRows = function () {
this.rows = [];
for (var i = 0; i <= this.initialVertivalBarLength; i += 1) {
this.addOneMoreRow();
}
};
DiagramRenderer.prototype.newRowFor = function (assertionLine) {
return createRow(this.widthOf(assertionLine), ' ');
};
DiagramRenderer.prototype.addOneMoreRow = function () {
this.rows.push(this.newRowFor(this.assertionLine));
};
DiagramRenderer.prototype.lastRow = function () {
return this.rows[this.rows.length - 1];
};
DiagramRenderer.prototype.renderVerticalBarAt = function (columnIndex) {
var i, lastRowIndex = this.rows.length - 1;
for (i = 0; i < lastRowIndex; i += 1) {
this.rows[i].splice(columnIndex, 1, '|');
}
};
DiagramRenderer.prototype.renderValueAt = function (columnIndex, dumpedValue) {
var i, width = this.widthOf(dumpedValue);
for (i = 0; i < width; i += 1) {
this.lastRow().splice(columnIndex + i, 1, dumpedValue.charAt(i));
}
};
DiagramRenderer.prototype.isOverlapped = function (prevCapturing, nextCaputuring, dumpedValue) {
return (typeof prevCapturing !== 'undefined') && this.startColumnFor(prevCapturing) <= (this.startColumnFor(nextCaputuring) + this.widthOf(dumpedValue));
};
DiagramRenderer.prototype.constructRows = function (capturedEvents) {
var that = this;
var prevCaptured;
forEach(capturedEvents, function (captured) {
var dumpedValue = that.stringify(captured.value);
if (that.isOverlapped(prevCaptured, captured, dumpedValue)) {
that.addOneMoreRow();
}
that.renderVerticalBarAt(that.startColumnFor(captured));
that.renderValueAt(that.startColumnFor(captured), dumpedValue);
prevCaptured = captured;
});
};
DiagramRenderer.prototype.startColumnFor = function (captured) {
return this.widthOf(this.assertionLine.slice(0, captured.leftIndex));
};
function createRow (numCols, initial) {
var row = [], i;
for(i = 0; i < numCols; i += 1) {
row[i] = initial;
}
return row;
}
function rightToLeft (a, b) {
return b.leftIndex - a.leftIndex;
}
DiagramRenderer.stringWidth = stringWidth;
module.exports = DiagramRenderer;
},{"./lib/default-options":68,"./lib/string-width":69,"core-js/library/fn/array/for-each":3,"core-js/library/fn/object/assign":7,"power-assert-renderer-base":63,"stringifier":73,"util":78}],68:[function(_dereq_,module,exports){
'use strict';
module.exports = function defaultOptions () {
return {
ambiguousEastAsianCharWidth: 2,
maxDepth: 2,
indent: null,
outputOffset: 2,
anonymous: 'Object',
circular: '#@Circular#',
lineSeparator: '\n'
};
};
},{}],69:[function(_dereq_,module,exports){
'use strict';
var eaw = _dereq_('eastasianwidth');
function stringWidth (config) {
var ambiguousCharWidth = (config && config.ambiguousEastAsianCharWidth) || 1;
return function widthOf (str) {
var i, code, width = 0;
for(i = 0; i < str.length; i+=1) {
code = eaw.eastAsianWidth(str.charAt(i));
switch(code) {
case 'F':
case 'W':
width += 2;
break;
case 'H':
case 'Na':
case 'N':
width += 1;
break;
case 'A':
width += ambiguousCharWidth;
break;
}
}
return width;
};
}
module.exports = stringWidth;
},{"eastasianwidth":58}],70:[function(_dereq_,module,exports){
'use strict';
var BaseRenderer = _dereq_('power-assert-renderer-base');
var inherits = _dereq_('util').inherits;
function FileRenderer () {
BaseRenderer.call(this);
}
inherits(FileRenderer, BaseRenderer);
FileRenderer.prototype.onStart = function (context) {
this.filepath = context.source.filepath;
this.lineNumber = context.source.line;
};
FileRenderer.prototype.onEnd = function () {
if (this.filepath) {
this.write('# ' + [this.filepath, this.lineNumber].join(':'));
} else {
this.write('# at line: ' + this.lineNumber);
}
};
module.exports = FileRenderer;
},{"power-assert-renderer-base":63,"util":78}],71:[function(_dereq_,module,exports){
'use strict';
var DiagramRenderer = _dereq_('power-assert-renderer-diagram');
var inherits = _dereq_('util').inherits;
var some = _dereq_('core-js/library/fn/array/some');
/**
* options.stringify [function]
* options.maxDepth [number]
* options.lineSeparator [string]
* options.anonymous [string]
* options.circular [string]
*
* options.widthOf [function]
* options.ambiguousEastAsianCharWidth [number]
*/
function SuccinctRenderer (config) {
DiagramRenderer.call(this, config);
}
inherits(SuccinctRenderer, DiagramRenderer);
SuccinctRenderer.prototype.onData = function (esNode) {
if (!esNode.isCaptured) {
return;
}
if (withinMemberExpression(esNode)) {
return;
}
this.dumpIfSupported(esNode);
};
SuccinctRenderer.prototype.dumpIfSupported = function (esNode) {
switch(esNode.node.type) {
case 'Identifier':
case 'MemberExpression':
case 'CallExpression':
this.events.push({value: esNode.value, leftIndex: esNode.range[0]});
break;
}
};
function withinMemberExpression (esNode) {
var ancestors = collectAncestors([], esNode.parent);
return some(ancestors, function (eachNode) {
return eachNode.node.type === 'MemberExpression';
});
}
function collectAncestors (ary, esNode) {
if (!esNode) {
return ary;
}
ary.push(esNode);
return collectAncestors(ary, esNode.parent);
}
module.exports = SuccinctRenderer;
},{"core-js/library/fn/array/some":6,"power-assert-renderer-diagram":67,"util":78}],72:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],73:[function(_dereq_,module,exports){
/**
* stringifier
*
* https://github.com/twada/stringifier
*
* Copyright (c) 2014-2015 Takuto Wada
* Licensed under the MIT license.
* http://twada.mit-license.org/2014-2015
*/
'use strict';
var traverse = _dereq_('traverse');
var typeName = _dereq_('type-name');
var assign = _dereq_('core-js/library/fn/object/assign');
var s = _dereq_('./strategies');
function defaultHandlers () {
return {
'null': s.always('null'),
'undefined': s.always('undefined'),
'function': s.prune(),
'string': s.json(),
'boolean': s.json(),
'number': s.number(),
'symbol': s.toStr(),
'RegExp': s.toStr(),
'String': s.newLike(),
'Boolean': s.newLike(),
'Number': s.newLike(),
'Date': s.newLike(),
'Array': s.array(),
'Object': s.object(),
'@default': s.object()
};
}
function defaultOptions () {
return {
maxDepth: null,
indent: null,
anonymous: '@Anonymous',
circular: '#@Circular#',
snip: '..(snip)',
lineSeparator: '\n',
typeFun: typeName
};
}
function createStringifier (customOptions) {
var options = assign({}, defaultOptions(), customOptions);
var handlers = assign({}, defaultHandlers(), options.handlers);
return function stringifyAny (push, x) {
var context = this;
var handler = handlerFor(context.node, options, handlers);
var currentPath = '/' + context.path.join('/');
var customization = handlers[currentPath];
var acc = {
context: context,
options: options,
handlers: handlers,
push: push
};
if (typeName(customization) === 'function') {
handler = customization;
} else if (typeName(customization) === 'number') {
handler = s.flow.compose(s.filters.truncate(customization),handler);
} else if (context.parent && typeName(context.parent.node) === 'Array' && !(context.key in context.parent.node)) {
// sparse arrays
handler = s.always('');
}
handler(acc, x);
return push;
};
}
function handlerFor (val, options, handlers) {
var tname = options.typeFun(val);
if (typeName(handlers[tname]) === 'function') {
return handlers[tname];
}
return handlers['@default'];
}
function walk (val, reducer) {
var buffer = [];
var push = function (str) {
buffer.push(str);
};
traverse(val).reduce(reducer, push);
return buffer.join('');
}
function stringify (val, options) {
return walk(val, createStringifier(options));
}
function stringifier (options) {
return function (val) {
return walk(val, createStringifier(options));
};
}
stringifier.stringify = stringify;
stringifier.strategies = s;
stringifier.defaultOptions = defaultOptions;
stringifier.defaultHandlers = defaultHandlers;
module.exports = stringifier;
},{"./strategies":74,"core-js/library/fn/object/assign":7,"traverse":75,"type-name":76}],74:[function(_dereq_,module,exports){
'use strict';
var typeName = _dereq_('type-name');
var forEach = _dereq_('core-js/library/fn/array/for-each');
var arrayFilter = _dereq_('core-js/library/fn/array/filter');
var reduceRight = _dereq_('core-js/library/fn/array/reduce-right');
var indexOf = _dereq_('core-js/library/fn/array/index-of');
var slice = Array.prototype.slice;
var END = {};
var ITERATE = {};
// arguments should end with end or iterate
function compose () {
var filters = slice.apply(arguments);
return reduceRight(filters, function(right, left) {
return left(right);
});
}
// skip children
function end () {
return function (acc, x) {
acc.context.keys = [];
return END;
};
}
// iterate children
function iterate () {
return function (acc, x) {
return ITERATE;
};
}
function filter (predicate) {
return function (next) {
return function (acc, x) {
var toBeIterated;
var isIteratingArray = (typeName(x) === 'Array');
if (typeName(predicate) === 'function') {
toBeIterated = [];
forEach(acc.context.keys, function (key) {
var indexOrKey = isIteratingArray ? parseInt(key, 10) : key;
var kvp = {
key: indexOrKey,
value: x[key]
};
var decision = predicate(kvp);
if (decision) {
toBeIterated.push(key);
}
if (typeName(decision) === 'number') {
truncateByKey(decision, key, acc);
}
if (typeName(decision) === 'function') {
customizeStrategyForKey(decision, key, acc);
}
});
acc.context.keys = toBeIterated;
}
return next(acc, x);
};
};
}
function customizeStrategyForKey (strategy, key, acc) {
acc.handlers[currentPath(key, acc)] = strategy;
}
function truncateByKey (size, key, acc) {
acc.handlers[currentPath(key, acc)] = size;
}
function currentPath (key, acc) {
var pathToCurrentNode = [''].concat(acc.context.path);
if (typeName(key) !== 'undefined') {
pathToCurrentNode.push(key);
}
return pathToCurrentNode.join('/');
}
function allowedKeys (orderedWhiteList) {
return function (next) {
return function (acc, x) {
var isIteratingArray = (typeName(x) === 'Array');
if (!isIteratingArray && typeName(orderedWhiteList) === 'Array') {
acc.context.keys = arrayFilter(orderedWhiteList, function (propKey) {
return indexOf(acc.context.keys, propKey) !== -1;
});
}
return next(acc, x);
};
};
}
function safeKeys () {
return function (next) {
return function (acc, x) {
if (typeName(x) !== 'Array') {
acc.context.keys = arrayFilter(acc.context.keys, function (propKey) {
// Error handling for unsafe property access.
// For example, on PhantomJS,
// accessing HTMLInputElement.selectionEnd causes TypeError
try {
var val = x[propKey];
return true;
} catch (e) {
// skip unsafe key
return false;
}
});
}
return next(acc, x);
};
};
}
function arrayIndicesToKeys () {
return function (next) {
return function (acc, x) {
if (typeName(x) === 'Array' && 0 < x.length) {
var indices = Array(x.length);
for(var i = 0; i < x.length; i += 1) {
indices[i] = String(i); // traverse uses strings as keys
}
acc.context.keys = indices;
}
return next(acc, x);
};
};
}
function when (guard, then) {
return function (next) {
return function (acc, x) {
var kvp = {
key: acc.context.key,
value: x
};
if (guard(kvp, acc)) {
return then(acc, x);
}
return next(acc, x);
};
};
}
function truncate (size) {
return function (next) {
return function (acc, x) {
var orig = acc.push;
var ret;
acc.push = function (str) {
var savings = str.length - size;
var truncated;
if (savings <= size) {
orig.call(acc, str);
} else {
truncated = str.substring(0, size);
orig.call(acc, truncated + acc.options.snip);
}
};
ret = next(acc, x);
acc.push = orig;
return ret;
};
};
}
function constructorName () {
return function (next) {
return function (acc, x) {
var name = acc.options.typeFun(x);
if (name === '') {
name = acc.options.anonymous;
}
acc.push(name);
return next(acc, x);
};
};
}
function always (str) {
return function (next) {
return function (acc, x) {
acc.push(str);
return next(acc, x);
};
};
}
function optionValue (key) {
return function (next) {
return function (acc, x) {
acc.push(acc.options[key]);
return next(acc, x);
};
};
}
function json (replacer) {
return function (next) {
return function (acc, x) {
acc.push(JSON.stringify(x, replacer));
return next(acc, x);
};
};
}
function toStr () {
return function (next) {
return function (acc, x) {
acc.push(x.toString());
return next(acc, x);
};
};
}
function decorateArray () {
return function (next) {
return function (acc, x) {
acc.context.before(function (node) {
acc.push('[');
});
acc.context.after(function (node) {
afterAllChildren(this, acc.push, acc.options);
acc.push(']');
});
acc.context.pre(function (val, key) {
beforeEachChild(this, acc.push, acc.options);
});
acc.context.post(function (childContext) {
afterEachChild(childContext, acc.push);
});
return next(acc, x);
};
};
}
function decorateObject () {
return function (next) {
return function (acc, x) {
acc.context.before(function (node) {
acc.push('{');
});
acc.context.after(function (node) {
afterAllChildren(this, acc.push, acc.options);
acc.push('}');
});
acc.context.pre(function (val, key) {
beforeEachChild(this, acc.push, acc.options);
acc.push(sanitizeKey(key) + (acc.options.indent ? ': ' : ':'));
});
acc.context.post(function (childContext) {
afterEachChild(childContext, acc.push);
});
return next(acc, x);
};
};
}
function sanitizeKey (key) {
return /^[A-Za-z_]+$/.test(key) ? key : JSON.stringify(key);
}
function afterAllChildren (context, push, options) {
if (options.indent && 0 < context.keys.length) {
push(options.lineSeparator);
for(var i = 0; i < context.level; i += 1) { // indent level - 1
push(options.indent);
}
}
}
function beforeEachChild (context, push, options) {
if (options.indent) {
push(options.lineSeparator);
for(var i = 0; i <= context.level; i += 1) {
push(options.indent);
}
}
}
function afterEachChild (childContext, push) {
if (!childContext.isLast) {
push(',');
}
}
function nan (kvp, acc) {
return kvp.value !== kvp.value;
}
function positiveInfinity (kvp, acc) {
return !isFinite(kvp.value) && kvp.value === Infinity;
}
function negativeInfinity (kvp, acc) {
return !isFinite(kvp.value) && kvp.value !== Infinity;
}
function circular (kvp, acc) {
return acc.context.circular;
}
function maxDepth (kvp, acc) {
return (acc.options.maxDepth && acc.options.maxDepth <= acc.context.level);
}
var prune = compose(
always('#'),
constructorName(),
always('#'),
end()
);
var omitNaN = when(nan, compose(
always('NaN'),
end()
));
var omitPositiveInfinity = when(positiveInfinity, compose(
always('Infinity'),
end()
));
var omitNegativeInfinity = when(negativeInfinity, compose(
always('-Infinity'),
end()
));
var omitCircular = when(circular, compose(
optionValue('circular'),
end()
));
var omitMaxDepth = when(maxDepth, prune);
module.exports = {
filters: {
always: always,
optionValue: optionValue,
constructorName: constructorName,
json: json,
toStr: toStr,
prune: prune,
truncate: truncate,
decorateArray: decorateArray,
decorateObject: decorateObject
},
flow: {
compose: compose,
when: when,
allowedKeys: allowedKeys,
safeKeys: safeKeys,
arrayIndicesToKeys: arrayIndicesToKeys,
filter: filter,
iterate: iterate,
end: end
},
symbols: {
END: END,
ITERATE: ITERATE
},
always: function (str) {
return compose(always(str), end());
},
json: function () {
return compose(json(), end());
},
toStr: function () {
return compose(toStr(), end());
},
prune: function () {
return prune;
},
number: function () {
return compose(
omitNaN,
omitPositiveInfinity,
omitNegativeInfinity,
json(),
end()
);
},
newLike: function () {
return compose(
always('new '),
constructorName(),
always('('),
json(),
always(')'),
end()
);
},
array: function (predicate) {
return compose(
omitCircular,
omitMaxDepth,
decorateArray(),
arrayIndicesToKeys(),
filter(predicate),
iterate()
);
},
object: function (predicate, orderedWhiteList) {
return compose(
omitCircular,
omitMaxDepth,
constructorName(),
decorateObject(),
allowedKeys(orderedWhiteList),
safeKeys(),
filter(predicate),
iterate()
);
}
};
},{"core-js/library/fn/array/filter":2,"core-js/library/fn/array/for-each":3,"core-js/library/fn/array/index-of":4,"core-js/library/fn/array/reduce-right":5,"type-name":76}],75:[function(_dereq_,module,exports){
var traverse = module.exports = function (obj) {
return new Traverse(obj);
};
function Traverse (obj) {
this.value = obj;
}
Traverse.prototype.get = function (ps) {
var node = this.value;
for (var i = 0; i < ps.length; i ++) {
var key = ps[i];
if (!node || !hasOwnProperty.call(node, key)) {
node = undefined;
break;
}
node = node[key];
}
return node;
};
Traverse.prototype.has = function (ps) {
var node = this.value;
for (var i = 0; i < ps.length; i ++) {
var key = ps[i];
if (!node || !hasOwnProperty.call(node, key)) {
return false;
}
node = node[key];
}
return true;
};
Traverse.prototype.set = function (ps, value) {
var node = this.value;
for (var i = 0; i < ps.length - 1; i ++) {
var key = ps[i];
if (!hasOwnProperty.call(node, key)) node[key] = {};
node = node[key];
}
node[ps[i]] = value;
return value;
};
Traverse.prototype.map = function (cb) {
return walk(this.value, cb, true);
};
Traverse.prototype.forEach = function (cb) {
this.value = walk(this.value, cb, false);
return this.value;
};
Traverse.prototype.reduce = function (cb, init) {
var skip = arguments.length === 1;
var acc = skip ? this.value : init;
this.forEach(function (x) {
if (!this.isRoot || !skip) {
acc = cb.call(this, acc, x);
}
});
return acc;
};
Traverse.prototype.paths = function () {
var acc = [];
this.forEach(function (x) {
acc.push(this.path);
});
return acc;
};
Traverse.prototype.nodes = function () {
var acc = [];
this.forEach(function (x) {
acc.push(this.node);
});
return acc;
};
Traverse.prototype.clone = function () {
var parents = [], nodes = [];
return (function clone (src) {
for (var i = 0; i < parents.length; i++) {
if (parents[i] === src) {
return nodes[i];
}
}
if (typeof src === 'object' && src !== null) {
var dst = copy(src);
parents.push(src);
nodes.push(dst);
forEach(objectKeys(src), function (key) {
dst[key] = clone(src[key]);
});
parents.pop();
nodes.pop();
return dst;
}
else {
return src;
}
})(this.value);
};
function walk (root, cb, immutable) {
var path = [];
var parents = [];
var alive = true;
return (function walker (node_) {
var node = immutable ? copy(node_) : node_;
var modifiers = {};
var keepGoing = true;
var state = {
node : node,
node_ : node_,
path : [].concat(path),
parent : parents[parents.length - 1],
parents : parents,
key : path.slice(-1)[0],
isRoot : path.length === 0,
level : path.length,
circular : null,
update : function (x, stopHere) {
if (!state.isRoot) {
state.parent.node[state.key] = x;
}
state.node = x;
if (stopHere) keepGoing = false;
},
'delete' : function (stopHere) {
delete state.parent.node[state.key];
if (stopHere) keepGoing = false;
},
remove : function (stopHere) {
if (isArray(state.parent.node)) {
state.parent.node.splice(state.key, 1);
}
else {
delete state.parent.node[state.key];
}
if (stopHere) keepGoing = false;
},
keys : null,
before : function (f) { modifiers.before = f },
after : function (f) { modifiers.after = f },
pre : function (f) { modifiers.pre = f },
post : function (f) { modifiers.post = f },
stop : function () { alive = false },
block : function () { keepGoing = false }
};
if (!alive) return state;
function updateState() {
if (typeof state.node === 'object' && state.node !== null) {
if (!state.keys || state.node_ !== state.node) {
state.keys = objectKeys(state.node)
}
state.isLeaf = state.keys.length == 0;
for (var i = 0; i < parents.length; i++) {
if (parents[i].node_ === node_) {
state.circular = parents[i];
break;
}
}
}
else {
state.isLeaf = true;
state.keys = null;
}
state.notLeaf = !state.isLeaf;
state.notRoot = !state.isRoot;
}
updateState();
// use return values to update if defined
var ret = cb.call(state, state.node);
if (ret !== undefined && state.update) state.update(ret);
if (modifiers.before) modifiers.before.call(state, state.node);
if (!keepGoing) return state;
if (typeof state.node == 'object'
&& state.node !== null && !state.circular) {
parents.push(state);
updateState();
forEach(state.keys, function (key, i) {
path.push(key);
if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);
var child = walker(state.node[key]);
if (immutable && hasOwnProperty.call(state.node, key)) {
state.node[key] = child.node;
}
child.isLast = i == state.keys.length - 1;
child.isFirst = i == 0;
if (modifiers.post) modifiers.post.call(state, child);
path.pop();
});
parents.pop();
}
if (modifiers.after) modifiers.after.call(state, state.node);
return state;
})(root).node;
}
function copy (src) {
if (typeof src === 'object' && src !== null) {
var dst;
if (isArray(src)) {
dst = [];
}
else if (isDate(src)) {
dst = new Date(src.getTime ? src.getTime() : src);
}
else if (isRegExp(src)) {
dst = new RegExp(src);
}
else if (isError(src)) {
dst = { message: src.message };
}
else if (isBoolean(src)) {
dst = new Boolean(src);
}
else if (isNumber(src)) {
dst = new Number(src);
}
else if (isString(src)) {
dst = new String(src);
}
else if (Object.create && Object.getPrototypeOf) {
dst = Object.create(Object.getPrototypeOf(src));
}
else if (src.constructor === Object) {
dst = {};
}
else {
var proto =
(src.constructor && src.constructor.prototype)
|| src.__proto__
|| {}
;
var T = function () {};
T.prototype = proto;
dst = new T;
}
forEach(objectKeys(src), function (key) {
dst[key] = src[key];
});
return dst;
}
else return src;
}
var objectKeys = Object.keys || function keys (obj) {
var res = [];
for (var key in obj) res.push(key)
return res;
};
function toS (obj) { return Object.prototype.toString.call(obj) }
function isDate (obj) { return toS(obj) === '[object Date]' }
function isRegExp (obj) { return toS(obj) === '[object RegExp]' }
function isError (obj) { return toS(obj) === '[object Error]' }
function isBoolean (obj) { return toS(obj) === '[object Boolean]' }
function isNumber (obj) { return toS(obj) === '[object Number]' }
function isString (obj) { return toS(obj) === '[object String]' }
var isArray = Array.isArray || function isArray (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
var forEach = function (xs, fn) {
if (xs.forEach) return xs.forEach(fn)
else for (var i = 0; i < xs.length; i++) {
fn(xs[i], i, xs);
}
};
forEach(objectKeys(Traverse.prototype), function (key) {
traverse[key] = function (obj) {
var args = [].slice.call(arguments, 1);
var t = new Traverse(obj);
return t[key].apply(t, args);
};
});
var hasOwnProperty = Object.hasOwnProperty || function (obj, key) {
return key in obj;
};
},{}],76:[function(_dereq_,module,exports){
/**
* type-name - Just a reasonable typeof
*
* https://github.com/twada/type-name
*
* Copyright (c) 2014-2016 Takuto Wada
* Licensed under the MIT license.
* http://twada.mit-license.org/2014-2016
*/
'use strict';
var toStr = Object.prototype.toString;
function funcName (f) {
return f.name ? f.name : /^\s*function\s*([^\(]*)/im.exec(f.toString())[1];
}
function ctorName (obj) {
var strName = toStr.call(obj).slice(8, -1);
if ((strName === 'Object' || strName === 'Error') && obj.constructor) {
return funcName(obj.constructor);
}
return strName;
}
function typeName (val) {
var type;
if (val === null) {
return 'null';
}
type = typeof(val);
if (type === 'object') {
return ctorName(val);
}
return type;
}
module.exports = typeName;
},{}],77:[function(_dereq_,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],78:[function(_dereq_,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 = _dereq_('./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 = _dereq_('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,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":77,"_process":72,"inherits":61}]},{},[1])(1)
});