Updated eslint whitespace rules

This commit is contained in:
n1474335 2017-02-09 15:09:33 +00:00
parent ebf2258715
commit e803d208e8
51 changed files with 801 additions and 793 deletions

View File

@ -135,7 +135,7 @@ module.exports = function(grunt) {
"src/js/lib/Sortable.js", "src/js/lib/Sortable.js",
"src/js/lib/bootstrap-colorpicker.js", "src/js/lib/bootstrap-colorpicker.js",
"src/js/lib/xpath.js", "src/js/lib/xpath.js",
// Custom libraries // Custom libraries
"src/js/lib/canvas_components.js", "src/js/lib/canvas_components.js",

View File

@ -45,9 +45,7 @@
"comma-spacing": "error", "comma-spacing": "error",
"comma-style": "error", "comma-style": "error",
"computed-property-spacing": "error", "computed-property-spacing": "error",
"no-trailing-spaces": ["warn", { "no-trailing-spaces": "warn",
"skipBlankLines": true
}],
"eol-last": "error", "eol-last": "error",
"func-call-spacing": "error", "func-call-spacing": "error",
"indent": ["error", 4, { "indent": ["error", 4, {
@ -70,7 +68,19 @@
"ClassDeclaration": true, "ClassDeclaration": true,
"ArrowFunctionExpression": true "ArrowFunctionExpression": true
} }
}] }],
"keyword-spacing": ["error", {
"before": true,
"after": true
}],
"no-multiple-empty-lines": ["warn", {
"max": 2,
"maxEOF": 1,
"maxBOF": 0
}],
"no-whitespace-before-property": "error",
"operator-linebreak": ["error", "after"],
"space-in-parens": "error"
}, },
"globals": { "globals": {
/* core/* */ /* core/* */

View File

@ -113,7 +113,7 @@ Chef.prototype.silentBake = function(recipeConfig) {
try { try {
recipe.execute(dish); recipe.execute(dish);
} catch(err) { } catch (err) {
// Suppress all errors // Suppress all errors
} }
return new Date().getTime() - startTime; return new Date().getTime() - startTime;

View File

@ -100,7 +100,7 @@ Dish.enumLookup = function(typeEnum) {
Dish.prototype.set = function(value, type) { Dish.prototype.set = function(value, type) {
this.value = value; this.value = value;
this.type = type; this.type = type;
if (!this.valid()) { if (!this.valid()) {
var sample = Utils.truncate(JSON.stringify(this.value), 13); var sample = Utils.truncate(JSON.stringify(this.value), 13);
throw "Data is not a valid " + Dish.enumLookup(type) + ": " + sample; throw "Data is not a valid " + Dish.enumLookup(type) + ": " + sample;
@ -145,7 +145,7 @@ Dish.prototype.translate = function(toType) {
default: default:
break; break;
} }
// Convert from byteArray to toType // Convert from byteArray to toType
switch (toType) { switch (toType) {
case Dish.STRING: case Dish.STRING:
@ -175,7 +175,7 @@ Dish.prototype.valid = function() {
if (!(this.value instanceof Array)) { if (!(this.value instanceof Array)) {
return false; return false;
} }
// Check that every value is a number between 0 - 255 // Check that every value is a number between 0 - 255
for (var i = 0; i < this.value.length; i++) { for (var i = 0; i < this.value.length; i++) {
if (typeof this.value[i] != "number" || if (typeof this.value[i] != "number" ||

View File

@ -24,7 +24,7 @@ var FlowControl = {
* @default * @default
*/ */
FORK_IGNORE_ERRORS: false, FORK_IGNORE_ERRORS: false,
/** /**
* Fork operation. * Fork operation.
* *
@ -45,10 +45,10 @@ var FlowControl = {
ignoreErrors = ings[2], ignoreErrors = ings[2],
subOpList = [], subOpList = [],
inputs = []; inputs = [];
if (input) if (input)
inputs = input.split(splitDelim); inputs = input.split(splitDelim);
// Create subOpList for each tranche to operate on // Create subOpList for each tranche to operate on
// (all remaining operations unless we encounter a Merge) // (all remaining operations unless we encounter a Merge)
for (var i = state.progress + 1; i < opList.length; i++) { for (var i = state.progress + 1; i < opList.length; i++) {
@ -58,19 +58,19 @@ var FlowControl = {
subOpList.push(opList[i]); subOpList.push(opList[i]);
} }
} }
var recipe = new Recipe(), var recipe = new Recipe(),
output = "", output = "",
progress = 0; progress = 0;
recipe.addOperations(subOpList); recipe.addOperations(subOpList);
// Run recipe over each tranche // Run recipe over each tranche
for (i = 0; i < inputs.length; i++) { for (i = 0; i < inputs.length; i++) {
var dish = new Dish(inputs[i], inputType); var dish = new Dish(inputs[i], inputType);
try { try {
progress = recipe.execute(dish, 0); progress = recipe.execute(dish, 0);
} catch(err) { } catch (err) {
if (!ignoreErrors) { if (!ignoreErrors) {
throw err; throw err;
} }
@ -78,13 +78,13 @@ var FlowControl = {
} }
output += dish.get(outputType) + mergeDelim; output += dish.get(outputType) + mergeDelim;
} }
state.dish.set(output, outputType); state.dish.set(output, outputType);
state.progress += progress; state.progress += progress;
return state; return state;
}, },
/** /**
* Merge operation. * Merge operation.
* *
@ -99,8 +99,8 @@ var FlowControl = {
// merge when it sees this operation. // merge when it sees this operation.
return state; return state;
}, },
/** /**
* @constant * @constant
* @default * @default
@ -111,7 +111,7 @@ var FlowControl = {
* @default * @default
*/ */
MAX_JUMPS: 10, MAX_JUMPS: 10,
/** /**
* Jump operation. * Jump operation.
* *
@ -126,18 +126,18 @@ var FlowControl = {
var ings = state.opList[state.progress].getIngValues(), var ings = state.opList[state.progress].getIngValues(),
jumpNum = ings[0], jumpNum = ings[0],
maxJumps = ings[1]; maxJumps = ings[1];
if (state.numJumps >= maxJumps) { if (state.numJumps >= maxJumps) {
state.progress++; state.progress++;
return state; return state;
} }
state.progress += jumpNum; state.progress += jumpNum;
state.numJumps++; state.numJumps++;
return state; return state;
}, },
/** /**
* Conditional Jump operation. * Conditional Jump operation.
* *
@ -154,21 +154,21 @@ var FlowControl = {
regexStr = ings[0], regexStr = ings[0],
jumpNum = ings[1], jumpNum = ings[1],
maxJumps = ings[2]; maxJumps = ings[2];
if (state.numJumps >= maxJumps) { if (state.numJumps >= maxJumps) {
state.progress++; state.progress++;
return state; return state;
} }
if (regexStr !== "" && dish.get(Dish.STRING).search(regexStr) > -1) { if (regexStr !== "" && dish.get(Dish.STRING).search(regexStr) > -1) {
state.progress += jumpNum; state.progress += jumpNum;
state.numJumps++; state.numJumps++;
} }
return state; return state;
}, },
/** /**
* Return operation. * Return operation.
* *
@ -182,5 +182,5 @@ var FlowControl = {
state.progress = state.opList.length; state.progress = state.opList.length;
return state; return state;
}, },
}; };

View File

@ -12,7 +12,7 @@ var Ingredient = function(ingredientConfig) {
this.name = ""; this.name = "";
this.type = ""; this.type = "";
this.value = null; this.value = null;
if (ingredientConfig) { if (ingredientConfig) {
this._parseConfig(ingredientConfig); this._parseConfig(ingredientConfig);
} }

View File

@ -20,7 +20,7 @@ var Operation = function(operationName, operationConfig) {
this.breakpoint = false; this.breakpoint = false;
this.disabled = false; this.disabled = false;
this.ingList = []; this.ingList = [];
if (operationConfig) { if (operationConfig) {
this._parseConfig(operationConfig); this._parseConfig(operationConfig);
} }
@ -57,16 +57,16 @@ Operation.prototype._parseConfig = function(operationConfig) {
*/ */
Operation.prototype.getConfig = function() { Operation.prototype.getConfig = function() {
var ingredientConfig = []; var ingredientConfig = [];
for (var o = 0; o < this.ingList.length; o++) { for (var o = 0; o < this.ingList.length; o++) {
ingredientConfig.push(this.ingList[o].getConfig()); ingredientConfig.push(this.ingList[o].getConfig());
} }
var operationConfig = { var operationConfig = {
"op": this.name, "op": this.name,
"args": ingredientConfig "args": ingredientConfig
}; };
return operationConfig; return operationConfig;
}; };

View File

@ -10,7 +10,7 @@
*/ */
var Recipe = function(recipeConfig) { var Recipe = function(recipeConfig) {
this.opList = []; this.opList = [];
if (recipeConfig) { if (recipeConfig) {
this._parseConfig(recipeConfig); this._parseConfig(recipeConfig);
} }
@ -43,11 +43,11 @@ Recipe.prototype._parseConfig = function(recipeConfig) {
*/ */
Recipe.prototype.getConfig = function() { Recipe.prototype.getConfig = function() {
var recipeConfig = []; var recipeConfig = [];
for (var o = 0; o < this.opList.length; o++) { for (var o = 0; o < this.opList.length; o++) {
recipeConfig.push(this.opList[o].getConfig()); recipeConfig.push(this.opList[o].getConfig());
} }
return recipeConfig; return recipeConfig;
}; };
@ -123,13 +123,13 @@ Recipe.prototype.containsFlowControl = function() {
Recipe.prototype.lastOpIndex = function(startIndex) { Recipe.prototype.lastOpIndex = function(startIndex) {
var i = startIndex + 1 || 0, var i = startIndex + 1 || 0,
op; op;
for (; i < this.opList.length; i++) { for (; i < this.opList.length; i++) {
op = this.opList[i]; op = this.opList[i];
if (op.isDisabled()) return i-1; if (op.isDisabled()) return i-1;
if (op.isBreakpoint()) return i-1; if (op.isBreakpoint()) return i-1;
} }
return i-1; return i-1;
}; };
@ -144,7 +144,7 @@ Recipe.prototype.lastOpIndex = function(startIndex) {
Recipe.prototype.execute = function(dish, startFrom) { Recipe.prototype.execute = function(dish, startFrom) {
startFrom = startFrom || 0; startFrom = startFrom || 0;
var op, input, output, numJumps = 0; var op, input, output, numJumps = 0;
for (var i = startFrom; i < this.opList.length; i++) { for (var i = startFrom; i < this.opList.length; i++) {
op = this.opList[i]; op = this.opList[i];
if (op.isDisabled()) { if (op.isDisabled()) {
@ -153,10 +153,10 @@ Recipe.prototype.execute = function(dish, startFrom) {
if (op.isBreakpoint()) { if (op.isBreakpoint()) {
return i; return i;
} }
try { try {
input = dish.get(op.inputType); input = dish.get(op.inputType);
if (op.isFlowControl()) { if (op.isFlowControl()) {
// Package up the current state // Package up the current state
var state = { var state = {
@ -165,7 +165,7 @@ Recipe.prototype.execute = function(dish, startFrom) {
"opList" : this.opList, "opList" : this.opList,
"numJumps" : numJumps "numJumps" : numJumps
}; };
state = op.run(state); state = op.run(state);
i = state.progress; i = state.progress;
numJumps = state.numJumps; numJumps = state.numJumps;
@ -184,11 +184,11 @@ Recipe.prototype.execute = function(dish, startFrom) {
} else { } else {
e.displayStr = op.name + " - " + (e.displayStr || e.message); e.displayStr = op.name + " - " + (e.displayStr || e.message);
} }
throw e; throw e;
} }
} }
return this.opList.length; return this.opList.length;
}; };

View File

@ -922,8 +922,8 @@ var Utils = {
* @returns {Object} * @returns {Object}
*/ */
extend: function(a, b){ extend: function(a, b){
for(var key in b) for (var key in b)
if(b.hasOwnProperty(key)) if (b.hasOwnProperty(key))
a[key] = b[key]; a[key] = b[key];
return a; return a;
}, },
@ -1169,7 +1169,6 @@ String.prototype.count = function(chr) {
}; };
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
// Library overrides /////////////////////////////////////////////////////////////////////////////// // Library overrides ///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////

View File

@ -14,7 +14,7 @@ var Base = {
* @default * @default
*/ */
DEFAULT_RADIX: 36, DEFAULT_RADIX: 36,
/** /**
* To Base operation. * To Base operation.
* *
@ -32,8 +32,8 @@ var Base = {
} }
return input.toString(radix); return input.toString(radix);
}, },
/** /**
* From Base operation. * From Base operation.
* *
@ -48,5 +48,5 @@ var Base = {
} }
return parseInt(input.replace(/\s/g, ""), radix); return parseInt(input.replace(/\s/g, ""), radix);
}, },
}; };

View File

@ -28,7 +28,7 @@ var BitwiseOp = {
x = null, x = null,
k = null, k = null,
o = null; o = null;
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
k = key[i % key.length]; k = key[i % key.length];
o = input[i]; o = input[i];
@ -45,11 +45,11 @@ var BitwiseOp = {
} }
} }
} }
return result; return result;
}, },
/** /**
* @constant * @constant
* @default * @default
@ -65,7 +65,7 @@ var BitwiseOp = {
* @default * @default
*/ */
KEY_FORMAT: ["Hex", "Base64", "UTF8", "UTF16", "UTF16LE", "UTF16BE", "Latin1"], KEY_FORMAT: ["Hex", "Base64", "UTF8", "UTF16", "UTF16LE", "UTF16BE", "Latin1"],
/** /**
* XOR operation. * XOR operation.
* *
@ -77,13 +77,13 @@ var BitwiseOp = {
var key = Utils.format[args[0].option].parse(args[0].string || ""), var key = Utils.format[args[0].option].parse(args[0].string || ""),
scheme = args[1], scheme = args[1],
nullPreserving = args[2]; nullPreserving = args[2];
key = Utils.wordArrayToByteArray(key); key = Utils.wordArrayToByteArray(key);
return BitwiseOp._bitOp(input, key, BitwiseOp._xor, nullPreserving, scheme); return BitwiseOp._bitOp(input, key, BitwiseOp._xor, nullPreserving, scheme);
}, },
/** /**
* @constant * @constant
* @default * @default
@ -109,7 +109,7 @@ var BitwiseOp = {
* @default * @default
*/ */
XOR_BRUTE_OUTPUT_HEX: false, XOR_BRUTE_OUTPUT_HEX: false,
/** /**
* XOR Brute Force operation. * XOR Brute Force operation.
* *
@ -127,18 +127,18 @@ var BitwiseOp = {
printKey = args[6], printKey = args[6],
outputHex = args[7], outputHex = args[7],
regex; regex;
var output = "", var output = "",
result, result,
resultUtf8; resultUtf8;
input = input.slice(sampleOffset, sampleOffset + sampleLength); input = input.slice(sampleOffset, sampleOffset + sampleLength);
if (crib !== "") { if (crib !== "") {
regex = new RegExp(crib, "im"); regex = new RegExp(crib, "im");
} }
for (var key = 1, l = Math.pow(256, keyLength); key < l; key++) { for (var key = 1, l = Math.pow(256, keyLength); key < l; key++) {
result = BitwiseOp._bitOp(input, Utils.hexToByteArray(key.toString(16)), BitwiseOp._xor, nullPreserving, differential); result = BitwiseOp._bitOp(input, Utils.hexToByteArray(key.toString(16)), BitwiseOp._xor, nullPreserving, differential);
resultUtf8 = Utils.byteArrayToUtf8(result); resultUtf8 = Utils.byteArrayToUtf8(result);
@ -152,8 +152,8 @@ var BitwiseOp = {
} }
return output; return output;
}, },
/** /**
* NOT operation. * NOT operation.
* *
@ -164,8 +164,8 @@ var BitwiseOp = {
runNot: function (input, args) { runNot: function (input, args) {
return BitwiseOp._bitOp(input, null, BitwiseOp._not); return BitwiseOp._bitOp(input, null, BitwiseOp._not);
}, },
/** /**
* AND operation. * AND operation.
* *
@ -176,11 +176,11 @@ var BitwiseOp = {
runAnd: function (input, args) { runAnd: function (input, args) {
var key = Utils.format[args[0].option].parse(args[0].string || ""); var key = Utils.format[args[0].option].parse(args[0].string || "");
key = Utils.wordArrayToByteArray(key); key = Utils.wordArrayToByteArray(key);
return BitwiseOp._bitOp(input, key, BitwiseOp._and); return BitwiseOp._bitOp(input, key, BitwiseOp._and);
}, },
/** /**
* OR operation. * OR operation.
* *
@ -191,11 +191,11 @@ var BitwiseOp = {
runOr: function (input, args) { runOr: function (input, args) {
var key = Utils.format[args[0].option].parse(args[0].string || ""); var key = Utils.format[args[0].option].parse(args[0].string || "");
key = Utils.wordArrayToByteArray(key); key = Utils.wordArrayToByteArray(key);
return BitwiseOp._bitOp(input, key, BitwiseOp._or); return BitwiseOp._bitOp(input, key, BitwiseOp._or);
}, },
/** /**
* ADD operation. * ADD operation.
* *
@ -206,11 +206,11 @@ var BitwiseOp = {
runAdd: function (input, args) { runAdd: function (input, args) {
var key = Utils.format[args[0].option].parse(args[0].string || ""); var key = Utils.format[args[0].option].parse(args[0].string || "");
key = Utils.wordArrayToByteArray(key); key = Utils.wordArrayToByteArray(key);
return BitwiseOp._bitOp(input, key, BitwiseOp._add); return BitwiseOp._bitOp(input, key, BitwiseOp._add);
}, },
/** /**
* SUB operation. * SUB operation.
* *
@ -221,11 +221,11 @@ var BitwiseOp = {
runSub: function (input, args) { runSub: function (input, args) {
var key = Utils.format[args[0].option].parse(args[0].string || ""); var key = Utils.format[args[0].option].parse(args[0].string || "");
key = Utils.wordArrayToByteArray(key); key = Utils.wordArrayToByteArray(key);
return BitwiseOp._bitOp(input, key, BitwiseOp._sub); return BitwiseOp._bitOp(input, key, BitwiseOp._sub);
}, },
/** /**
* XOR bitwise calculation. * XOR bitwise calculation.
* *
@ -237,8 +237,8 @@ var BitwiseOp = {
_xor: function (operand, key) { _xor: function (operand, key) {
return operand ^ key; return operand ^ key;
}, },
/** /**
* NOT bitwise calculation. * NOT bitwise calculation.
* *
@ -249,8 +249,8 @@ var BitwiseOp = {
_not: function (operand, _) { _not: function (operand, _) {
return ~operand & 0xff; return ~operand & 0xff;
}, },
/** /**
* AND bitwise calculation. * AND bitwise calculation.
* *
@ -262,8 +262,8 @@ var BitwiseOp = {
_and: function (operand, key) { _and: function (operand, key) {
return operand & key; return operand & key;
}, },
/** /**
* OR bitwise calculation. * OR bitwise calculation.
* *
@ -276,7 +276,7 @@ var BitwiseOp = {
return operand | key; return operand | key;
}, },
/** /**
* ADD bitwise calculation. * ADD bitwise calculation.
* *
@ -289,7 +289,7 @@ var BitwiseOp = {
return (operand + key) % 256; return (operand + key) % 256;
}, },
/** /**
* SUB bitwise calculation. * SUB bitwise calculation.
* *

View File

@ -16,7 +16,7 @@ var CharEnc = {
* @default * @default
*/ */
IO_FORMAT: ["UTF8", "UTF16", "UTF16LE", "UTF16BE", "Latin1", "Windows-1251", "Hex", "Base64"], IO_FORMAT: ["UTF8", "UTF16", "UTF16LE", "UTF16BE", "Latin1", "Windows-1251", "Hex", "Base64"],
/** /**
* Text encoding operation. * Text encoding operation.
* *
@ -27,14 +27,14 @@ var CharEnc = {
run: function(input, args) { run: function(input, args) {
var inputFormat = args[0], var inputFormat = args[0],
outputFormat = args[1]; outputFormat = args[1];
if (inputFormat === "Windows-1251") { if (inputFormat === "Windows-1251") {
input = Utils.win1251ToUnicode(input); input = Utils.win1251ToUnicode(input);
input = CryptoJS.enc.Utf8.parse(input); input = CryptoJS.enc.Utf8.parse(input);
} else { } else {
input = Utils.format[inputFormat].parse(input); input = Utils.format[inputFormat].parse(input);
} }
if (outputFormat === "Windows-1251") { if (outputFormat === "Windows-1251") {
input = CryptoJS.enc.Utf8.stringify(input); input = CryptoJS.enc.Utf8.stringify(input);
return Utils.unicodeToWin1251(input); return Utils.unicodeToWin1251(input);
@ -42,5 +42,5 @@ var CharEnc = {
return Utils.format[outputFormat].stringify(input); return Utils.format[outputFormat].stringify(input);
} }
}, },
}; };

View File

@ -19,12 +19,12 @@ var Checksum = {
runFletcher8: function(input, args) { runFletcher8: function(input, args) {
var a = 0, var a = 0,
b = 0; b = 0;
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
a = (a + input[i]) % 0xf; a = (a + input[i]) % 0xf;
b = (b + a) % 0xf; b = (b + a) % 0xf;
} }
return Utils.hex(((b << 4) | a) >>> 0, 2); return Utils.hex(((b << 4) | a) >>> 0, 2);
}, },
@ -39,12 +39,12 @@ var Checksum = {
runFletcher16: function(input, args) { runFletcher16: function(input, args) {
var a = 0, var a = 0,
b = 0; b = 0;
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
a = (a + input[i]) % 0xff; a = (a + input[i]) % 0xff;
b = (b + a) % 0xff; b = (b + a) % 0xff;
} }
return Utils.hex(((b << 8) | a) >>> 0, 4); return Utils.hex(((b << 8) | a) >>> 0, 4);
}, },
@ -59,12 +59,12 @@ var Checksum = {
runFletcher32: function(input, args) { runFletcher32: function(input, args) {
var a = 0, var a = 0,
b = 0; b = 0;
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
a = (a + input[i]) % 0xffff; a = (a + input[i]) % 0xffff;
b = (b + a) % 0xffff; b = (b + a) % 0xffff;
} }
return Utils.hex(((b << 16) | a) >>> 0, 8); return Utils.hex(((b << 16) | a) >>> 0, 8);
}, },
@ -79,16 +79,16 @@ var Checksum = {
runFletcher64: function(input, args) { runFletcher64: function(input, args) {
var a = 0, var a = 0,
b = 0; b = 0;
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
a = (a + input[i]) % 0xffffffff; a = (a + input[i]) % 0xffffffff;
b = (b + a) % 0xffffffff; b = (b + a) % 0xffffffff;
} }
return Utils.hex(b >>> 0, 8) + Utils.hex(a >>> 0, 8); return Utils.hex(b >>> 0, 8) + Utils.hex(a >>> 0, 8);
}, },
/** /**
* Adler-32 Checksum operation. * Adler-32 Checksum operation.
* *
@ -100,19 +100,19 @@ var Checksum = {
var MOD_ADLER = 65521, var MOD_ADLER = 65521,
a = 1, a = 1,
b = 0; b = 0;
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
a += input[i]; a += input[i];
b += a; b += a;
} }
a %= MOD_ADLER; a %= MOD_ADLER;
b %= MOD_ADLER; b %= MOD_ADLER;
return Utils.hex(((b << 16) | a) >>> 0, 8); return Utils.hex(((b << 16) | a) >>> 0, 8);
}, },
/** /**
* CRC-32 Checksum operation. * CRC-32 Checksum operation.
* *
@ -123,15 +123,15 @@ var Checksum = {
runCRC32: function(input, args) { runCRC32: function(input, args) {
var crcTable = window.crcTable || (window.crcTable = Checksum._genCRCTable()), var crcTable = window.crcTable || (window.crcTable = Checksum._genCRCTable()),
crc = 0 ^ (-1); crc = 0 ^ (-1);
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ input[i]) & 0xff]; crc = (crc >>> 8) ^ crcTable[(crc ^ input[i]) & 0xff];
} }
return Utils.hex((crc ^ (-1)) >>> 0); return Utils.hex((crc ^ (-1)) >>> 0);
}, },
/** /**
* TCP/IP Checksum operation. * TCP/IP Checksum operation.
* *
@ -151,9 +151,9 @@ var Checksum = {
*/ */
runTCPIP: function(input, args) { runTCPIP: function(input, args) {
var csum = 0; var csum = 0;
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
if(i % 2 === 0) { if (i % 2 === 0) {
csum += (input[i] << 8); csum += (input[i] << 8);
} else { } else {
csum += input[i]; csum += input[i];
@ -164,8 +164,8 @@ var Checksum = {
return Utils.hex(0xffff - csum); return Utils.hex(0xffff - csum);
}, },
/** /**
* Generates a CRC table for use with CRC checksums. * Generates a CRC table for use with CRC checksums.
* *
@ -175,7 +175,7 @@ var Checksum = {
_genCRCTable: function() { _genCRCTable: function() {
var c, var c,
crcTable = []; crcTable = [];
for (var n = 0; n < 256; n++) { for (var n = 0; n < 256; n++) {
c = n; c = n;
for (var k = 0; k < 8; k++) { for (var k = 0; k < 8; k++) {
@ -183,7 +183,7 @@ var Checksum = {
} }
crcTable[n] = c; crcTable[n] = c;
} }
return crcTable; return crcTable;
}, },

View File

@ -460,7 +460,7 @@ var Cipher = {
msgIndex = alphabet.indexOf(input[i]); msgIndex = alphabet.indexOf(input[i]);
// Subtract indexes from each other, add 26 just in case the value is negative, // Subtract indexes from each other, add 26 just in case the value is negative,
// modulo to remove if neccessary // modulo to remove if neccessary
output += alphabet[(msgIndex - keyIndex + alphabet.length ) % 26]; output += alphabet[(msgIndex - keyIndex + alphabet.length) % 26];
} else if (alphabet.indexOf(input[i].toLowerCase()) >= 0) { } else if (alphabet.indexOf(input[i].toLowerCase()) >= 0) {
chr = key[(i - fail) % key.length].toLowerCase(); chr = key[(i - fail) % key.length].toLowerCase();
keyIndex = alphabet.indexOf(chr); keyIndex = alphabet.indexOf(chr);
@ -546,7 +546,7 @@ var Cipher = {
// Calculates modular inverse of a // Calculates modular inverse of a
aModInv = Utils.modInv(a, 26); aModInv = Utils.modInv(a, 26);
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
if (alphabet.indexOf(input[i]) >= 0) { if (alphabet.indexOf(input[i]) >= 0) {
// Uses the affine decode function (y-b * A') % m = x (where m is length of the alphabet and A' is modular inverse) // Uses the affine decode function (y-b * A') % m = x (where m is length of the alphabet and A' is modular inverse)

View File

@ -244,7 +244,7 @@ var Code = {
var i = 0, var i = 0,
level = 0; level = 0;
while (i < code.length) { while (i < code.length) {
switch(code[i]) { switch (code[i]) {
case "{": case "{":
level++; level++;
break; break;

View File

@ -40,7 +40,7 @@ var Compress = {
"Dynamic Huffman Coding" : Zlib.RawDeflate.CompressionType.DYNAMIC, "Dynamic Huffman Coding" : Zlib.RawDeflate.CompressionType.DYNAMIC,
"None (Store)" : Zlib.RawDeflate.CompressionType.NONE, "None (Store)" : Zlib.RawDeflate.CompressionType.NONE,
}, },
/** /**
* Raw Deflate operation. * Raw Deflate operation.
* *
@ -54,8 +54,8 @@ var Compress = {
}); });
return Array.prototype.slice.call(deflate.compress()); return Array.prototype.slice.call(deflate.compress());
}, },
/** /**
* @constant * @constant
* @default * @default
@ -84,7 +84,7 @@ var Compress = {
"Adaptive" : Zlib.RawInflate.BufferType.ADAPTIVE, "Adaptive" : Zlib.RawInflate.BufferType.ADAPTIVE,
"Block" : Zlib.RawInflate.BufferType.BLOCK, "Block" : Zlib.RawInflate.BufferType.BLOCK,
}, },
/** /**
* Raw Inflate operation. * Raw Inflate operation.
* *
@ -103,7 +103,7 @@ var Compress = {
verify: args[4] verify: args[4]
}), }),
result = Array.prototype.slice.call(inflate.decompress()); result = Array.prototype.slice.call(inflate.decompress());
// Raw Inflate somethimes messes up and returns nonsense like this: // Raw Inflate somethimes messes up and returns nonsense like this:
// ]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]... // ]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]....]...
// e.g. Input data of [8b, 1d, dc, 44] // e.g. Input data of [8b, 1d, dc, 44]
@ -117,7 +117,7 @@ var Compress = {
valid = true; valid = true;
} }
} }
if (!valid) { if (!valid) {
throw "Error: Unable to inflate data"; throw "Error: Unable to inflate data";
} }
@ -125,8 +125,8 @@ var Compress = {
// Trust me, this is the easiest way... // Trust me, this is the easiest way...
return result; return result;
}, },
/** /**
* @constant * @constant
* @default * @default
@ -136,7 +136,7 @@ var Compress = {
"Dynamic Huffman Coding" : Zlib.Deflate.CompressionType.DYNAMIC, "Dynamic Huffman Coding" : Zlib.Deflate.CompressionType.DYNAMIC,
"None (Store)" : Zlib.Deflate.CompressionType.NONE, "None (Store)" : Zlib.Deflate.CompressionType.NONE,
}, },
/** /**
* Zlib Deflate operation. * Zlib Deflate operation.
* *
@ -150,8 +150,8 @@ var Compress = {
}); });
return Array.prototype.slice.call(deflate.compress()); return Array.prototype.slice.call(deflate.compress());
}, },
/** /**
* @constant * @constant
* @default * @default
@ -160,7 +160,7 @@ var Compress = {
"Adaptive" : Zlib.Inflate.BufferType.ADAPTIVE, "Adaptive" : Zlib.Inflate.BufferType.ADAPTIVE,
"Block" : Zlib.Inflate.BufferType.BLOCK, "Block" : Zlib.Inflate.BufferType.BLOCK,
}, },
/** /**
* Zlib Inflate operation. * Zlib Inflate operation.
* *
@ -180,14 +180,14 @@ var Compress = {
}); });
return Array.prototype.slice.call(inflate.decompress()); return Array.prototype.slice.call(inflate.decompress());
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
GZIP_CHECKSUM: false, GZIP_CHECKSUM: false,
/** /**
* Gzip operation. * Gzip operation.
* *
@ -206,7 +206,7 @@ var Compress = {
fhcrc: args[3] fhcrc: args[3]
} }
}; };
if (filename.length) { if (filename.length) {
options.flags.fname = true; options.flags.fname = true;
options.filename = filename; options.filename = filename;
@ -215,12 +215,12 @@ var Compress = {
options.flags.fcommenct = true; options.flags.fcommenct = true;
options.comment = comment; options.comment = comment;
} }
var gzip = new Zlib.Gzip(input, options); var gzip = new Zlib.Gzip(input, options);
return Array.prototype.slice.call(gzip.compress()); return Array.prototype.slice.call(gzip.compress());
}, },
/** /**
* Gunzip operation. * Gunzip operation.
* *
@ -234,8 +234,8 @@ var Compress = {
var gunzip = new Zlib.Gunzip(input); var gunzip = new Zlib.Gunzip(input);
return Array.prototype.slice.call(gunzip.decompress()); return Array.prototype.slice.call(gunzip.decompress());
}, },
/** /**
* @constant * @constant
* @default * @default
@ -258,7 +258,7 @@ var Compress = {
"Unix" : Zlib.Zip.OperatingSystem.UNIX, "Unix" : Zlib.Zip.OperatingSystem.UNIX,
"Macintosh" : Zlib.Zip.OperatingSystem.MACINTOSH "Macintosh" : Zlib.Zip.OperatingSystem.MACINTOSH
}, },
/** /**
* Zip operation. * Zip operation.
* *
@ -278,20 +278,20 @@ var Compress = {
}, },
}, },
zip = new Zlib.Zip(); zip = new Zlib.Zip();
if (password.length) if (password.length)
zip.setPassword(password); zip.setPassword(password);
zip.addFile(input, options); zip.addFile(input, options);
return Array.prototype.slice.call(zip.compress()); return Array.prototype.slice.call(zip.compress());
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
PKUNZIP_VERIFY: false, PKUNZIP_VERIFY: false,
/** /**
* Unzip operation. * Unzip operation.
* *
@ -308,9 +308,9 @@ var Compress = {
unzip = new Zlib.Unzip(input, options), unzip = new Zlib.Unzip(input, options),
filenames = unzip.getFilenames(), filenames = unzip.getFilenames(),
output = "<div style='padding: 5px;'>" + filenames.length + " file(s) found</div>\n"; output = "<div style='padding: 5px;'>" + filenames.length + " file(s) found</div>\n";
output += "<div class='panel-group' id='zip-accordion' role='tablist' aria-multiselectable='true'>"; output += "<div class='panel-group' id='zip-accordion' role='tablist' aria-multiselectable='true'>";
window.uzip = unzip; window.uzip = unzip;
for (var i = 0; i < filenames.length; i++) { for (var i = 0; i < filenames.length; i++) {
file = Utils.byteArrayToUtf8(unzip.decompress(filenames[i])); file = Utils.byteArrayToUtf8(unzip.decompress(filenames[i]));
@ -324,11 +324,11 @@ var Compress = {
"<div class='panel-body'>" + "<div class='panel-body'>" +
Utils.escapeHtml(file) + "</div></div></div>"; Utils.escapeHtml(file) + "</div></div></div>";
} }
return output + "</div>"; return output + "</div>";
}, },
/** /**
* Bzip2 Decompress operation. * Bzip2 Decompress operation.
* *
@ -340,10 +340,10 @@ var Compress = {
var compressed = new Uint8Array(input), var compressed = new Uint8Array(input),
bzip2Reader, bzip2Reader,
plain = ""; plain = "";
bzip2Reader = bzip2.array(compressed); bzip2Reader = bzip2.array(compressed);
plain = bzip2.simple(bzip2Reader); plain = bzip2.simple(bzip2Reader);
return plain; return plain;
}, },
}; };

View File

@ -10,13 +10,13 @@
* @namespace * @namespace
*/ */
var DateTime = { var DateTime = {
/** /**
* @constant * @constant
* @default * @default
*/ */
UNITS: ["Seconds (s)", "Milliseconds (ms)", "Microseconds (μs)", "Nanoseconds (ns)"], UNITS: ["Seconds (s)", "Milliseconds (ms)", "Microseconds (μs)", "Nanoseconds (ns)"],
/** /**
* From UNIX Timestamp operation. * From UNIX Timestamp operation.
* *
@ -27,9 +27,9 @@ var DateTime = {
runFromUnixTimestamp: function(input, args) { runFromUnixTimestamp: function(input, args) {
var units = args[0], var units = args[0],
d; d;
input = parseFloat(input); input = parseFloat(input);
if (units === "Seconds (s)") { if (units === "Seconds (s)") {
d = moment.unix(input); d = moment.unix(input);
return d.tz("UTC").format("ddd D MMMM YYYY HH:mm:ss") + " UTC"; return d.tz("UTC").format("ddd D MMMM YYYY HH:mm:ss") + " UTC";
@ -46,8 +46,8 @@ var DateTime = {
throw "Unrecognised unit"; throw "Unrecognised unit";
} }
}, },
/** /**
* To UNIX Timestamp operation. * To UNIX Timestamp operation.
* *
@ -58,7 +58,7 @@ var DateTime = {
runToUnixTimestamp: function(input, args) { runToUnixTimestamp: function(input, args) {
var units = args[0], var units = args[0],
d = moment(input); d = moment(input);
if (units === "Seconds (s)") { if (units === "Seconds (s)") {
return d.unix(); return d.unix();
} else if (units === "Milliseconds (ms)") { } else if (units === "Milliseconds (ms)") {
@ -71,8 +71,8 @@ var DateTime = {
throw "Unrecognised unit"; throw "Unrecognised unit";
} }
}, },
/** /**
* @constant * @constant
* @default * @default
@ -122,7 +122,7 @@ var DateTime = {
* @default * @default
*/ */
TIMEZONES: ["UTC"].concat(moment.tz.names()), TIMEZONES: ["UTC"].concat(moment.tz.names()),
/** /**
* Translate DateTime Format operation. * Translate DateTime Format operation.
* *
@ -140,14 +140,14 @@ var DateTime = {
try { try {
date = moment.tz(input, inputFormat, inputTimezone); date = moment.tz(input, inputFormat, inputTimezone);
if (!date || date.format() === "Invalid date") throw Error; if (!date || date.format() === "Invalid date") throw Error;
} catch(err) { } catch (err) {
return "Invalid format.\n\n" + DateTime.FORMAT_EXAMPLES; return "Invalid format.\n\n" + DateTime.FORMAT_EXAMPLES;
} }
return date.tz(outputTimezone).format(outputFormat); return date.tz(outputTimezone).format(outputFormat);
}, },
/** /**
* Parse DateTime operation. * Parse DateTime operation.
* *
@ -160,14 +160,14 @@ var DateTime = {
inputTimezone = args[2], inputTimezone = args[2],
date, date,
output = ""; output = "";
try { try {
date = moment.tz(input, inputFormat, inputTimezone); date = moment.tz(input, inputFormat, inputTimezone);
if (!date || date.format() === "Invalid date") throw Error; if (!date || date.format() === "Invalid date") throw Error;
} catch(err) { } catch (err) {
return "Invalid format.\n\n" + DateTime.FORMAT_EXAMPLES; return "Invalid format.\n\n" + DateTime.FORMAT_EXAMPLES;
} }
output += "Date: " + date.format("dddd Do MMMM YYYY") + output += "Date: " + date.format("dddd Do MMMM YYYY") +
"\nTime: " + date.format("HH:mm:ss") + "\nTime: " + date.format("HH:mm:ss") +
"\nPeriod: " + date.format("A") + "\nPeriod: " + date.format("A") +
@ -179,11 +179,11 @@ var DateTime = {
"\n\nDay of year: " + date.dayOfYear() + "\n\nDay of year: " + date.dayOfYear() +
"\nWeek number: " + date.weekYear() + "\nWeek number: " + date.weekYear() +
"\nQuarter: " + date.quarter(); "\nQuarter: " + date.quarter();
return output; return output;
}, },
/** /**
* @constant * @constant
*/ */
@ -450,5 +450,5 @@ var DateTime = {
</tbody>\ </tbody>\
</table>", </table>",
}; };

View File

@ -8,7 +8,7 @@
* @namespace * @namespace
*/ */
var Endian = { var Endian = {
/** /**
* @constant * @constant
* @default * @default
@ -24,7 +24,7 @@ var Endian = {
* @default * @default
*/ */
PAD_INCOMPLETE_WORDS: true, PAD_INCOMPLETE_WORDS: true,
/** /**
* Swap endianness operation. * Swap endianness operation.
* *
@ -41,11 +41,11 @@ var Endian = {
words = [], words = [],
i = 0, i = 0,
j = 0; j = 0;
if (wordLength <= 0) { if (wordLength <= 0) {
return "Word length must be greater than 0"; return "Word length must be greater than 0";
} }
// Convert input to raw data based on specified data format // Convert input to raw data based on specified data format
switch (dataFormat) { switch (dataFormat) {
case "Hex": case "Hex":
@ -57,21 +57,21 @@ var Endian = {
default: default:
data = input; data = input;
} }
// Split up into words // Split up into words
for (i = 0; i < data.length; i += wordLength) { for (i = 0; i < data.length; i += wordLength) {
var word = data.slice(i, i + wordLength); var word = data.slice(i, i + wordLength);
// Pad word if too short // Pad word if too short
if (padIncompleteWords && word.length < wordLength){ if (padIncompleteWords && word.length < wordLength){
for (j = word.length; j < wordLength; j++) { for (j = word.length; j < wordLength; j++) {
word.push(0); word.push(0);
} }
} }
words.push(word); words.push(word);
} }
// Swap endianness and flatten // Swap endianness and flatten
for (i = 0; i < words.length; i++) { for (i = 0; i < words.length; i++) {
j = words[i].length; j = words[i].length;
@ -79,7 +79,7 @@ var Endian = {
result.push(words[i][j]); result.push(words[i][j]);
} }
} }
// Convert data back to specified data format // Convert data back to specified data format
switch (dataFormat) { switch (dataFormat) {
case "Hex": case "Hex":
@ -90,5 +90,5 @@ var Endian = {
return result; return result;
} }
}, },
}; };

View File

@ -8,13 +8,13 @@
* @namespace * @namespace
*/ */
var Entropy = { var Entropy = {
/** /**
* @constant * @constant
* @default * @default
*/ */
CHUNK_SIZE: 1000, CHUNK_SIZE: 1000,
/** /**
* Entropy operation. * Entropy operation.
* *
@ -26,7 +26,7 @@ var Entropy = {
var chunkSize = args[0], var chunkSize = args[0],
output = "", output = "",
entropy = Entropy._calcEntropy(input); entropy = Entropy._calcEntropy(input);
output += "Shannon entropy: " + entropy + "\n" + output += "Shannon entropy: " + entropy + "\n" +
"<br><canvas id='chart-area'></canvas><br>\n" + "<br><canvas id='chart-area'></canvas><br>\n" +
"- 0 represents no randomness (i.e. all the bytes in the data have the same value) whereas 8, the maximum, represents a completely random string.\n" + "- 0 represents no randomness (i.e. all the bytes in the data have the same value) whereas 8, the maximum, represents a completely random string.\n" +
@ -54,7 +54,7 @@ var Entropy = {
}\ }\
]);\ ]);\
</script>"; </script>";
var chunkEntropy = 0; var chunkEntropy = 0;
if (chunkSize !== 0) { if (chunkSize !== 0) {
for (var i = 0; i < input.length; i += chunkSize) { for (var i = 0; i < input.length; i += chunkSize) {
@ -64,17 +64,17 @@ var Entropy = {
} else { } else {
output += "Chunk size cannot be 0."; output += "Chunk size cannot be 0.";
} }
return output; return output;
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
FREQ_ZEROS: false, FREQ_ZEROS: false,
/** /**
* Frequency distribution operation. * Frequency distribution operation.
* *
@ -84,29 +84,29 @@ var Entropy = {
*/ */
runFreqDistrib: function (input, args) { runFreqDistrib: function (input, args) {
if (!input.length) return "No data"; if (!input.length) return "No data";
var distrib = new Array(256), var distrib = new Array(256),
percentages = new Array(256), percentages = new Array(256),
len = input.length, len = input.length,
showZeroes = args[0]; showZeroes = args[0];
// Initialise distrib to 0 // Initialise distrib to 0
for (var i = 0; i < 256; i++) { for (var i = 0; i < 256; i++) {
distrib[i] = 0; distrib[i] = 0;
} }
// Count bytes // Count bytes
for (i = 0; i < len; i++) { for (i = 0; i < len; i++) {
distrib[input[i]]++; distrib[input[i]]++;
} }
// Calculate percentages // Calculate percentages
var repr = 0; var repr = 0;
for (i = 0; i < 256; i++) { for (i = 0; i < 256; i++) {
if (distrib[i] > 0) repr++; if (distrib[i] > 0) repr++;
percentages[i] = distrib[i] / len * 100; percentages[i] = distrib[i] / len * 100;
} }
// Print // Print
var output = "<canvas id='chart-area'></canvas><br>" + var output = "<canvas id='chart-area'></canvas><br>" +
"Total data length: " + len + "Total data length: " + len +
@ -123,7 +123,7 @@ var Entropy = {
\ \
CanvasComponents.drawBarChart(canvas, scores, 'Byte', 'Frequency %', 16, 6);\ CanvasComponents.drawBarChart(canvas, scores, 'Byte', 'Frequency %', 16, 6);\
</script>"; </script>";
for (i = 0; i < 256; i++) { for (i = 0; i < 256; i++) {
if (distrib[i] || showZeroes) { if (distrib[i] || showZeroes) {
output += " " + Utils.hex(i, 2) + " (" + output += " " + Utils.hex(i, 2) + " (" +
@ -131,11 +131,11 @@ var Entropy = {
Array(Math.ceil(percentages[i])+1).join("|") + "\n"; Array(Math.ceil(percentages[i])+1).join("|") + "\n";
} }
} }
return output; return output;
}, },
/** /**
* Calculates the Shannon entropy for a given chunk of data. * Calculates the Shannon entropy for a given chunk of data.
* *
@ -147,19 +147,19 @@ var Entropy = {
var prob = [], var prob = [],
uniques = data.unique(), uniques = data.unique(),
str = Utils.byteArrayToChars(data); str = Utils.byteArrayToChars(data);
for (var i = 0; i < uniques.length; i++) { for (var i = 0; i < uniques.length; i++) {
prob.push(str.count(Utils.chr(uniques[i])) / data.length); prob.push(str.count(Utils.chr(uniques[i])) / data.length);
} }
var entropy = 0, var entropy = 0,
p; p;
for (i = 0; i < prob.length; i++) { for (i = 0; i < prob.length; i++) {
p = prob[i]; p = prob[i];
entropy += p * Math.log(p) / Math.log(2); entropy += p * Math.log(p) / Math.log(2);
} }
return -entropy; return -entropy;
}, },

View File

@ -24,17 +24,17 @@ var Extract = {
var output = "", var output = "",
total = 0, total = 0,
match; match;
while ((match = searchRegex.exec(input))) { while ((match = searchRegex.exec(input))) {
if (removeRegex && removeRegex.test(match[0])) if (removeRegex && removeRegex.test(match[0]))
continue; continue;
total++; total++;
output += match[0] + "\n"; output += match[0] + "\n";
} }
if (includeTotal) if (includeTotal)
output = "Total found: " + total + "\n\n" + output; output = "Total found: " + total + "\n\n" + output;
return output; return output;
}, },
@ -49,7 +49,7 @@ var Extract = {
* @default * @default
*/ */
DISPLAY_TOTAL: false, DISPLAY_TOTAL: false,
/** /**
* Strings operation. * Strings operation.
* *
@ -62,11 +62,11 @@ var Extract = {
displayTotal = args[1], displayTotal = args[1],
strings = "[A-Z\\d/\\-:.,_$%'\"()<>= !\\[\\]{}@]", strings = "[A-Z\\d/\\-:.,_$%'\"()<>= !\\[\\]{}@]",
regex = new RegExp(strings + "{" + minLen + ",}", "ig"); regex = new RegExp(strings + "{" + minLen + ",}", "ig");
return Extract._search(input, regex, null, displayTotal); return Extract._search(input, regex, null, displayTotal);
}, },
/** /**
* @constant * @constant
* @default * @default
@ -82,7 +82,7 @@ var Extract = {
* @default * @default
*/ */
REMOVE_LOCAL: false, REMOVE_LOCAL: false,
/** /**
* Extract IP addresses operation. * Extract IP addresses operation.
* *
@ -98,7 +98,7 @@ var Extract = {
ipv4 = "(?:(?:\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d|\\d)(?:\\/\\d{1,2})?", ipv4 = "(?:(?:\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d|\\d)(?:\\/\\d{1,2})?",
ipv6 = "((?=.*::)(?!.*::.+::)(::)?([\\dA-F]{1,4}:(:|\\b)|){5}|([\\dA-F]{1,4}:){6})((([\\dA-F]{1,4}((?!\\3)::|:\\b|(?![\\dA-F])))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})", ipv6 = "((?=.*::)(?!.*::.+::)(::)?([\\dA-F]{1,4}:(:|\\b)|){5}|([\\dA-F]{1,4}:){6})((([\\dA-F]{1,4}((?!\\3)::|:\\b|(?![\\dA-F])))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})",
ips = ""; ips = "";
if (includeIpv4 && includeIpv6) { if (includeIpv4 && includeIpv6) {
ips = ipv4 + "|" + ipv6; ips = ipv4 + "|" + ipv6;
} else if (includeIpv4) { } else if (includeIpv4) {
@ -106,10 +106,10 @@ var Extract = {
} else if (includeIpv6) { } else if (includeIpv6) {
ips = ipv6; ips = ipv6;
} }
if (ips) { if (ips) {
var regex = new RegExp(ips, "ig"); var regex = new RegExp(ips, "ig");
if (removeLocal) { if (removeLocal) {
var ten = "10\\..+", var ten = "10\\..+",
oneninetwo = "192\\.168\\..+", oneninetwo = "192\\.168\\..+",
@ -117,7 +117,7 @@ var Extract = {
onetwoseven = "127\\..+", onetwoseven = "127\\..+",
removeRegex = new RegExp("^(?:" + ten + "|" + oneninetwo + removeRegex = new RegExp("^(?:" + ten + "|" + oneninetwo +
"|" + oneseventwo + "|" + onetwoseven + ")"); "|" + oneseventwo + "|" + onetwoseven + ")");
return Extract._search(input, regex, removeRegex, displayTotal); return Extract._search(input, regex, removeRegex, displayTotal);
} else { } else {
return Extract._search(input, regex, null, displayTotal); return Extract._search(input, regex, null, displayTotal);
@ -126,8 +126,8 @@ var Extract = {
return ""; return "";
} }
}, },
/** /**
* Extract email addresses operation. * Extract email addresses operation.
* *
@ -138,11 +138,11 @@ var Extract = {
runEmail: function(input, args) { runEmail: function(input, args) {
var displayTotal = args[0], var displayTotal = args[0],
regex = /\w[-.\w]*@[-\w]+(?:\.[-\w]+)*\.[A-Z]{2,4}/ig; regex = /\w[-.\w]*@[-\w]+(?:\.[-\w]+)*\.[A-Z]{2,4}/ig;
return Extract._search(input, regex, null, displayTotal); return Extract._search(input, regex, null, displayTotal);
}, },
/** /**
* Extract MAC addresses operation. * Extract MAC addresses operation.
* *
@ -153,11 +153,11 @@ var Extract = {
runMac: function(input, args) { runMac: function(input, args) {
var displayTotal = args[0], var displayTotal = args[0],
regex = /[A-F\d]{2}(?:[:-][A-F\d]{2}){5}/ig; regex = /[A-F\d]{2}(?:[:-][A-F\d]{2}){5}/ig;
return Extract._search(input, regex, null, displayTotal); return Extract._search(input, regex, null, displayTotal);
}, },
/** /**
* Extract URLs operation. * Extract URLs operation.
* *
@ -171,14 +171,14 @@ var Extract = {
hostname = "[-\\w]+(?:\\.\\w[-\\w]*)+", hostname = "[-\\w]+(?:\\.\\w[-\\w]*)+",
port = ":\\d+", port = ":\\d+",
path = "/[^.!,?;\"'<>()\\[\\]{}\\s\\x7F-\\xFF]*"; path = "/[^.!,?;\"'<>()\\[\\]{}\\s\\x7F-\\xFF]*";
path += "(?:[.!,?]+[^.!,?;\"'<>()\\[\\]{}\\s\\x7F-\\xFF]+)*"; path += "(?:[.!,?]+[^.!,?;\"'<>()\\[\\]{}\\s\\x7F-\\xFF]+)*";
var regex = new RegExp(protocol + hostname + "(?:" + port + var regex = new RegExp(protocol + hostname + "(?:" + port +
")?(?:" + path + ")?", "ig"); ")?(?:" + path + ")?", "ig");
return Extract._search(input, regex, null, displayTotal); return Extract._search(input, regex, null, displayTotal);
}, },
/** /**
* Extract domains operation. * Extract domains operation.
* *
@ -192,11 +192,11 @@ var Extract = {
hostname = "[-\\w\\.]+", hostname = "[-\\w\\.]+",
tld = "\\.(?:com|net|org|biz|info|co|uk|onion|int|mobi|name|edu|gov|mil|eu|ac|ae|af|de|ca|ch|cn|cy|es|gb|hk|il|in|io|tv|me|nl|no|nz|ro|ru|tr|us|az|ir|kz|uz|pk)+", tld = "\\.(?:com|net|org|biz|info|co|uk|onion|int|mobi|name|edu|gov|mil|eu|ac|ae|af|de|ca|ch|cn|cy|es|gb|hk|il|in|io|tv|me|nl|no|nz|ro|ru|tr|us|az|ir|kz|uz|pk)+",
regex = new RegExp("(?:" + protocol + ")?" + hostname + tld, "ig"); regex = new RegExp("(?:" + protocol + ")?" + hostname + tld, "ig");
return Extract._search(input, regex, null, displayTotal); return Extract._search(input, regex, null, displayTotal);
}, },
/** /**
* @constant * @constant
* @default * @default
@ -207,7 +207,7 @@ var Extract = {
* @default * @default
*/ */
INCLUDE_UNIX_PATH: true, INCLUDE_UNIX_PATH: true,
/** /**
* Extract file paths operation. * Extract file paths operation.
* *
@ -226,7 +226,7 @@ var Extract = {
"(?:\\." + winExt + ")?", "(?:\\." + winExt + ")?",
unixPath = "(?:/[A-Z\\d.][A-Z\\d\\-.]{0,61})+", unixPath = "(?:/[A-Z\\d.][A-Z\\d\\-.]{0,61})+",
filePaths = ""; filePaths = "";
if (includeWinPath && includeUnixPath) { if (includeWinPath && includeUnixPath) {
filePaths = winPath + "|" + unixPath; filePaths = winPath + "|" + unixPath;
} else if (includeWinPath) { } else if (includeWinPath) {
@ -234,7 +234,7 @@ var Extract = {
} else if (includeUnixPath) { } else if (includeUnixPath) {
filePaths = unixPath; filePaths = unixPath;
} }
if (filePaths) { if (filePaths) {
var regex = new RegExp(filePaths, "ig"); var regex = new RegExp(filePaths, "ig");
return Extract._search(input, regex, null, displayTotal); return Extract._search(input, regex, null, displayTotal);
@ -242,8 +242,8 @@ var Extract = {
return ""; return "";
} }
}, },
/** /**
* Extract dates operation. * Extract dates operation.
* *
@ -257,11 +257,11 @@ var Extract = {
date2 = "(?:0[1-9]|[12][0-9]|3[01])[- /.](?:0[1-9]|1[012])[- /.](?:19|20)\\d\\d", // dd/mm/yyyy date2 = "(?:0[1-9]|[12][0-9]|3[01])[- /.](?:0[1-9]|1[012])[- /.](?:19|20)\\d\\d", // dd/mm/yyyy
date3 = "(?:0[1-9]|1[012])[- /.](?:0[1-9]|[12][0-9]|3[01])[- /.](?:19|20)\\d\\d", // mm/dd/yyyy date3 = "(?:0[1-9]|1[012])[- /.](?:0[1-9]|[12][0-9]|3[01])[- /.](?:19|20)\\d\\d", // mm/dd/yyyy
regex = new RegExp(date1 + "|" + date2 + "|" + date3, "ig"); regex = new RegExp(date1 + "|" + date2 + "|" + date3, "ig");
return Extract._search(input, regex, null, displayTotal); return Extract._search(input, regex, null, displayTotal);
}, },
/** /**
* Extract all identifiers operation. * Extract all identifiers operation.
* *
@ -273,22 +273,22 @@ var Extract = {
var output = ""; var output = "";
output += "IP addresses\n"; output += "IP addresses\n";
output += Extract.runIp(input, [true, true, false]); output += Extract.runIp(input, [true, true, false]);
output += "\nEmail addresses\n"; output += "\nEmail addresses\n";
output += Extract.runEmail(input, []); output += Extract.runEmail(input, []);
output += "\nMAC addresses\n"; output += "\nMAC addresses\n";
output += Extract.runMac(input, []); output += Extract.runMac(input, []);
output += "\nURLs\n"; output += "\nURLs\n";
output += Extract.runUrls(input, []); output += Extract.runUrls(input, []);
output += "\nDomain names\n"; output += "\nDomain names\n";
output += Extract.runDomains(input, []); output += Extract.runDomains(input, []);
output += "\nFile paths\n"; output += "\nFile paths\n";
output += Extract.runFilePaths(input, [true, true]); output += Extract.runFilePaths(input, [true, true]);
output += "\nDates\n"; output += "\nDates\n";
output += Extract.runDates(input, []); output += Extract.runDates(input, []);
return output; return output;

View File

@ -243,7 +243,6 @@ var HTML = {
}, },
/** /**
* Converts an HSL color value to RGB. Conversion formula * Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_colorSpace. * adapted from http://en.wikipedia.org/wiki/HSL_colorSpace.
@ -309,7 +308,7 @@ var HTML = {
} else { } else {
var d = max - min; var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min); s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max) { switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break; case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break; case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break; case b: h = (r - g) / d + 4; break;

View File

@ -10,7 +10,7 @@
* @namespace * @namespace
*/ */
var HTTP = { var HTTP = {
/** /**
* Strip HTTP headers operation. * Strip HTTP headers operation.
* *
@ -21,11 +21,11 @@ var HTTP = {
runStripHeaders: function(input, args) { runStripHeaders: function(input, args) {
var headerEnd = input.indexOf("\r\n\r\n") + var headerEnd = input.indexOf("\r\n\r\n") +
(headerEnd < 0) ? input.indexOf("\n\n") + 2 : headerEnd + 4; (headerEnd < 0) ? input.indexOf("\n\n") + 2 : headerEnd + 4;
return (headerEnd < 2) ? input : input.slice(headerEnd, input.length); return (headerEnd < 2) ? input : input.slice(headerEnd, input.length);
}, },
/** /**
* Parse User Agent operation. * Parse User Agent operation.
* *
@ -35,7 +35,7 @@ var HTTP = {
*/ */
runParseUserAgent: function(input, args) { runParseUserAgent: function(input, args) {
var ua = UAS_parser.parse(input); // eslint-disable-line camelcase var ua = UAS_parser.parse(input); // eslint-disable-line camelcase
return "Type: " + ua.type + "\n" + return "Type: " + ua.type + "\n" +
"Family: " + ua.uaFamily + "\n" + "Family: " + ua.uaFamily + "\n" +
"Name: " + ua.uaName + "\n" + "Name: " + ua.uaName + "\n" +

View File

@ -34,7 +34,7 @@ var Hash = {
return Utils.toHexFast(CryptoApi.hash("md4", input, {})); return Utils.toHexFast(CryptoApi.hash("md4", input, {}));
}, },
/** /**
* MD5 operation. * MD5 operation.
* *
@ -58,8 +58,8 @@ var Hash = {
runSHA0: function (input, args) { runSHA0: function (input, args) {
return Utils.toHexFast(CryptoApi.hash("sha0", input, {})); return Utils.toHexFast(CryptoApi.hash("sha0", input, {}));
}, },
/** /**
* SHA1 operation. * SHA1 operation.
* *
@ -72,7 +72,7 @@ var Hash = {
return CryptoJS.SHA1(input).toString(CryptoJS.enc.Hex); return CryptoJS.SHA1(input).toString(CryptoJS.enc.Hex);
}, },
/** /**
* SHA224 operation. * SHA224 operation.
* *
@ -84,8 +84,8 @@ var Hash = {
input = CryptoJS.enc.Latin1.parse(input); input = CryptoJS.enc.Latin1.parse(input);
return CryptoJS.SHA224(input).toString(CryptoJS.enc.Hex); return CryptoJS.SHA224(input).toString(CryptoJS.enc.Hex);
}, },
/** /**
* SHA256 operation. * SHA256 operation.
* *
@ -97,8 +97,8 @@ var Hash = {
input = CryptoJS.enc.Latin1.parse(input); input = CryptoJS.enc.Latin1.parse(input);
return CryptoJS.SHA256(input).toString(CryptoJS.enc.Hex); return CryptoJS.SHA256(input).toString(CryptoJS.enc.Hex);
}, },
/** /**
* SHA384 operation. * SHA384 operation.
* *
@ -110,8 +110,8 @@ var Hash = {
input = CryptoJS.enc.Latin1.parse(input); input = CryptoJS.enc.Latin1.parse(input);
return CryptoJS.SHA384(input).toString(CryptoJS.enc.Hex); return CryptoJS.SHA384(input).toString(CryptoJS.enc.Hex);
}, },
/** /**
* SHA512 operation. * SHA512 operation.
* *
@ -123,14 +123,14 @@ var Hash = {
input = CryptoJS.enc.Latin1.parse(input); input = CryptoJS.enc.Latin1.parse(input);
return CryptoJS.SHA512(input).toString(CryptoJS.enc.Hex); return CryptoJS.SHA512(input).toString(CryptoJS.enc.Hex);
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
SHA3_LENGTH: ["512", "384", "256", "224"], SHA3_LENGTH: ["512", "384", "256", "224"],
/** /**
* SHA3 operation. * SHA3 operation.
* *
@ -146,8 +146,8 @@ var Hash = {
}; };
return CryptoJS.SHA3(input, options).toString(CryptoJS.enc.Hex); return CryptoJS.SHA3(input, options).toString(CryptoJS.enc.Hex);
}, },
/** /**
* RIPEMD-160 operation. * RIPEMD-160 operation.
* *
@ -160,13 +160,13 @@ var Hash = {
return CryptoJS.RIPEMD160(input).toString(CryptoJS.enc.Hex); return CryptoJS.RIPEMD160(input).toString(CryptoJS.enc.Hex);
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
HMAC_FUNCTIONS: ["MD5", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3", "RIPEMD-160"], HMAC_FUNCTIONS: ["MD5", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3", "RIPEMD-160"],
/** /**
* HMAC operation. * HMAC operation.
* *
@ -189,8 +189,8 @@ var Hash = {
}; };
return execute[hashFunc].toString(CryptoJS.enc.Hex); return execute[hashFunc].toString(CryptoJS.enc.Hex);
}, },
/** /**
* Generate all hashes operation. * Generate all hashes operation.
* *
@ -221,11 +221,11 @@ var Hash = {
"\nFletcher-64: " + Checksum.runFletcher64(byteArray, []) + "\nFletcher-64: " + Checksum.runFletcher64(byteArray, []) +
"\nAdler-32: " + Checksum.runAdler32(byteArray, []) + "\nAdler-32: " + Checksum.runAdler32(byteArray, []) +
"\nCRC-32: " + Checksum.runCRC32(byteArray, []); "\nCRC-32: " + Checksum.runCRC32(byteArray, []);
return output; return output;
}, },
/** /**
* Analyse hash operation. * Analyse hash operation.
* *
@ -235,21 +235,21 @@ var Hash = {
*/ */
runAnalyse: function(input, args) { runAnalyse: function(input, args) {
input = input.replace(/\s/g, ""); input = input.replace(/\s/g, "");
var output = "", var output = "",
byteLength = input.length / 2, byteLength = input.length / 2,
bitLength = byteLength * 8, bitLength = byteLength * 8,
possibleHashFunctions = []; possibleHashFunctions = [];
if (!/^[a-f0-9]+$/i.test(input)) { if (!/^[a-f0-9]+$/i.test(input)) {
return "Invalid hash"; return "Invalid hash";
} }
output += "Hash length: " + input.length + "\n" + output += "Hash length: " + input.length + "\n" +
"Byte length: " + byteLength + "\n" + "Byte length: " + byteLength + "\n" +
"Bit length: " + bitLength + "\n\n" + "Bit length: " + bitLength + "\n\n" +
"Based on the length, this hash could have been generated by one of the following hashing functions:\n"; "Based on the length, this hash could have been generated by one of the following hashing functions:\n";
switch (bitLength) { switch (bitLength) {
case 4: case 4:
possibleHashFunctions = [ possibleHashFunctions = [
@ -376,8 +376,8 @@ var Hash = {
]; ];
break; break;
} }
return output + possibleHashFunctions.join("\n"); return output + possibleHashFunctions.join("\n");
}, },
}; };

View File

@ -26,7 +26,7 @@ var Hexdump = {
* @default * @default
*/ */
INCLUDE_FINAL_LENGTH: false, INCLUDE_FINAL_LENGTH: false,
/** /**
* To Hexdump operation. * To Hexdump operation.
* *
@ -38,7 +38,7 @@ var Hexdump = {
var length = args[0] || Hexdump.WIDTH; var length = args[0] || Hexdump.WIDTH;
var upperCase = args[1]; var upperCase = args[1];
var includeFinalLength = args[2]; var includeFinalLength = args[2];
var output = "", padding = 2; var output = "", padding = 2;
for (var i = 0; i < input.length; i += length) { for (var i = 0; i < input.length; i += length) {
var buff = input.slice(i, i+length); var buff = input.slice(i, i+length);
@ -46,27 +46,27 @@ var Hexdump = {
for (var j = 0; j < buff.length; j++) { for (var j = 0; j < buff.length; j++) {
hexa += Utils.hex(buff[j], padding) + " "; hexa += Utils.hex(buff[j], padding) + " ";
} }
var lineNo = Utils.hex(i, 8); var lineNo = Utils.hex(i, 8);
if (upperCase) { if (upperCase) {
hexa = hexa.toUpperCase(); hexa = hexa.toUpperCase();
lineNo = lineNo.toUpperCase(); lineNo = lineNo.toUpperCase();
} }
output += lineNo + " " + output += lineNo + " " +
Utils.padRight(hexa, (length*(padding+1))) + Utils.padRight(hexa, (length*(padding+1))) +
" |" + Utils.padRight(Utils.printable(Utils.byteArrayToChars(buff)), buff.length) + "|\n"; " |" + Utils.padRight(Utils.printable(Utils.byteArrayToChars(buff)), buff.length) + "|\n";
if (includeFinalLength && i+buff.length === input.length) { if (includeFinalLength && i+buff.length === input.length) {
output += Utils.hex(i+buff.length, 8) + "\n"; output += Utils.hex(i+buff.length, 8) + "\n";
} }
} }
return output.slice(0, -1); return output.slice(0, -1);
}, },
/** /**
* From Hexdump operation. * From Hexdump operation.
* *
@ -78,7 +78,7 @@ var Hexdump = {
var output = [], var output = [],
regex = /^\s*(?:[\dA-F]{4,16}:?)?\s*((?:[\dA-F]{2}\s){1,8}(?:\s|[\dA-F]{2}-)(?:[\dA-F]{2}\s){1,8}|(?:[\dA-F]{2}\s|[\dA-F]{4}\s)+)/igm, regex = /^\s*(?:[\dA-F]{4,16}:?)?\s*((?:[\dA-F]{2}\s){1,8}(?:\s|[\dA-F]{2}-)(?:[\dA-F]{2}\s){1,8}|(?:[\dA-F]{2}\s|[\dA-F]{4}\s)+)/igm,
block, line; block, line;
while ((block = regex.exec(input))) { while ((block = regex.exec(input))) {
line = Utils.fromHex(block[1].replace(/-/g, " ")); line = Utils.fromHex(block[1].replace(/-/g, " "));
for (var i = 0; i < line.length; i++) { for (var i = 0; i < line.length; i++) {
@ -94,8 +94,8 @@ var Hexdump = {
} }
return output; return output;
}, },
/** /**
* Highlight to hexdump * Highlight to hexdump
* *
@ -113,9 +113,9 @@ var Hexdump = {
offset = pos[0].start % w, offset = pos[0].start % w,
start = 0, start = 0,
end = 0; end = 0;
pos[0].start = line*width + 10 + offset*3; pos[0].start = line*width + 10 + offset*3;
line = Math.floor(pos[0].end / w); line = Math.floor(pos[0].end / w);
offset = pos[0].end % w; offset = pos[0].end % w;
if (offset === 0) { if (offset === 0) {
@ -123,11 +123,11 @@ var Hexdump = {
offset = w; offset = w;
} }
pos[0].end = line*width + 10 + offset*3 - 1; pos[0].end = line*width + 10 + offset*3 - 1;
// Set up multiple selections for bytes // Set up multiple selections for bytes
var startLineNum = Math.floor(pos[0].start / width); var startLineNum = Math.floor(pos[0].start / width);
var endLineNum = Math.floor(pos[0].end / width); var endLineNum = Math.floor(pos[0].end / width);
if (startLineNum === endLineNum) { if (startLineNum === endLineNum) {
pos.push(pos[0]); pos.push(pos[0]);
} else { } else {
@ -142,7 +142,7 @@ var Hexdump = {
pos.push({ start: start, end: end }); pos.push({ start: start, end: end });
} }
} }
// Set up multiple selections for ASCII // Set up multiple selections for ASCII
var len = pos.length, lineNum = 0; var len = pos.length, lineNum = 0;
start = 0; start = 0;
@ -155,8 +155,8 @@ var Hexdump = {
} }
return pos; return pos;
}, },
/** /**
* Highlight from hexdump * Highlight from hexdump
* *
@ -169,10 +169,10 @@ var Hexdump = {
highlightFrom: function(pos, args) { highlightFrom: function(pos, args) {
var w = args[0] || 16; var w = args[0] || 16;
var width = 14 + (w*4); var width = 14 + (w*4);
var line = Math.floor(pos[0].start / width); var line = Math.floor(pos[0].start / width);
var offset = pos[0].start % width; var offset = pos[0].start % width;
if (offset < 10) { // In line number section if (offset < 10) { // In line number section
pos[0].start = line*w; pos[0].start = line*w;
} else if (offset > 10+(w*3)) { // In ASCII section } else if (offset > 10+(w*3)) { // In ASCII section
@ -180,10 +180,10 @@ var Hexdump = {
} else { // In byte section } else { // In byte section
pos[0].start = line*w + Math.floor((offset-10)/3); pos[0].start = line*w + Math.floor((offset-10)/3);
} }
line = Math.floor(pos[0].end / width); line = Math.floor(pos[0].end / width);
offset = pos[0].end % width; offset = pos[0].end % width;
if (offset < 10) { // In line number section if (offset < 10) { // In line number section
pos[0].end = line*w; pos[0].end = line*w;
} else if (offset > 10+(w*3)) { // In ASCII section } else if (offset > 10+(w*3)) { // In ASCII section
@ -191,8 +191,8 @@ var Hexdump = {
} else { // In byte section } else { // In byte section
pos[0].end = line*w + Math.ceil((offset-10)/3); pos[0].end = line*w + Math.ceil((offset-10)/3);
} }
return pos; return pos;
}, },
}; };

View File

@ -26,7 +26,7 @@ var IP = {
* @default * @default
*/ */
ALLOW_LARGE_LIST: false, ALLOW_LARGE_LIST: false,
/** /**
* Parse IP range operation. * Parse IP range operation.
* *
@ -38,14 +38,14 @@ var IP = {
var includeNetworkInfo = args[0], var includeNetworkInfo = args[0],
enumerateAddresses = args[1], enumerateAddresses = args[1],
allowLargeList = args[2]; allowLargeList = args[2];
// Check what type of input we are looking at // Check what type of input we are looking at
var ipv4CidrRegex = /^\s*((?:\d{1,3}\.){3}\d{1,3})\/(\d\d?)\s*$/, var ipv4CidrRegex = /^\s*((?:\d{1,3}\.){3}\d{1,3})\/(\d\d?)\s*$/,
ipv4RangeRegex = /^\s*((?:\d{1,3}\.){3}\d{1,3})\s*-\s*((?:\d{1,3}\.){3}\d{1,3})\s*$/, ipv4RangeRegex = /^\s*((?:\d{1,3}\.){3}\d{1,3})\s*-\s*((?:\d{1,3}\.){3}\d{1,3})\s*$/,
ipv6CidrRegex = /^\s*(((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\4)::|:\b|(?![\dA-F])))|(?!\3\4)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\/(\d\d?\d?)\s*$/i, ipv6CidrRegex = /^\s*(((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\4)::|:\b|(?![\dA-F])))|(?!\3\4)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\/(\d\d?\d?)\s*$/i,
ipv6RangeRegex = /^\s*(((?=.*::)(?!.*::[^-]+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\4)::|:\b|(?![\dA-F])))|(?!\3\4)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\s*-\s*(((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\17)::|:\b|(?![\dA-F])))|(?!\16\17)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\s*$/i, ipv6RangeRegex = /^\s*(((?=.*::)(?!.*::[^-]+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\4)::|:\b|(?![\dA-F])))|(?!\3\4)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\s*-\s*(((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\17)::|:\b|(?![\dA-F])))|(?!\16\17)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\s*$/i,
match; match;
if ((match = ipv4CidrRegex.exec(input))) { if ((match = ipv4CidrRegex.exec(input))) {
return IP._ipv4CidrRange(match, includeNetworkInfo, enumerateAddresses, allowLargeList); return IP._ipv4CidrRange(match, includeNetworkInfo, enumerateAddresses, allowLargeList);
} else if ((match = ipv4RangeRegex.exec(input))) { } else if ((match = ipv4RangeRegex.exec(input))) {
@ -58,8 +58,8 @@ var IP = {
return "Invalid input.\n\nEnter either a CIDR range (e.g. 10.0.0.0/24) or a hyphenated range (e.g. 10.0.0.0 - 10.0.1.0). IPv6 also supported."; return "Invalid input.\n\nEnter either a CIDR range (e.g. 10.0.0.0/24) or a hyphenated range (e.g. 10.0.0.0 - 10.0.1.0). IPv6 also supported.";
} }
}, },
/** /**
* @constant * @constant
* @default * @default
@ -70,7 +70,7 @@ var IP = {
* @default * @default
*/ */
IPV6_REGEX: /^\s*(((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\4)::|:\b|(?![\dA-F])))|(?!\3\4)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\s*$/i, IPV6_REGEX: /^\s*(((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\4)::|:\b|(?![\dA-F])))|(?!\3\4)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\s*$/i,
/** /**
* Parse IPv6 address operation. * Parse IPv6 address operation.
* *
@ -81,14 +81,14 @@ var IP = {
runParseIpv6: function (input, args) { runParseIpv6: function (input, args) {
var match, var match,
output = ""; output = "";
if ((match = IP.IPV6_REGEX.exec(input))) { if ((match = IP.IPV6_REGEX.exec(input))) {
var ipv6 = IP._strToIpv6(match[1]), var ipv6 = IP._strToIpv6(match[1]),
longhand = IP._ipv6ToStr(ipv6), longhand = IP._ipv6ToStr(ipv6),
shorthand = IP._ipv6ToStr(ipv6, true); shorthand = IP._ipv6ToStr(ipv6, true);
output += "Longhand: " + longhand + "\nShorthand: " + shorthand + "\n"; output += "Longhand: " + longhand + "\nShorthand: " + shorthand + "\n";
// Detect reserved addresses // Detect reserved addresses
if (shorthand === "::") { if (shorthand === "::") {
// Unspecified address // Unspecified address
@ -131,34 +131,34 @@ var IP = {
flagRandom1 = (ipv6[4] >>> 10) & 15, flagRandom1 = (ipv6[4] >>> 10) & 15,
flagUg = (ipv6[4] >>> 8) & 3, flagUg = (ipv6[4] >>> 8) & 3,
flagRandom2 = ipv6[4] & 255; flagRandom2 = ipv6[4] & 255;
output += "\nServer IPv4 address: " + IP._ipv4ToStr(serverIpv4) + output += "\nServer IPv4 address: " + IP._ipv4ToStr(serverIpv4) +
"\nClient IPv4 address: " + IP._ipv4ToStr(clientIpv4) + "\nClient IPv4 address: " + IP._ipv4ToStr(clientIpv4) +
"\nClient UDP port: " + udpPort + "\nClient UDP port: " + udpPort +
"\nFlags:" + "\nFlags:" +
"\n\tCone: " + flagCone; "\n\tCone: " + flagCone;
if (flagCone) { if (flagCone) {
output += " (Client is behind a cone NAT)"; output += " (Client is behind a cone NAT)";
} else { } else {
output += " (Client is not behind a cone NAT)"; output += " (Client is not behind a cone NAT)";
} }
output += "\n\tR: " + flagR; output += "\n\tR: " + flagR;
if (flagR) { if (flagR) {
output += " Error: This flag should be set to 0. See RFC 5991 and RFC 4380."; output += " Error: This flag should be set to 0. See RFC 5991 and RFC 4380.";
} }
output += "\n\tRandom1: " + Utils.bin(flagRandom1, 4) + output += "\n\tRandom1: " + Utils.bin(flagRandom1, 4) +
"\n\tUG: " + Utils.bin(flagUg, 2); "\n\tUG: " + Utils.bin(flagUg, 2);
if (flagUg) { if (flagUg) {
output += " Error: This flag should be set to 00. See RFC 4380."; output += " Error: This flag should be set to 00. See RFC 4380.";
} }
output += "\n\tRandom2: " + Utils.bin(flagRandom2, 8); output += "\n\tRandom2: " + Utils.bin(flagRandom2, 8);
if (!flagR && !flagUg && flagRandom1 && flagRandom2) { if (!flagR && !flagUg && flagRandom1 && flagRandom2) {
output += "\n\nThis is a valid Teredo address which complies with RFC 4380 and RFC 5991."; output += "\n\nThis is a valid Teredo address which complies with RFC 4380 and RFC 5991.";
} else if (!flagR && !flagUg) { } else if (!flagR && !flagUg) {
@ -186,12 +186,12 @@ var IP = {
// 6to4 // 6to4
output += "\n6to4 transition IPv6 address detected. See RFC 3056 for more details." + output += "\n6to4 transition IPv6 address detected. See RFC 3056 for more details." +
"\n6to4 prefix range: 2002::/16"; "\n6to4 prefix range: 2002::/16";
var v4Addr = IP._ipv4ToStr((ipv6[1] << 16) + ipv6[2]), var v4Addr = IP._ipv4ToStr((ipv6[1] << 16) + ipv6[2]),
slaId = ipv6[3], slaId = ipv6[3],
interfaceIdStr = ipv6[4].toString(16) + ipv6[5].toString(16) + ipv6[6].toString(16) + ipv6[7].toString(16), interfaceIdStr = ipv6[4].toString(16) + ipv6[5].toString(16) + ipv6[6].toString(16) + ipv6[7].toString(16),
interfaceId = new BigInteger(interfaceIdStr, 16); interfaceId = new BigInteger(interfaceIdStr, 16);
output += "\n\nEncapsulated IPv4 address: " + v4Addr + output += "\n\nEncapsulated IPv4 address: " + v4Addr +
"\nSLA ID: " + slaId + "\nSLA ID: " + slaId +
"\nInterface ID (base 16): " + interfaceIdStr + "\nInterface ID (base 16): " + interfaceIdStr +
@ -214,14 +214,14 @@ var IP = {
} }
return output; return output;
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
IP_FORMAT_LIST: ["Dotted Decimal", "Decimal", "Hex"], IP_FORMAT_LIST: ["Dotted Decimal", "Decimal", "Hex"],
/** /**
* Change IP format operation. * Change IP format operation.
* *
@ -235,17 +235,17 @@ var IP = {
lines = input.split("\n"), lines = input.split("\n"),
output = "", output = "",
j = 0; j = 0;
for (var i = 0; i < lines.length; i++) { for (var i = 0; i < lines.length; i++) {
if (lines[i] === "") continue; if (lines[i] === "") continue;
var baIp = []; var baIp = [];
if (inFormat === outFormat) { if (inFormat === outFormat) {
output += lines[i] + "\n"; output += lines[i] + "\n";
continue; continue;
} }
// Convert to byte array IP from input format // Convert to byte array IP from input format
switch (inFormat) { switch (inFormat) {
case "Dotted Decimal": case "Dotted Decimal":
@ -267,7 +267,7 @@ var IP = {
default: default:
throw "Unsupported input IP format"; throw "Unsupported input IP format";
} }
// Convert byte array IP to output format // Convert byte array IP to output format
switch (outFormat) { switch (outFormat) {
case "Dotted Decimal": case "Dotted Decimal":
@ -292,11 +292,11 @@ var IP = {
throw "Unsupported output IP format"; throw "Unsupported output IP format";
} }
} }
return output.slice(0, output.length-1); return output.slice(0, output.length-1);
}, },
/** /**
* @constant * @constant
* @default * @default
@ -312,7 +312,7 @@ var IP = {
* @default * @default
*/ */
GROUP_ONLY_SUBNET: false, GROUP_ONLY_SUBNET: false,
/** /**
* Group IP addresses operation. * Group IP addresses operation.
* *
@ -334,17 +334,17 @@ var IP = {
ip = null, ip = null,
network = null, network = null,
networkStr = ""; networkStr = "";
if (cidr < 0 || cidr > 127) { if (cidr < 0 || cidr > 127) {
return "CIDR must be less than 32 for IPv4 or 128 for IPv6"; return "CIDR must be less than 32 for IPv4 or 128 for IPv6";
} }
// Parse all IPs and add to network dictionary // Parse all IPs and add to network dictionary
for (var i = 0; i < ips.length; i++) { for (var i = 0; i < ips.length; i++) {
if ((match = IP.IPV4_REGEX.exec(ips[i]))) { if ((match = IP.IPV4_REGEX.exec(ips[i]))) {
ip = IP._strToIpv4(match[1]) >>> 0; ip = IP._strToIpv4(match[1]) >>> 0;
network = ip & ipv4Mask; network = ip & ipv4Mask;
if (ipv4Networks.hasOwnProperty(network)) { if (ipv4Networks.hasOwnProperty(network)) {
ipv4Networks[network].push(ip); ipv4Networks[network].push(ip);
} else { } else {
@ -354,13 +354,13 @@ var IP = {
ip = IP._strToIpv6(match[1]); ip = IP._strToIpv6(match[1]);
network = []; network = [];
networkStr = ""; networkStr = "";
for (var j = 0; j < 8; j++) { for (var j = 0; j < 8; j++) {
network.push(ip[j] & ipv6Mask[j]); network.push(ip[j] & ipv6Mask[j]);
} }
networkStr = IP._ipv6ToStr(network, true); networkStr = IP._ipv6ToStr(network, true);
if (ipv6Networks.hasOwnProperty(networkStr)) { if (ipv6Networks.hasOwnProperty(networkStr)) {
ipv6Networks[networkStr].push(ip); ipv6Networks[networkStr].push(ip);
} else { } else {
@ -368,13 +368,13 @@ var IP = {
} }
} }
} }
// Sort IPv4 network dictionaries and print // Sort IPv4 network dictionaries and print
for (network in ipv4Networks) { for (network in ipv4Networks) {
ipv4Networks[network] = ipv4Networks[network].sort(); ipv4Networks[network] = ipv4Networks[network].sort();
output += IP._ipv4ToStr(network) + "/" + cidr + "\n"; output += IP._ipv4ToStr(network) + "/" + cidr + "\n";
if (!onlySubnets) { if (!onlySubnets) {
for (i = 0; i < ipv4Networks[network].length; i++) { for (i = 0; i < ipv4Networks[network].length; i++) {
output += " " + IP._ipv4ToStr(ipv4Networks[network][i]) + "\n"; output += " " + IP._ipv4ToStr(ipv4Networks[network][i]) + "\n";
@ -382,13 +382,13 @@ var IP = {
output += "\n"; output += "\n";
} }
} }
// Sort IPv6 network dictionaries and print // Sort IPv6 network dictionaries and print
for (networkStr in ipv6Networks) { for (networkStr in ipv6Networks) {
//ipv6Networks[networkStr] = ipv6Networks[networkStr].sort(); TODO //ipv6Networks[networkStr] = ipv6Networks[networkStr].sort(); TODO
output += networkStr + "/" + cidr + "\n"; output += networkStr + "/" + cidr + "\n";
if (!onlySubnets) { if (!onlySubnets) {
for (i = 0; i < ipv6Networks[networkStr].length; i++) { for (i = 0; i < ipv6Networks[networkStr].length; i++) {
output += " " + IP._ipv6ToStr(ipv6Networks[networkStr][i], true) + "\n"; output += " " + IP._ipv6ToStr(ipv6Networks[networkStr][i], true) + "\n";
@ -399,15 +399,15 @@ var IP = {
return output; return output;
}, },
/** /**
* @constant * @constant
* @default * @default
* @private * @private
*/ */
_LARGE_RANGE_ERROR: "The specified range contains more than 65,536 addresses. Running this query could crash your browser. If you want to run it, select the \"Allow large queries\" option. You are advised to turn off \"Auto Bake\" whilst editing large ranges.", _LARGE_RANGE_ERROR: "The specified range contains more than 65,536 addresses. Running this query could crash your browser. If you want to run it, select the \"Allow large queries\" option. You are advised to turn off \"Auto Bake\" whilst editing large ranges.",
/** /**
* Parses an IPv4 CIDR range (e.g. 192.168.0.0/24) and displays information about it. * Parses an IPv4 CIDR range (e.g. 192.168.0.0/24) and displays information about it.
* *
@ -422,15 +422,15 @@ var IP = {
var output = "", var output = "",
network = IP._strToIpv4(cidr[1]), network = IP._strToIpv4(cidr[1]),
cidrRange = parseInt(cidr[2], 10); cidrRange = parseInt(cidr[2], 10);
if (cidrRange < 0 || cidrRange > 31) { if (cidrRange < 0 || cidrRange > 31) {
return "IPv4 CIDR must be less than 32"; return "IPv4 CIDR must be less than 32";
} }
var mask = ~(0xFFFFFFFF >>> cidrRange), var mask = ~(0xFFFFFFFF >>> cidrRange),
ip1 = network & mask, ip1 = network & mask,
ip2 = ip1 | ~mask; ip2 = ip1 | ~mask;
if (includeNetworkInfo) { if (includeNetworkInfo) {
output += "Network: " + IP._ipv4ToStr(network) + "\n"; output += "Network: " + IP._ipv4ToStr(network) + "\n";
output += "CIDR: " + cidrRange + "\n"; output += "CIDR: " + cidrRange + "\n";
@ -438,7 +438,7 @@ var IP = {
output += "Range: " + IP._ipv4ToStr(ip1) + " - " + IP._ipv4ToStr(ip2) + "\n"; output += "Range: " + IP._ipv4ToStr(ip1) + " - " + IP._ipv4ToStr(ip2) + "\n";
output += "Total addresses in range: " + (((ip2 - ip1) >>> 0) + 1) + "\n\n"; output += "Total addresses in range: " + (((ip2 - ip1) >>> 0) + 1) + "\n\n";
} }
if (enumerateAddresses) { if (enumerateAddresses) {
if (cidrRange >= 16 || allowLargeList) { if (cidrRange >= 16 || allowLargeList) {
output += IP._generateIpv4Range(ip1, ip2).join("\n"); output += IP._generateIpv4Range(ip1, ip2).join("\n");
@ -448,8 +448,8 @@ var IP = {
} }
return output; return output;
}, },
/** /**
* Parses an IPv6 CIDR range (e.g. ff00::/48) and displays information about it. * Parses an IPv6 CIDR range (e.g. ff00::/48) and displays information about it.
* *
@ -462,22 +462,22 @@ var IP = {
var output = "", var output = "",
network = IP._strToIpv6(cidr[1]), network = IP._strToIpv6(cidr[1]),
cidrRange = parseInt(cidr[cidr.length-1], 10); cidrRange = parseInt(cidr[cidr.length-1], 10);
if (cidrRange < 0 || cidrRange > 127) { if (cidrRange < 0 || cidrRange > 127) {
return "IPv6 CIDR must be less than 128"; return "IPv6 CIDR must be less than 128";
} }
var mask = IP._genIpv6Mask(cidrRange), var mask = IP._genIpv6Mask(cidrRange),
ip1 = new Array(8), ip1 = new Array(8),
ip2 = new Array(8), ip2 = new Array(8),
totalDiff = "", totalDiff = "",
total = new Array(128); total = new Array(128);
for (var i = 0; i < 8; i++) { for (var i = 0; i < 8; i++) {
ip1[i] = network[i] & mask[i]; ip1[i] = network[i] & mask[i];
ip2[i] = ip1[i] | (~mask[i] & 0x0000FFFF); ip2[i] = ip1[i] | (~mask[i] & 0x0000FFFF);
totalDiff = (ip2[i] - ip1[i]).toString(2); totalDiff = (ip2[i] - ip1[i]).toString(2);
if (totalDiff !== "0") { if (totalDiff !== "0") {
for (var n = 0; n < totalDiff.length; n++) { for (var n = 0; n < totalDiff.length; n++) {
total[i*16 + 16-(totalDiff.length-n)] = totalDiff[n]; total[i*16 + 16-(totalDiff.length-n)] = totalDiff[n];
@ -493,11 +493,11 @@ var IP = {
output += "Range: " + IP._ipv6ToStr(ip1) + " - " + IP._ipv6ToStr(ip2) + "\n"; output += "Range: " + IP._ipv6ToStr(ip1) + " - " + IP._ipv6ToStr(ip2) + "\n";
output += "Total addresses in range: " + (parseInt(total.join(""), 2) + 1) + "\n\n"; output += "Total addresses in range: " + (parseInt(total.join(""), 2) + 1) + "\n\n";
} }
return output; return output;
}, },
/** /**
* Generates an IPv6 subnet mask given a CIDR value. * Generates an IPv6 subnet mask given a CIDR value.
* *
@ -508,7 +508,7 @@ var IP = {
_genIpv6Mask: function(cidr) { _genIpv6Mask: function(cidr) {
var mask = new Array(8), var mask = new Array(8),
shift; shift;
for (var i = 0; i < 8; i++) { for (var i = 0; i < 8; i++) {
if (cidr > ((i+1)*16)) { if (cidr > ((i+1)*16)) {
mask[i] = 0x0000FFFF; mask[i] = 0x0000FFFF;
@ -518,11 +518,11 @@ var IP = {
mask[i] = ~((0x0000FFFF >>> shift) | 0xFFFF0000); mask[i] = ~((0x0000FFFF >>> shift) | 0xFFFF0000);
} }
} }
return mask; return mask;
}, },
/** /**
* Parses an IPv4 hyphenated range (e.g. 192.168.0.0 - 192.168.0.255) and displays information * Parses an IPv4 hyphenated range (e.g. 192.168.0.0 - 192.168.0.255) and displays information
* about it. * about it.
@ -538,23 +538,23 @@ var IP = {
var output = "", var output = "",
ip1 = IP._strToIpv4(range[1]), ip1 = IP._strToIpv4(range[1]),
ip2 = IP._strToIpv4(range[2]); ip2 = IP._strToIpv4(range[2]);
// Calculate mask // Calculate mask
var diff = ip1 ^ ip2, var diff = ip1 ^ ip2,
cidr = 32, cidr = 32,
mask = 0; mask = 0;
while (diff !== 0) { while (diff !== 0) {
diff >>= 1; diff >>= 1;
cidr--; cidr--;
mask = (mask << 1) | 1; mask = (mask << 1) | 1;
} }
mask = ~mask >>> 0; mask = ~mask >>> 0;
var network = ip1 & mask, var network = ip1 & mask,
subIp1 = network & mask, subIp1 = network & mask,
subIp2 = subIp1 | ~mask; subIp2 = subIp1 | ~mask;
if (includeNetworkInfo) { if (includeNetworkInfo) {
output += "Minimum subnet required to hold this range:\n"; output += "Minimum subnet required to hold this range:\n";
output += "\tNetwork: " + IP._ipv4ToStr(network) + "\n"; output += "\tNetwork: " + IP._ipv4ToStr(network) + "\n";
@ -565,7 +565,7 @@ var IP = {
output += "Range: " + IP._ipv4ToStr(ip1) + " - " + IP._ipv4ToStr(ip2) + "\n"; output += "Range: " + IP._ipv4ToStr(ip1) + " - " + IP._ipv4ToStr(ip2) + "\n";
output += "Total addresses in range: " + (((ip2 - ip1) >>> 0) + 1) + "\n\n"; output += "Total addresses in range: " + (((ip2 - ip1) >>> 0) + 1) + "\n\n";
} }
if (enumerateAddresses) { if (enumerateAddresses) {
if (((ip2 - ip1) >>> 0) <= 65536 || allowLargeList) { if (((ip2 - ip1) >>> 0) <= 65536 || allowLargeList) {
output += IP._generateIpv4Range(ip1, ip2).join("\n"); output += IP._generateIpv4Range(ip1, ip2).join("\n");
@ -575,8 +575,8 @@ var IP = {
} }
return output; return output;
}, },
/** /**
* Parses an IPv6 hyphenated range (e.g. ff00:: - ffff::) and displays information about it. * Parses an IPv6 hyphenated range (e.g. ff00:: - ffff::) and displays information about it.
* *
@ -589,14 +589,14 @@ var IP = {
var output = "", var output = "",
ip1 = IP._strToIpv6(range[1]), ip1 = IP._strToIpv6(range[1]),
ip2 = IP._strToIpv6(range[14]); ip2 = IP._strToIpv6(range[14]);
var t = "", var t = "",
total = new Array(128); total = new Array(128);
// Initialise total array to "0" // Initialise total array to "0"
for (var i = 0; i < 128; i++) for (var i = 0; i < 128; i++)
total[i] = "0"; total[i] = "0";
for (i = 0; i < 8; i++) { for (i = 0; i < 8; i++) {
t = (ip2[i] - ip1[i]).toString(2); t = (ip2[i] - ip1[i]).toString(2);
if (t !== "0") { if (t !== "0") {
@ -605,17 +605,17 @@ var IP = {
} }
} }
} }
if (includeNetworkInfo) { if (includeNetworkInfo) {
output += "Range: " + IP._ipv6ToStr(ip1) + " - " + IP._ipv6ToStr(ip2) + "\n"; output += "Range: " + IP._ipv6ToStr(ip1) + " - " + IP._ipv6ToStr(ip2) + "\n";
output += "Shorthand range: " + IP._ipv6ToStr(ip1, true) + " - " + IP._ipv6ToStr(ip2, true) + "\n"; output += "Shorthand range: " + IP._ipv6ToStr(ip1, true) + " - " + IP._ipv6ToStr(ip2, true) + "\n";
output += "Total addresses in range: " + (parseInt(total.join(""), 2) + 1) + "\n\n"; output += "Total addresses in range: " + (parseInt(total.join(""), 2) + 1) + "\n\n";
} }
return output; return output;
}, },
/** /**
* Converts an IPv4 address from string format to numerical format. * Converts an IPv4 address from string format to numerical format.
* *
@ -631,21 +631,21 @@ var IP = {
var blocks = ipStr.split("."), var blocks = ipStr.split("."),
numBlocks = parseBlocks(blocks), numBlocks = parseBlocks(blocks),
result = 0; result = 0;
result += numBlocks[0] << 24; result += numBlocks[0] << 24;
result += numBlocks[1] << 16; result += numBlocks[1] << 16;
result += numBlocks[2] << 8; result += numBlocks[2] << 8;
result += numBlocks[3]; result += numBlocks[3];
return result; return result;
/** /**
* Converts a list of 4 numeric strings in the range 0-255 to a list of numbers. * Converts a list of 4 numeric strings in the range 0-255 to a list of numbers.
*/ */
function parseBlocks(blocks) { function parseBlocks(blocks) {
if (blocks.length !== 4) if (blocks.length !== 4)
throw "More than 4 blocks."; throw "More than 4 blocks.";
var numBlocks = []; var numBlocks = [];
for (var i = 0; i < 4; i++) { for (var i = 0; i < 4; i++) {
numBlocks[i] = parseInt(blocks[i], 10); numBlocks[i] = parseInt(blocks[i], 10);
@ -655,8 +655,8 @@ var IP = {
return numBlocks; return numBlocks;
} }
}, },
/** /**
* Converts an IPv4 address from numerical format to string format. * Converts an IPv4 address from numerical format to string format.
* *
@ -673,11 +673,11 @@ var IP = {
blockB = (ipInt >> 16) & 255, blockB = (ipInt >> 16) & 255,
blockC = (ipInt >> 8) & 255, blockC = (ipInt >> 8) & 255,
blockD = ipInt & 255; blockD = ipInt & 255;
return blockA + "." + blockB + "." + blockC + "." + blockD; return blockA + "." + blockB + "." + blockC + "." + blockD;
}, },
/** /**
* Converts an IPv6 address from string format to numerical array format. * Converts an IPv6 address from string format to numerical array format.
* *
@ -694,7 +694,7 @@ var IP = {
numBlocks = parseBlocks(blocks), numBlocks = parseBlocks(blocks),
j = 0, j = 0,
ipv6 = new Array(8); ipv6 = new Array(8);
for (var i = 0; i < 8; i++) { for (var i = 0; i < 8; i++) {
if (isNaN(numBlocks[j])) { if (isNaN(numBlocks[j])) {
ipv6[i] = 0; ipv6[i] = 0;
@ -705,7 +705,7 @@ var IP = {
} }
} }
return ipv6; return ipv6;
/** /**
* Converts a list of 3-8 numeric hex strings in the range 0-65535 to a list of numbers. * Converts a list of 3-8 numeric hex strings in the range 0-65535 to a list of numbers.
*/ */
@ -721,8 +721,8 @@ var IP = {
return numBlocks; return numBlocks;
} }
}, },
/** /**
* Converts an IPv6 address from numerical array format to string format. * Converts an IPv6 address from numerical array format to string format.
* *
@ -741,13 +741,13 @@ var IP = {
_ipv6ToStr: function(ipv6, compact) { _ipv6ToStr: function(ipv6, compact) {
var output = "", var output = "",
i = 0; i = 0;
if (compact) { if (compact) {
var start = -1, var start = -1,
end = -1, end = -1,
s = 0, s = 0,
e = -1; e = -1;
for (i = 0; i < 8; i++) { for (i = 0; i < 8; i++) {
if (ipv6[i] === 0 && e === (i-1)) { if (ipv6[i] === 0 && e === (i-1)) {
e = i; e = i;
@ -759,7 +759,7 @@ var IP = {
end = e; end = e;
} }
} }
for (i = 0; i < 8; i++) { for (i = 0; i < 8; i++) {
if (i !== start) { if (i !== start) {
output += Utils.hex(ipv6[i], 1) + ":"; output += Utils.hex(ipv6[i], 1) + ":";
@ -778,8 +778,8 @@ var IP = {
} }
return output.slice(0, output.length-1); return output.slice(0, output.length-1);
}, },
/** /**
* Generates a list of IPv4 addresses in string format between two given numerical values. * Generates a list of IPv4 addresses in string format between two given numerical values.
* *

View File

@ -10,7 +10,7 @@
* @namespace * @namespace
*/ */
var JS = { var JS = {
/** /**
* @constant * @constant
* @default * @default
@ -36,7 +36,7 @@ var JS = {
* @default * @default
*/ */
PARSE_TOLERANT: false, PARSE_TOLERANT: false,
/** /**
* JavaScript Parser operation. * JavaScript Parser operation.
* *
@ -58,12 +58,12 @@ var JS = {
comment: parseComment, comment: parseComment,
tolerant: parseTolerant tolerant: parseTolerant
}; };
result = esprima.parse(input, options); result = esprima.parse(input, options);
return JSON.stringify(result, null, 2); return JSON.stringify(result, null, 2);
}, },
/** /**
* @constant * @constant
* @default * @default
@ -84,7 +84,7 @@ var JS = {
* @default * @default
*/ */
BEAUTIFY_COMMENT: true, BEAUTIFY_COMMENT: true,
/** /**
* JavaScript Beautify operation. * JavaScript Beautify operation.
* *
@ -99,14 +99,14 @@ var JS = {
beautifyComment = args[3], beautifyComment = args[3],
result = "", result = "",
AST; AST;
try { try {
AST = esprima.parse(input, { AST = esprima.parse(input, {
range: true, range: true,
tokens: true, tokens: true,
comment: true comment: true
}); });
var options = { var options = {
format: { format: {
indent: { indent: {
@ -117,19 +117,19 @@ var JS = {
}, },
comment: beautifyComment comment: beautifyComment
}; };
if (options.comment) if (options.comment)
AST = escodegen.attachComments(AST, AST.comments, AST.tokens); AST = escodegen.attachComments(AST, AST.comments, AST.tokens);
result = escodegen.generate(AST, options); result = escodegen.generate(AST, options);
} catch(e) { } catch (e) {
// Leave original error so the user can see the detail // Leave original error so the user can see the detail
throw "Unable to parse JavaScript.<br>" + e.message; throw "Unable to parse JavaScript.<br>" + e.message;
} }
return result; return result;
}, },
/** /**
* JavaScript Minify operation. * JavaScript Minify operation.
* *
@ -142,7 +142,7 @@ var JS = {
AST = esprima.parse(input), AST = esprima.parse(input),
optimisedAST = esmangle.optimize(AST, null), optimisedAST = esmangle.optimize(AST, null),
mangledAST = esmangle.mangle(optimisedAST); mangledAST = esmangle.mangle(optimisedAST);
result = escodegen.generate(mangledAST, { result = escodegen.generate(mangledAST, {
format: { format: {
renumber: true, renumber: true,

View File

@ -44,7 +44,7 @@ var MAC = {
*/ */
runFormat: function(input, args) { runFormat: function(input, args) {
if (!input) return ""; if (!input) return "";
var outputCase = args[0], var outputCase = args[0],
noDelim = args[1], noDelim = args[1],
dashDelim = args[2], dashDelim = args[2],
@ -58,7 +58,7 @@ var MAC = {
macHyphen = cleanMac.replace(/(.{2}(?=.))/g, "$1-"), macHyphen = cleanMac.replace(/(.{2}(?=.))/g, "$1-"),
macColon = cleanMac.replace(/(.{2}(?=.))/g, "$1:"), macColon = cleanMac.replace(/(.{2}(?=.))/g, "$1:"),
macCisco = cleanMac.replace(/(.{4}(?=.))/g, "$1."); macCisco = cleanMac.replace(/(.{4}(?=.))/g, "$1.");
if (outputCase === "Lower only") { if (outputCase === "Lower only") {
if (noDelim) outputList.push(cleanMac); if (noDelim) outputList.push(cleanMac);
if (dashDelim) outputList.push(macHyphen); if (dashDelim) outputList.push(macHyphen);
@ -75,7 +75,7 @@ var MAC = {
if (colonDelim) outputList.push(macColon, macColon.toUpperCase()); if (colonDelim) outputList.push(macColon, macColon.toUpperCase());
if (ciscoStyle) outputList.push(macCisco, macCisco.toUpperCase()); if (ciscoStyle) outputList.push(macCisco, macCisco.toUpperCase());
} }
outputList.push( outputList.push(
"" // Empty line to delimit groups "" // Empty line to delimit groups
); );

View File

@ -89,7 +89,7 @@ var MorseCode = {
words = Array.prototype.map.call(words, function(word) { words = Array.prototype.map.call(words, function(word) {
var letters = Array.prototype.map.call(word, function(character) { var letters = Array.prototype.map.call(word, function(character) {
var letter = character.toUpperCase(); var letter = character.toUpperCase();
if(typeof MorseCode.MORSE_TABLE[letter] == "undefined") { if (typeof MorseCode.MORSE_TABLE[letter] == "undefined") {
return ""; return "";
} }
@ -106,7 +106,7 @@ var MorseCode = {
input = input.replace( input = input.replace(
/<dash>|<dot>|<ld>|<wd>/g, /<dash>|<dot>|<ld>|<wd>/g,
function(match) { function(match) {
switch(match) { switch (match) {
case "<dash>": return dash; case "<dash>": return dash;
case "<dot>": return dot; case "<dot>": return dot;
case "<ld>": return letterDelim; case "<ld>": return letterDelim;
@ -131,14 +131,14 @@ var MorseCode = {
var reverseTable = function() { var reverseTable = function() {
reversedTable = {}; reversedTable = {};
for(var letter in MorseCode.MORSE_TABLE) { for (var letter in MorseCode.MORSE_TABLE) {
var signal = MorseCode.MORSE_TABLE[letter]; var signal = MorseCode.MORSE_TABLE[letter];
reversedTable[signal] = letter; reversedTable[signal] = letter;
} }
}; };
return function(input, args) { return function(input, args) {
if(reversedTable === null) { if (reversedTable === null) {
reverseTable(); reverseTable();
} }

View File

@ -23,5 +23,5 @@ var Numberwang = {
return "Sorry, that's not Numberwang. Let's rotate the board!"; return "Sorry, that's not Numberwang. Let's rotate the board!";
} }
}, },
}; };

View File

@ -10,13 +10,13 @@
* @namespace * @namespace
*/ */
var PublicKey = { var PublicKey = {
/** /**
* @constant * @constant
* @default * @default
*/ */
X509_INPUT_FORMAT: ["PEM", "DER Hex", "Base64", "Raw"], X509_INPUT_FORMAT: ["PEM", "DER Hex", "Base64", "Raw"],
/** /**
* Parse X.509 certificate operation. * Parse X.509 certificate operation.
* *
@ -27,11 +27,11 @@ var PublicKey = {
runParseX509: function (input, args) { runParseX509: function (input, args) {
var cert = new X509(), var cert = new X509(),
inputFormat = args[0]; inputFormat = args[0];
if (!input.length) { if (!input.length) {
return "No input"; return "No input";
} }
switch (inputFormat) { switch (inputFormat) {
case "DER Hex": case "DER Hex":
input = input.replace(/\s/g, ""); input = input.replace(/\s/g, "");
@ -53,7 +53,7 @@ var PublicKey = {
default: default:
throw "Undefined input format"; throw "Undefined input format";
} }
var version = ASN1HEX.getDecendantHexVByNthList(cert.hex, 0, [0, 0, 0]), var version = ASN1HEX.getDecendantHexVByNthList(cert.hex, 0, [0, 0, 0]),
sn = cert.getSerialNumberHex(), sn = cert.getSerialNumberHex(),
algorithm = KJUR.asn1.x509.OID.oid2name(KJUR.asn1.ASN1Util.oidHexToInt(ASN1HEX.getDecendantHexVByNthList(cert.hex, 0, [0, 2, 0]))), algorithm = KJUR.asn1.x509.OID.oid2name(KJUR.asn1.ASN1Util.oidHexToInt(ASN1HEX.getDecendantHexVByNthList(cert.hex, 0, [0, 2, 0]))),
@ -69,7 +69,7 @@ var PublicKey = {
certSig = ASN1HEX.getDecendantHexVByNthList(cert.hex, 0, [2]).substr(2), certSig = ASN1HEX.getDecendantHexVByNthList(cert.hex, 0, [2]).substr(2),
sigStr = "", sigStr = "",
extensions = ASN1HEX.dump(ASN1HEX.getDecendantHexVByNthList(cert.hex, 0, [0, 7])); extensions = ASN1HEX.dump(ASN1HEX.getDecendantHexVByNthList(cert.hex, 0, [0, 7]));
// Public Key fields // Public Key fields
if (pk.type === "EC") { // ECDSA if (pk.type === "EC") { // ECDSA
pkFields.push({ pkFields.push({
@ -120,7 +120,7 @@ var PublicKey = {
value: "Unknown Public Key type" value: "Unknown Public Key type"
}); });
} }
// Signature fields // Signature fields
if (ASN1HEX.dump(certSig).indexOf("SEQUENCE") === 0) { // DSA or ECDSA if (ASN1HEX.dump(certSig).indexOf("SEQUENCE") === 0) { // DSA or ECDSA
sigStr = " r: " + PublicKey._formatByteStr(ASN1HEX.getDecendantHexVByNthList(certSig, 0, [0]), 16, 18) + "\n" + sigStr = " r: " + PublicKey._formatByteStr(ASN1HEX.getDecendantHexVByNthList(certSig, 0, [0]), 16, 18) + "\n" +
@ -128,7 +128,7 @@ var PublicKey = {
} else { // RSA } else { // RSA
sigStr = " Signature: " + PublicKey._formatByteStr(certSig, 16, 18) + "\n"; sigStr = " Signature: " + PublicKey._formatByteStr(certSig, 16, 18) + "\n";
} }
// Format Public Key fields // Format Public Key fields
for (var i = 0; i < pkFields.length; i++) { for (var i = 0; i < pkFields.length; i++) {
pkStr += " " + pkFields[i].key + ":" + pkStr += " " + pkFields[i].key + ":" +
@ -138,12 +138,12 @@ var PublicKey = {
" " " "
); );
} }
var issuerStr = PublicKey._formatDnStr(issuer, 2), var issuerStr = PublicKey._formatDnStr(issuer, 2),
nbDate = PublicKey._formatDate(notBefore), nbDate = PublicKey._formatDate(notBefore),
naDate = PublicKey._formatDate(notAfter), naDate = PublicKey._formatDate(notAfter),
subjectStr = PublicKey._formatDnStr(subject, 2); subjectStr = PublicKey._formatDnStr(subject, 2);
var output = "Version: " + (parseInt(version, 16) + 1) + " (0x" + version + ")\n" + var output = "Version: " + (parseInt(version, 16) + 1) + " (0x" + version + ")\n" +
"Serial number: " + new BigInteger(sn, 16).toString() + " (0x" + sn + ")\n" + "Serial number: " + new BigInteger(sn, 16).toString() + " (0x" + sn + ")\n" +
"Algorithm ID: " + algorithm + "\n" + "Algorithm ID: " + algorithm + "\n" +
@ -162,11 +162,11 @@ var PublicKey = {
sigStr + sigStr +
"\nExtensions (parsed ASN.1)\n" + "\nExtensions (parsed ASN.1)\n" +
extensions; extensions;
return output; return output;
}, },
/** /**
* PEM to Hex operation. * PEM to Hex operation.
* *
@ -185,14 +185,14 @@ var PublicKey = {
} }
return KEYUTIL.getHexFromPEM(input); return KEYUTIL.getHexFromPEM(input);
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
PEM_HEADER_STRING: "CERTIFICATE", PEM_HEADER_STRING: "CERTIFICATE",
/** /**
* Hex to PEM operation. * Hex to PEM operation.
* *
@ -203,8 +203,8 @@ var PublicKey = {
runHexToPem: function(input, args) { runHexToPem: function(input, args) {
return KJUR.asn1.ASN1Util.getPEMStringFromHex(input.replace(/\s/g, ""), args[0]); return KJUR.asn1.ASN1Util.getPEMStringFromHex(input.replace(/\s/g, ""), args[0]);
}, },
/** /**
* Hex to Object Identifier operation. * Hex to Object Identifier operation.
* *
@ -215,8 +215,8 @@ var PublicKey = {
runHexToObjectIdentifier: function(input, args) { runHexToObjectIdentifier: function(input, args) {
return KJUR.asn1.ASN1Util.oidHexToInt(input.replace(/\s/g, "")); return KJUR.asn1.ASN1Util.oidHexToInt(input.replace(/\s/g, ""));
}, },
/** /**
* Object Identifier to Hex operation. * Object Identifier to Hex operation.
* *
@ -227,14 +227,14 @@ var PublicKey = {
runObjectIdentifierToHex: function(input, args) { runObjectIdentifierToHex: function(input, args) {
return KJUR.asn1.ASN1Util.oidIntToHex(input); return KJUR.asn1.ASN1Util.oidIntToHex(input);
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
ASN1_TRUNCATE_LENGTH: 32, ASN1_TRUNCATE_LENGTH: 32,
/** /**
* Parse ASN.1 hex string operation. * Parse ASN.1 hex string operation.
* *
@ -249,8 +249,8 @@ var PublicKey = {
"ommitLongOctet": truncateLen "ommitLongOctet": truncateLen
}, index); }, index);
}, },
/** /**
* Formats Distinguished Name (DN) strings. * Formats Distinguished Name (DN) strings.
* *
@ -266,29 +266,29 @@ var PublicKey = {
key, key,
value, value,
str; str;
for (var i = 0; i < fields.length; i++) { for (var i = 0; i < fields.length; i++) {
if (!fields[i].length) continue; if (!fields[i].length) continue;
key = fields[i].split("=")[0]; key = fields[i].split("=")[0];
maxKeyLen = key.length > maxKeyLen ? key.length : maxKeyLen; maxKeyLen = key.length > maxKeyLen ? key.length : maxKeyLen;
} }
for (i = 0; i < fields.length; i++) { for (i = 0; i < fields.length; i++) {
if (!fields[i].length) continue; if (!fields[i].length) continue;
key = fields[i].split("=")[0]; key = fields[i].split("=")[0];
value = fields[i].split("=")[1]; value = fields[i].split("=")[1];
str = Utils.padRight(key, maxKeyLen) + " = " + value + "\n"; str = Utils.padRight(key, maxKeyLen) + " = " + value + "\n";
output += Utils.padLeft(str, indent + str.length, " "); output += Utils.padLeft(str, indent + str.length, " ");
} }
return output; return output;
}, },
/** /**
* Formats byte strings by adding line breaks and delimiters. * Formats byte strings by adding line breaks and delimiters.
* *
@ -302,7 +302,7 @@ var PublicKey = {
byteStr = Utils.toHex(Utils.fromHex(byteStr), ":"); byteStr = Utils.toHex(Utils.fromHex(byteStr), ":");
length = length * 3; length = length * 3;
var output = ""; var output = "";
for (var i = 0; i < byteStr.length; i += length) { for (var i = 0; i < byteStr.length; i += length) {
var str = byteStr.slice(i, i + length) + "\n"; var str = byteStr.slice(i, i + length) + "\n";
if (i === 0) { if (i === 0) {
@ -311,11 +311,11 @@ var PublicKey = {
output += Utils.padLeft(str, indent + str.length, " "); output += Utils.padLeft(str, indent + str.length, " ");
} }
} }
return output.slice(0, output.length-1); return output.slice(0, output.length-1);
}, },
/** /**
* Formats dates. * Formats dates.
* *
@ -331,7 +331,7 @@ var PublicKey = {
dateStr[8] + dateStr[9] + ":" + dateStr[8] + dateStr[9] + ":" +
dateStr[10] + dateStr[11]; dateStr[10] + dateStr[11];
}, },
}; };

View File

@ -16,7 +16,7 @@ var Punycode = {
* @default * @default
*/ */
IDN: false, IDN: false,
/** /**
* To Punycode operation. * To Punycode operation.
* *
@ -26,15 +26,15 @@ var Punycode = {
*/ */
runToAscii: function(input, args) { runToAscii: function(input, args) {
var idn = args[0]; var idn = args[0];
if (idn) { if (idn) {
return punycode.ToASCII(input); return punycode.ToASCII(input);
} else { } else {
return punycode.encode(input); return punycode.encode(input);
} }
}, },
/** /**
* From Punycode operation. * From Punycode operation.
* *
@ -44,12 +44,12 @@ var Punycode = {
*/ */
runToUnicode: function(input, args) { runToUnicode: function(input, args) {
var idn = args[0]; var idn = args[0];
if (idn) { if (idn) {
return punycode.ToUnicode(input); return punycode.ToUnicode(input);
} else { } else {
return punycode.decode(input); return punycode.decode(input);
} }
}, },
}; };

View File

@ -2,14 +2,14 @@
======================================================================== ========================================================================
mimelib: http://github.com/andris9/mimelib mimelib: http://github.com/andris9/mimelib
Copyright (c) 2011-2012 Andris Reinman Copyright (c) 2011-2012 Andris Reinman
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -31,7 +31,7 @@
* @namespace * @namespace
*/ */
var QuotedPrintable = { var QuotedPrintable = {
/** /**
* To Quoted Printable operation. * To Quoted Printable operation.
* *
@ -41,7 +41,7 @@ var QuotedPrintable = {
*/ */
runTo: function (input, args) { runTo: function (input, args) {
var mimeEncodedStr = QuotedPrintable.mimeEncode(input); var mimeEncodedStr = QuotedPrintable.mimeEncode(input);
// fix line breaks // fix line breaks
mimeEncodedStr = mimeEncodedStr.replace(/\r?\n|\r/g, function() { mimeEncodedStr = mimeEncodedStr.replace(/\r?\n|\r/g, function() {
return "\r\n"; return "\r\n";
@ -51,8 +51,8 @@ var QuotedPrintable = {
return QuotedPrintable._addSoftLinebreaks(mimeEncodedStr, "qp"); return QuotedPrintable._addSoftLinebreaks(mimeEncodedStr, "qp");
}, },
/** /**
* From Quoted Printable operation. * From Quoted Printable operation.
* *
@ -64,8 +64,8 @@ var QuotedPrintable = {
var str = input.replace(/\=(?:\r?\n|$)/g, ""); var str = input.replace(/\=(?:\r?\n|$)/g, "");
return QuotedPrintable.mimeDecode(str); return QuotedPrintable.mimeDecode(str);
}, },
/** /**
* Decodes mime-encoded data. * Decodes mime-encoded data.
* *
@ -91,8 +91,8 @@ var QuotedPrintable = {
return buffer; return buffer;
}, },
/** /**
* Encodes mime data. * Encodes mime data.
* *
@ -123,8 +123,8 @@ var QuotedPrintable = {
return result; return result;
}, },
/** /**
* Checks if a given number falls within a given set of ranges. * Checks if a given number falls within a given set of ranges.
* *
@ -145,7 +145,7 @@ var QuotedPrintable = {
return false; return false;
}, },
/** /**
* Adds soft line breaks to a string. * Adds soft line breaks to a string.
* Lines can't be longer that 76 + <CR><LF> = 78 bytes * Lines can't be longer that 76 + <CR><LF> = 78 bytes
@ -168,7 +168,7 @@ var QuotedPrintable = {
} }
}, },
/** /**
* Adds soft line breaks to a base64 string. * Adds soft line breaks to a base64 string.
* *
@ -182,7 +182,7 @@ var QuotedPrintable = {
return base64EncodedStr.replace(new RegExp(".{" + lineLengthMax + "}", "g"), "$&\r\n").trim(); return base64EncodedStr.replace(new RegExp(".{" + lineLengthMax + "}", "g"), "$&\r\n").trim();
}, },
/** /**
* Adds soft line breaks to a quoted printable string. * Adds soft line breaks to a quoted printable string.
* *
@ -266,5 +266,5 @@ var QuotedPrintable = {
return result; return result;
}, },
}; };

View File

@ -21,7 +21,7 @@ var Rotate = {
* @default * @default
*/ */
ROTATE_WHOLE: false, ROTATE_WHOLE: false,
/** /**
* Runs rotation operations across the input data. * Runs rotation operations across the input data.
* *
@ -42,8 +42,8 @@ var Rotate = {
} }
return result; return result;
}, },
/** /**
* Rotate right operation. * Rotate right operation.
* *
@ -58,8 +58,8 @@ var Rotate = {
return Rotate._rot(input, args[0], Rotate._rotr); return Rotate._rot(input, args[0], Rotate._rotr);
} }
}, },
/** /**
* Rotate left operation. * Rotate left operation.
* *
@ -74,8 +74,8 @@ var Rotate = {
return Rotate._rot(input, args[0], Rotate._rotl); return Rotate._rot(input, args[0], Rotate._rotl);
} }
}, },
/** /**
* @constant * @constant
* @default * @default
@ -105,12 +105,12 @@ var Rotate = {
chr, chr,
rot13Lowercase = args[0], rot13Lowercase = args[0],
rot13Upperacse = args[1]; rot13Upperacse = args[1];
if (amount) { if (amount) {
if (amount < 0) { if (amount < 0) {
amount = 26 - (Math.abs(amount) % 26); amount = 26 - (Math.abs(amount) % 26);
} }
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
chr = input[i]; chr = input[i];
if (rot13Upperacse && chr >= 65 && chr <= 90) { // Upper case if (rot13Upperacse && chr >= 65 && chr <= 90) { // Upper case
@ -173,8 +173,8 @@ var Rotate = {
var bit = (b & 1) << 7; var bit = (b & 1) << 7;
return (b >> 1) | bit; return (b >> 1) | bit;
}, },
/** /**
* Rotate left bitwise op. * Rotate left bitwise op.
* *
@ -186,8 +186,8 @@ var Rotate = {
var bit = (b >> 7) & 1; var bit = (b >> 7) & 1;
return ((b << 1) | bit) & 0xFF; return ((b << 1) | bit) & 0xFF;
}, },
/** /**
* Rotates a byte array to the right by a specific amount as a whole, so that bits are wrapped * Rotates a byte array to the right by a specific amount as a whole, so that bits are wrapped
* from the end of the array to the beginning. * from the end of the array to the beginning.
@ -201,7 +201,7 @@ var Rotate = {
var carryBits = 0, var carryBits = 0,
newByte, newByte,
result = []; result = [];
amount = amount % 8; amount = amount % 8;
for (var i = 0; i < data.length; i++) { for (var i = 0; i < data.length; i++) {
var oldByte = data[i] >>> 0; var oldByte = data[i] >>> 0;
@ -212,8 +212,8 @@ var Rotate = {
result[0] |= carryBits; result[0] |= carryBits;
return result; return result;
}, },
/** /**
* Rotates a byte array to the left by a specific amount as a whole, so that bits are wrapped * Rotates a byte array to the left by a specific amount as a whole, so that bits are wrapped
* from the beginning of the array to the end. * from the beginning of the array to the end.
@ -227,7 +227,7 @@ var Rotate = {
var carryBits = 0, var carryBits = 0,
newByte, newByte,
result = []; result = [];
amount = amount % 8; amount = amount % 8;
for (var i = data.length-1; i >= 0; i--) { for (var i = data.length-1; i >= 0; i--) {
var oldByte = data[i]; var oldByte = data[i];

View File

@ -24,7 +24,7 @@ var SeqUtils = {
* @default * @default
*/ */
SORT_ORDER: ["Alphabetical (case sensitive)", "Alphabetical (case insensitive)", "IP address"], SORT_ORDER: ["Alphabetical (case sensitive)", "Alphabetical (case insensitive)", "IP address"],
/** /**
* Sort operation. * Sort operation.
* *
@ -37,7 +37,7 @@ var SeqUtils = {
sortReverse = args[1], sortReverse = args[1],
order = args[2], order = args[2],
sorted = input.split(delim); sorted = input.split(delim);
if (order === "Alphabetical (case sensitive)") { if (order === "Alphabetical (case sensitive)") {
sorted = sorted.sort(); sorted = sorted.sort();
} else if (order === "Alphabetical (case insensitive)") { } else if (order === "Alphabetical (case insensitive)") {
@ -45,12 +45,12 @@ var SeqUtils = {
} else if (order === "IP address") { } else if (order === "IP address") {
sorted = sorted.sort(SeqUtils._ipSort); sorted = sorted.sort(SeqUtils._ipSort);
} }
if (sortReverse) sorted.reverse(); if (sortReverse) sorted.reverse();
return sorted.join(delim); return sorted.join(delim);
}, },
/** /**
* Unique operation. * Unique operation.
* *
@ -62,14 +62,14 @@ var SeqUtils = {
var delim = Utils.charRep[args[0]]; var delim = Utils.charRep[args[0]];
return input.split(delim).unique().join(delim); return input.split(delim).unique().join(delim);
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
SEARCH_TYPE: ["Regex", "Extended (\\n, \\t, \\x...)", "Simple string"], SEARCH_TYPE: ["Regex", "Extended (\\n, \\t, \\x...)", "Simple string"],
/** /**
* Count occurrences operation. * Count occurrences operation.
* *
@ -80,13 +80,13 @@ var SeqUtils = {
runCount: function(input, args) { runCount: function(input, args) {
var search = args[0].string, var search = args[0].string,
type = args[0].option; type = args[0].option;
if (type === "Regex" && search) { if (type === "Regex" && search) {
try { try {
var regex = new RegExp(search, "gi"), var regex = new RegExp(search, "gi"),
matches = input.match(regex); matches = input.match(regex);
return matches.length; return matches.length;
} catch(err) { } catch (err) {
return 0; return 0;
} }
} else if (search) { } else if (search) {
@ -98,14 +98,14 @@ var SeqUtils = {
return 0; return 0;
} }
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
REVERSE_BY: ["Character", "Line"], REVERSE_BY: ["Character", "Line"],
/** /**
* Reverse operation. * Reverse operation.
* *
@ -137,8 +137,8 @@ var SeqUtils = {
return input.reverse(); return input.reverse();
} }
}, },
/** /**
* Add line numbers operation. * Add line numbers operation.
* *
@ -150,14 +150,14 @@ var SeqUtils = {
var lines = input.split("\n"), var lines = input.split("\n"),
output = "", output = "",
width = lines.length.toString().length; width = lines.length.toString().length;
for (var n = 0; n < lines.length; n++) { for (var n = 0; n < lines.length; n++) {
output += Utils.pad((n+1).toString(), width, " ") + " " + lines[n] + "\n"; output += Utils.pad((n+1).toString(), width, " ") + " " + lines[n] + "\n";
} }
return output.slice(0, output.length-1); return output.slice(0, output.length-1);
}, },
/** /**
* Remove line numbers operation. * Remove line numbers operation.
* *
@ -168,8 +168,8 @@ var SeqUtils = {
runRemoveLineNumbers: function(input, args) { runRemoveLineNumbers: function(input, args) {
return input.replace(/^[ \t]{0,5}\d+[\s:|\-,.)\]]/gm, ""); return input.replace(/^[ \t]{0,5}\d+[\s:|\-,.)\]]/gm, "");
}, },
/** /**
* Expand alphabet range operation. * Expand alphabet range operation.
* *
@ -180,8 +180,8 @@ var SeqUtils = {
runExpandAlphRange: function(input, args) { runExpandAlphRange: function(input, args) {
return Utils.expandAlphRange(input).join(args[0]); return Utils.expandAlphRange(input).join(args[0]);
}, },
/** /**
* Comparison operation for sorting of strings ignoring case. * Comparison operation for sorting of strings ignoring case.
* *
@ -193,8 +193,8 @@ var SeqUtils = {
_caseInsensitiveSort: function(a, b) { _caseInsensitiveSort: function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase()); return a.toLowerCase().localeCompare(b.toLowerCase());
}, },
/** /**
* Comparison operation for sorting of IPv4 addresses. * Comparison operation for sorting of IPv4 addresses.
* *
@ -206,15 +206,15 @@ var SeqUtils = {
_ipSort: function(a, b) { _ipSort: function(a, b) {
var a_ = a.split("."), var a_ = a.split("."),
b_ = b.split("."); b_ = b.split(".");
a_ = a_[0] * 0x1000000 + a_[1] * 0x10000 + a_[2] * 0x100 + a_[3] * 1; a_ = a_[0] * 0x1000000 + a_[1] * 0x10000 + a_[2] * 0x100 + a_[3] * 1;
b_ = b_[0] * 0x1000000 + b_[1] * 0x10000 + b_[2] * 0x100 + b_[3] * 1; b_ = b_[0] * 0x1000000 + b_[1] * 0x10000 + b_[2] * 0x100 + b_[3] * 1;
if (isNaN(a_) && !isNaN(b_)) return 1; if (isNaN(a_) && !isNaN(b_)) return 1;
if (!isNaN(a_) && isNaN(b_)) return -1; if (!isNaN(a_) && isNaN(b_)) return -1;
if (isNaN(a_) && isNaN(b_)) return a.localeCompare(b); if (isNaN(a_) && isNaN(b_)) return a.localeCompare(b);
return a_ - b_; return a_ - b_;
}, },
}; };

View File

@ -89,7 +89,7 @@ var StrUtils = {
* @default * @default
*/ */
DISPLAY_TOTAL: false, DISPLAY_TOTAL: false,
/** /**
* Regular expression operation. * Regular expression operation.
* *
@ -104,14 +104,14 @@ var StrUtils = {
displayTotal = args[4], displayTotal = args[4],
outputFormat = args[5], outputFormat = args[5],
modifiers = "g"; modifiers = "g";
if (i) modifiers += "i"; if (i) modifiers += "i";
if (m) modifiers += "m"; if (m) modifiers += "m";
if (userRegex && userRegex !== "^" && userRegex !== "$") { if (userRegex && userRegex !== "^" && userRegex !== "$") {
try { try {
var regex = new RegExp(userRegex, modifiers); var regex = new RegExp(userRegex, modifiers);
switch (outputFormat) { switch (outputFormat) {
case "Highlight matches": case "Highlight matches":
return StrUtils._regexHighlight(input, regex, displayTotal); return StrUtils._regexHighlight(input, regex, displayTotal);
@ -132,13 +132,13 @@ var StrUtils = {
} }
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
CASE_SCOPE: ["All", "Word", "Sentence", "Paragraph"], CASE_SCOPE: ["All", "Word", "Sentence", "Paragraph"],
/** /**
* To Upper case operation. * To Upper case operation.
* *
@ -148,7 +148,7 @@ var StrUtils = {
*/ */
runUpper: function (input, args) { runUpper: function (input, args) {
var scope = args[0]; var scope = args[0];
switch (scope) { switch (scope) {
case "Word": case "Word":
return input.replace(/(\b\w)/gi, function(m) { return input.replace(/(\b\w)/gi, function(m) {
@ -168,8 +168,8 @@ var StrUtils = {
return input.toUpperCase(); return input.toUpperCase();
} }
}, },
/** /**
* To Upper case operation. * To Upper case operation.
* *
@ -180,8 +180,8 @@ var StrUtils = {
runLower: function (input, args) { runLower: function (input, args) {
return input.toLowerCase(); return input.toLowerCase();
}, },
/** /**
* @constant * @constant
* @default * @default
@ -202,7 +202,7 @@ var StrUtils = {
* @default * @default
*/ */
FIND_REPLACE_MULTILINE : true, FIND_REPLACE_MULTILINE : true,
/** /**
* Find / Replace operation. * Find / Replace operation.
* *
@ -218,24 +218,24 @@ var StrUtils = {
i = args[3], i = args[3],
m = args[4], m = args[4],
modifiers = ""; modifiers = "";
if (g) modifiers += "g"; if (g) modifiers += "g";
if (i) modifiers += "i"; if (i) modifiers += "i";
if (m) modifiers += "m"; if (m) modifiers += "m";
if (type === "Regex") { if (type === "Regex") {
find = new RegExp(find, modifiers); find = new RegExp(find, modifiers);
} else if (type.indexOf("Extended") === 0) { } else if (type.indexOf("Extended") === 0) {
find = Utils.parseEscapedChars(find); find = Utils.parseEscapedChars(find);
} }
return input.replace(find, replace, modifiers); return input.replace(find, replace, modifiers);
// Non-standard addition of flags in the third argument. This will work in Firefox but // Non-standard addition of flags in the third argument. This will work in Firefox but
// probably nowhere else. The purpose is to allow global matching when the `find` parameter // probably nowhere else. The purpose is to allow global matching when the `find` parameter
// is just a string. // is just a string.
}, },
/** /**
* @constant * @constant
* @default * @default
@ -246,7 +246,7 @@ var StrUtils = {
* @default * @default
*/ */
DELIMITER_OPTIONS: ["Line feed", "CRLF", "Space", "Comma", "Semi-colon", "Colon", "Nothing (separate chars)"], DELIMITER_OPTIONS: ["Line feed", "CRLF", "Space", "Comma", "Semi-colon", "Colon", "Nothing (separate chars)"],
/** /**
* Split operation. * Split operation.
* *
@ -258,7 +258,7 @@ var StrUtils = {
var splitDelim = args[0] || StrUtils.SPLIT_DELIM, var splitDelim = args[0] || StrUtils.SPLIT_DELIM,
joinDelim = Utils.charRep[args[1]], joinDelim = Utils.charRep[args[1]],
sections = input.split(splitDelim); sections = input.split(splitDelim);
return sections.join(joinDelim); return sections.join(joinDelim);
}, },
@ -287,8 +287,8 @@ var StrUtils = {
return input.split(delim).filter(regexFilter).join(delim); return input.split(delim).filter(regexFilter).join(delim);
}, },
/** /**
* @constant * @constant
* @default * @default
@ -299,7 +299,7 @@ var StrUtils = {
* @default * @default
*/ */
DIFF_BY: ["Character", "Word", "Line", "Sentence", "CSS", "JSON"], DIFF_BY: ["Character", "Word", "Line", "Sentence", "CSS", "JSON"],
/** /**
* Diff operation. * Diff operation.
* *
@ -316,11 +316,11 @@ var StrUtils = {
samples = input.split(sampleDelim), samples = input.split(sampleDelim),
output = "", output = "",
diff; diff;
if (!samples || samples.length !== 2) { if (!samples || samples.length !== 2) {
return "Incorrect number of samples, perhaps you need to modify the sample delimiter or add more samples?"; return "Incorrect number of samples, perhaps you need to modify the sample delimiter or add more samples?";
} }
switch (diffBy) { switch (diffBy) {
case "Character": case "Character":
diff = JsDiff.diffChars(samples[0], samples[1]); diff = JsDiff.diffChars(samples[0], samples[1]);
@ -351,7 +351,7 @@ var StrUtils = {
default: default:
return "Invalid 'Diff by' option."; return "Invalid 'Diff by' option.";
} }
for (var i = 0; i < diff.length; i++) { for (var i = 0; i < diff.length; i++) {
if (diff[i].added) { if (diff[i].added) {
if (showAdded) output += "<span class='hlgreen'>" + Utils.escapeHtml(diff[i].value) + "</span>"; if (showAdded) output += "<span class='hlgreen'>" + Utils.escapeHtml(diff[i].value) + "</span>";
@ -361,17 +361,17 @@ var StrUtils = {
output += Utils.escapeHtml(diff[i].value); output += Utils.escapeHtml(diff[i].value);
} }
} }
return output; return output;
}, },
/** /**
* @constant * @constant
* @default * @default
*/ */
OFF_CHK_SAMPLE_DELIMITER: "\\n\\n", OFF_CHK_SAMPLE_DELIMITER: "\\n\\n",
/** /**
* Offset checker operation. * Offset checker operation.
* *
@ -388,21 +388,21 @@ var StrUtils = {
match = false, match = false,
inMatch = false, inMatch = false,
chr; chr;
if (!samples || samples.length < 2) { if (!samples || samples.length < 2) {
return "Not enough samples, perhaps you need to modify the sample delimiter or add more data?"; return "Not enough samples, perhaps you need to modify the sample delimiter or add more data?";
} }
// Initialise output strings // Initialise output strings
for (s = 0; s < samples.length; s++) { for (s = 0; s < samples.length; s++) {
outputs[s] = ""; outputs[s] = "";
} }
// Loop through each character in the first sample // Loop through each character in the first sample
for (i = 0; i < samples[0].length; i++) { for (i = 0; i < samples[0].length; i++) {
chr = samples[0][i]; chr = samples[0][i];
match = false; match = false;
// Loop through each sample to see if the chars are the same // Loop through each sample to see if the chars are the same
for (s = 1; s < samples.length; s++) { for (s = 1; s < samples.length; s++) {
if (samples[s][i] !== chr) { if (samples[s][i] !== chr) {
@ -411,7 +411,7 @@ var StrUtils = {
} }
match = true; match = true;
} }
// Write output for each sample // Write output for each sample
for (s = 0; s < samples.length; s++) { for (s = 0; s < samples.length; s++) {
if (samples[s].length <= i) { if (samples[s].length <= i) {
@ -419,7 +419,7 @@ var StrUtils = {
if (s === samples.length - 1) inMatch = false; if (s === samples.length - 1) inMatch = false;
continue; continue;
} }
if (match && !inMatch) { if (match && !inMatch) {
outputs[s] += "<span class='hlgreen'>" + Utils.escapeHtml(samples[s][i]); outputs[s] += "<span class='hlgreen'>" + Utils.escapeHtml(samples[s][i]);
if (samples[s].length === i + 1) outputs[s] += "</span>"; if (samples[s].length === i + 1) outputs[s] += "</span>";
@ -434,18 +434,18 @@ var StrUtils = {
if (samples[s].length - 1 !== i) inMatch = false; if (samples[s].length - 1 !== i) inMatch = false;
} }
} }
if (samples[0].length - 1 === i) { if (samples[0].length - 1 === i) {
if (inMatch) outputs[s] += "</span>"; if (inMatch) outputs[s] += "</span>";
outputs[s] += Utils.escapeHtml(samples[s].substring(i + 1)); outputs[s] += Utils.escapeHtml(samples[s].substring(i + 1));
} }
} }
} }
return outputs.join(sampleDelim); return outputs.join(sampleDelim);
}, },
/** /**
* Parse escaped string operation. * Parse escaped string operation.
* *
@ -456,8 +456,8 @@ var StrUtils = {
runParseEscapedString: function(input, args) { runParseEscapedString: function(input, args) {
return Utils.parseEscapedChars(input); return Utils.parseEscapedChars(input);
}, },
/** /**
* Adds HTML highlights to matches within a string. * Adds HTML highlights to matches within a string.
* *
@ -473,31 +473,31 @@ var StrUtils = {
hl = 1, hl = 1,
i = 0, i = 0,
total = 0; total = 0;
while ((m = regex.exec(input))) { while ((m = regex.exec(input))) {
// Add up to match // Add up to match
output += Utils.escapeHtml(input.slice(i, m.index)); output += Utils.escapeHtml(input.slice(i, m.index));
// Add match with highlighting // Add match with highlighting
output += "<span class='hl"+hl+"'>" + Utils.escapeHtml(m[0]) + "</span>"; output += "<span class='hl"+hl+"'>" + Utils.escapeHtml(m[0]) + "</span>";
// Switch highlight // Switch highlight
hl = hl === 1 ? 2 : 1; hl = hl === 1 ? 2 : 1;
i = regex.lastIndex; i = regex.lastIndex;
total++; total++;
} }
// Add all after final match // Add all after final match
output += Utils.escapeHtml(input.slice(i, input.length)); output += Utils.escapeHtml(input.slice(i, input.length));
if (displayTotal) if (displayTotal)
output = "Total found: " + total + "\n\n" + output; output = "Total found: " + total + "\n\n" + output;
return output; return output;
}, },
/** /**
* Creates a string listing the matches within a string. * Creates a string listing the matches within a string.
* *
@ -513,7 +513,7 @@ var StrUtils = {
var output = "", var output = "",
total = 0, total = 0,
match; match;
while ((match = regex.exec(input))) { while ((match = regex.exec(input))) {
total++; total++;
if (matches) { if (matches) {
@ -528,11 +528,11 @@ var StrUtils = {
} }
} }
} }
if (displayTotal) if (displayTotal)
output = "Total found: " + total + "\n\n" + output; output = "Total found: " + total + "\n\n" + output;
return output; return output;
}, },
}; };

View File

@ -39,7 +39,7 @@ var Tidy = {
* @default * @default
*/ */
REMOVE_FULL_STOPS : false, REMOVE_FULL_STOPS : false,
/** /**
* Remove whitespace operation. * Remove whitespace operation.
* *
@ -55,7 +55,7 @@ var Tidy = {
removeFormFeeds = args[4], removeFormFeeds = args[4],
removeFullStops = args[5], removeFullStops = args[5],
data = input; data = input;
if (removeSpaces) data = data.replace(/ /g, ""); if (removeSpaces) data = data.replace(/ /g, "");
if (removeCariageReturns) data = data.replace(/\r/g, ""); if (removeCariageReturns) data = data.replace(/\r/g, "");
if (removeLineFeeds) data = data.replace(/\n/g, ""); if (removeLineFeeds) data = data.replace(/\n/g, "");
@ -64,8 +64,8 @@ var Tidy = {
if (removeFullStops) data = data.replace(/\./g, ""); if (removeFullStops) data = data.replace(/\./g, "");
return data; return data;
}, },
/** /**
* Remove null bytes operation. * Remove null bytes operation.
* *
@ -80,8 +80,8 @@ var Tidy = {
} }
return output; return output;
}, },
/** /**
* @constant * @constant
* @default * @default
@ -97,7 +97,7 @@ var Tidy = {
* @default * @default
*/ */
DROP_LENGTH : 5, DROP_LENGTH : 5,
/** /**
* Drop bytes operation. * Drop bytes operation.
* *
@ -109,17 +109,17 @@ var Tidy = {
var start = args[0], var start = args[0],
length = args[1], length = args[1],
applyToEachLine = args[2]; applyToEachLine = args[2];
if (start < 0 || length < 0) if (start < 0 || length < 0)
throw "Error: Invalid value"; throw "Error: Invalid value";
if (!applyToEachLine) if (!applyToEachLine)
return input.slice(0, start).concat(input.slice(start+length, input.length)); return input.slice(0, start).concat(input.slice(start+length, input.length));
// Split input into lines // Split input into lines
var lines = [], var lines = [],
line = []; line = [];
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
if (input[i] === 0x0a) { if (input[i] === 0x0a) {
lines.push(line); lines.push(line);
@ -129,7 +129,7 @@ var Tidy = {
} }
} }
lines.push(line); lines.push(line);
var output = []; var output = [];
for (i = 0; i < lines.length; i++) { for (i = 0; i < lines.length; i++) {
output = output.concat(lines[i].slice(0, start).concat(lines[i].slice(start+length, lines[i].length))); output = output.concat(lines[i].slice(0, start).concat(lines[i].slice(start+length, lines[i].length)));
@ -137,8 +137,8 @@ var Tidy = {
} }
return output.slice(0, output.length-1); return output.slice(0, output.length-1);
}, },
/** /**
* @constant * @constant
* @default * @default
@ -149,7 +149,7 @@ var Tidy = {
* @default * @default
*/ */
TAKE_LENGTH: 5, TAKE_LENGTH: 5,
/** /**
* Take bytes operation. * Take bytes operation.
* *
@ -161,17 +161,17 @@ var Tidy = {
var start = args[0], var start = args[0],
length = args[1], length = args[1],
applyToEachLine = args[2]; applyToEachLine = args[2];
if (start < 0 || length < 0) if (start < 0 || length < 0)
throw "Error: Invalid value"; throw "Error: Invalid value";
if (!applyToEachLine) if (!applyToEachLine)
return input.slice(start, start+length); return input.slice(start, start+length);
// Split input into lines // Split input into lines
var lines = [], var lines = [],
line = []; line = [];
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
if (input[i] === 0x0a) { if (input[i] === 0x0a) {
lines.push(line); lines.push(line);
@ -181,7 +181,7 @@ var Tidy = {
} }
} }
lines.push(line); lines.push(line);
var output = []; var output = [];
for (i = 0; i < lines.length; i++) { for (i = 0; i < lines.length; i++) {
output = output.concat(lines[i].slice(start, start+length)); output = output.concat(lines[i].slice(start, start+length));
@ -189,8 +189,8 @@ var Tidy = {
} }
return output.slice(0, output.length-1); return output.slice(0, output.length-1);
}, },
/** /**
* @constant * @constant
* @default * @default
@ -206,7 +206,7 @@ var Tidy = {
* @default * @default
*/ */
PAD_CHAR : " ", PAD_CHAR : " ",
/** /**
* Pad lines operation. * Pad lines operation.
* *
@ -221,7 +221,7 @@ var Tidy = {
lines = input.split("\n"), lines = input.split("\n"),
output = "", output = "",
i = 0; i = 0;
if (position === "Start") { if (position === "Start") {
for (i = 0; i < lines.length; i++) { for (i = 0; i < lines.length; i++) {
output += Utils.padLeft(lines[i], lines[i].length+len, chr) + "\n"; output += Utils.padLeft(lines[i], lines[i].length+len, chr) + "\n";
@ -231,8 +231,8 @@ var Tidy = {
output += Utils.padRight(lines[i], lines[i].length+len, chr) + "\n"; output += Utils.padRight(lines[i], lines[i].length+len, chr) + "\n";
} }
} }
return output.slice(0, output.length-1); return output.slice(0, output.length-1);
}, },
}; };

View File

@ -17,7 +17,7 @@ var URL_ = {
* @default * @default
*/ */
ENCODE_ALL: false, ENCODE_ALL: false,
/** /**
* URL Encode operation. * URL Encode operation.
* *
@ -29,8 +29,8 @@ var URL_ = {
var encodeAll = args[0]; var encodeAll = args[0];
return encodeAll ? URL_._encodeAllChars(input) : encodeURI(input); return encodeAll ? URL_._encodeAllChars(input) : encodeURI(input);
}, },
/** /**
* URL Decode operation. * URL Decode operation.
* *
@ -42,12 +42,12 @@ var URL_ = {
var data = input.replace(/\+/g, "%20"); var data = input.replace(/\+/g, "%20");
try { try {
return decodeURIComponent(data); return decodeURIComponent(data);
} catch(err) { } catch (err) {
return unescape(data); return unescape(data);
} }
}, },
/** /**
* Parse URI operation. * Parse URI operation.
* *
@ -57,11 +57,11 @@ var URL_ = {
*/ */
runParse: function(input, args) { runParse: function(input, args) {
var a = document.createElement("a"); var a = document.createElement("a");
// Overwrite base href which will be the current CyberChef URL to reduce confusion. // Overwrite base href which will be the current CyberChef URL to reduce confusion.
a.href = "http://example.com/"; a.href = "http://example.com/";
a.href = input; a.href = input;
if (a.protocol) { if (a.protocol) {
var output = ""; var output = "";
if (a.hostname !== window.location.hostname) { if (a.hostname !== window.location.hostname) {
@ -69,7 +69,7 @@ var URL_ = {
if (a.hostname) output += "Hostname:\t" + a.hostname + "\n"; if (a.hostname) output += "Hostname:\t" + a.hostname + "\n";
if (a.port) output += "Port:\t\t" + a.port + "\n"; if (a.port) output += "Port:\t\t" + a.port + "\n";
} }
if (a.pathname && a.pathname !== window.location.pathname) { if (a.pathname && a.pathname !== window.location.pathname) {
var pathname = a.pathname; var pathname = a.pathname;
if (pathname.indexOf(window.location.pathname) === 0) if (pathname.indexOf(window.location.pathname) === 0)
@ -77,11 +77,11 @@ var URL_ = {
if (pathname) if (pathname)
output += "Path name:\t" + pathname + "\n"; output += "Path name:\t" + pathname + "\n";
} }
if (a.hash && a.hash !== window.location.hash) { if (a.hash && a.hash !== window.location.hash) {
output += "Hash:\t\t" + a.hash + "\n"; output += "Hash:\t\t" + a.hash + "\n";
} }
if (a.search && a.search !== window.location.search) { if (a.search && a.search !== window.location.search) {
output += "Arguments:\n"; output += "Arguments:\n";
var args_ = (a.search.slice(1, a.search.length)).split("&"); var args_ = (a.search.slice(1, a.search.length)).split("&");
@ -97,14 +97,14 @@ var URL_ = {
else output += "\n"; else output += "\n";
} }
} }
return output; return output;
} }
return "Invalid URI"; return "Invalid URI";
}, },
/** /**
* URL encodes additional special characters beyond the standard set. * URL encodes additional special characters beyond the standard set.
* *
@ -126,5 +126,5 @@ var URL_ = {
.replace(/_/g, "%5F") .replace(/_/g, "%5F")
.replace(/~/g, "%7E"); .replace(/~/g, "%7E");
}, },
}; };

View File

@ -28,25 +28,25 @@ var Unicode = {
output = "", output = "",
m, m,
i = 0; i = 0;
while ((m = regex.exec(input))) { while ((m = regex.exec(input))) {
// Add up to match // Add up to match
output += input.slice(i, m.index); output += input.slice(i, m.index);
i = m.index; i = m.index;
// Add match // Add match
output += Utils.chr(parseInt(m[1], 16)); output += Utils.chr(parseInt(m[1], 16));
i = regex.lastIndex; i = regex.lastIndex;
} }
// Add all after final match // Add all after final match
output += input.slice(i, input.length); output += input.slice(i, input.length);
return output; return output;
}, },
/** /**
* Lookup table to add prefixes to unicode delimiters so that they can be used in a regex. * Lookup table to add prefixes to unicode delimiters so that they can be used in a regex.
* *

View File

@ -30,13 +30,13 @@ ControlsWaiter.prototype.adjustWidth = function() {
stepImg = document.querySelector("#step img"), stepImg = document.querySelector("#step img"),
clrRecipImg = document.querySelector("#clr-recipe img"), clrRecipImg = document.querySelector("#clr-recipe img"),
clrBreaksImg = document.querySelector("#clr-breaks img"); clrBreaksImg = document.querySelector("#clr-breaks img");
if (controls.clientWidth < 470) { if (controls.clientWidth < 470) {
step.childNodes[1].nodeValue = " Step"; step.childNodes[1].nodeValue = " Step";
} else { } else {
step.childNodes[1].nodeValue = " Step through"; step.childNodes[1].nodeValue = " Step through";
} }
if (controls.clientWidth < 400) { if (controls.clientWidth < 400) {
saveImg.style.display = "none"; saveImg.style.display = "none";
loadImg.style.display = "none"; loadImg.style.display = "none";
@ -50,7 +50,7 @@ ControlsWaiter.prototype.adjustWidth = function() {
clrRecipImg.style.display = "inline"; clrRecipImg.style.display = "inline";
clrBreaksImg.style.display = "inline"; clrBreaksImg.style.display = "inline";
} }
if (controls.clientWidth < 330) { if (controls.clientWidth < 330) {
clrBreaks.childNodes[1].nodeValue = " Clear breaks"; clrBreaks.childNodes[1].nodeValue = " Clear breaks";
} else { } else {
@ -66,7 +66,7 @@ ControlsWaiter.prototype.adjustWidth = function() {
*/ */
ControlsWaiter.prototype.setAutoBake = function(value) { ControlsWaiter.prototype.setAutoBake = function(value) {
var autoBakeCheckbox = document.getElementById("auto-bake"); var autoBakeCheckbox = document.getElementById("auto-bake");
if (autoBakeCheckbox.checked !== value) { if (autoBakeCheckbox.checked !== value) {
autoBakeCheckbox.click(); autoBakeCheckbox.click();
} }
@ -97,9 +97,9 @@ ControlsWaiter.prototype.stepClick = function() {
ControlsWaiter.prototype.autoBakeChange = function() { ControlsWaiter.prototype.autoBakeChange = function() {
var autoBakeLabel = document.getElementById("auto-bake-label"), var autoBakeLabel = document.getElementById("auto-bake-label"),
autoBakeCheckbox = document.getElementById("auto-bake"); autoBakeCheckbox = document.getElementById("auto-bake");
this.app.autoBake_ = autoBakeCheckbox.checked; this.app.autoBake_ = autoBakeCheckbox.checked;
if (autoBakeCheckbox.checked) { if (autoBakeCheckbox.checked) {
autoBakeLabel.classList.remove("btn-default"); autoBakeLabel.classList.remove("btn-default");
autoBakeLabel.classList.add("btn-success"); autoBakeLabel.classList.add("btn-success");
@ -124,7 +124,7 @@ ControlsWaiter.prototype.clearRecipeClick = function() {
*/ */
ControlsWaiter.prototype.clearBreaksClick = function() { ControlsWaiter.prototype.clearBreaksClick = function() {
var bps = document.querySelectorAll("#rec-list li.operation .breakpoint"); var bps = document.querySelectorAll("#rec-list li.operation .breakpoint");
for (var i = 0; i < bps.length; i++) { for (var i = 0; i < bps.length; i++) {
bps[i].setAttribute("break", "false"); bps[i].setAttribute("break", "false");
bps[i].classList.remove("breakpoint-selected"); bps[i].classList.remove("breakpoint-selected");
@ -139,12 +139,12 @@ ControlsWaiter.prototype.clearBreaksClick = function() {
*/ */
ControlsWaiter.prototype.initialiseSaveLink = function(recipeConfig) { ControlsWaiter.prototype.initialiseSaveLink = function(recipeConfig) {
recipeConfig = recipeConfig || this.app.getRecipeConfig(); recipeConfig = recipeConfig || this.app.getRecipeConfig();
var includeRecipe = document.getElementById("save-link-recipe-checkbox").checked, var includeRecipe = document.getElementById("save-link-recipe-checkbox").checked,
includeInput = document.getElementById("save-link-input-checkbox").checked, includeInput = document.getElementById("save-link-input-checkbox").checked,
saveLinkEl = document.getElementById("save-link"), saveLinkEl = document.getElementById("save-link"),
saveLink = this.generateStateUrl(includeRecipe, includeInput, recipeConfig); saveLink = this.generateStateUrl(includeRecipe, includeInput, recipeConfig);
saveLinkEl.innerHTML = Utils.truncate(saveLink, 120); saveLinkEl.innerHTML = Utils.truncate(saveLink, 120);
saveLinkEl.setAttribute("href", saveLink); saveLinkEl.setAttribute("href", saveLink);
}; };
@ -161,26 +161,26 @@ ControlsWaiter.prototype.initialiseSaveLink = function(recipeConfig) {
*/ */
ControlsWaiter.prototype.generateStateUrl = function(includeRecipe, includeInput, recipeConfig, baseURL) { ControlsWaiter.prototype.generateStateUrl = function(includeRecipe, includeInput, recipeConfig, baseURL) {
recipeConfig = recipeConfig || this.app.getRecipeConfig(); recipeConfig = recipeConfig || this.app.getRecipeConfig();
var link = baseURL || window.location.protocol + "//" + var link = baseURL || window.location.protocol + "//" +
window.location.host + window.location.host +
window.location.pathname, window.location.pathname,
recipeStr = JSON.stringify(recipeConfig), recipeStr = JSON.stringify(recipeConfig),
inputStr = Utils.toBase64(this.app.getInput(), "A-Za-z0-9+/"); // B64 alphabet with no padding inputStr = Utils.toBase64(this.app.getInput(), "A-Za-z0-9+/"); // B64 alphabet with no padding
includeRecipe = includeRecipe && (recipeConfig.length > 0); includeRecipe = includeRecipe && (recipeConfig.length > 0);
includeInput = includeInput && (inputStr.length > 0) && (inputStr.length < 8000); includeInput = includeInput && (inputStr.length > 0) && (inputStr.length < 8000);
if (includeRecipe) { if (includeRecipe) {
link += "?recipe=" + encodeURIComponent(recipeStr); link += "?recipe=" + encodeURIComponent(recipeStr);
} }
if (includeRecipe && includeInput) { if (includeRecipe && includeInput) {
link += "&input=" + encodeURIComponent(inputStr); link += "&input=" + encodeURIComponent(inputStr);
} else if (includeInput) { } else if (includeInput) {
link += "?input=" + encodeURIComponent(inputStr); link += "?input=" + encodeURIComponent(inputStr);
} }
return link; return link;
}; };
@ -192,7 +192,7 @@ ControlsWaiter.prototype.saveTextChange = function() {
try { try {
var recipeConfig = JSON.parse(document.getElementById("save-text").value); var recipeConfig = JSON.parse(document.getElementById("save-text").value);
this.initialiseSaveLink(recipeConfig); this.initialiseSaveLink(recipeConfig);
} catch(err) {} } catch (err) {}
}; };
@ -202,9 +202,9 @@ ControlsWaiter.prototype.saveTextChange = function() {
ControlsWaiter.prototype.saveClick = function() { ControlsWaiter.prototype.saveClick = function() {
var recipeConfig = this.app.getRecipeConfig(), var recipeConfig = this.app.getRecipeConfig(),
recipeStr = JSON.stringify(recipeConfig).replace(/},{/g, "},\n{"); recipeStr = JSON.stringify(recipeConfig).replace(/},{/g, "},\n{");
document.getElementById("save-text").value = recipeStr; document.getElementById("save-text").value = recipeStr;
this.initialiseSaveLink(recipeConfig); this.initialiseSaveLink(recipeConfig);
$("#save-modal").modal(); $("#save-modal").modal();
}; };
@ -241,25 +241,25 @@ ControlsWaiter.prototype.loadClick = function() {
ControlsWaiter.prototype.saveButtonClick = function() { ControlsWaiter.prototype.saveButtonClick = function() {
var recipeName = document.getElementById("save-name").value, var recipeName = document.getElementById("save-name").value,
recipeStr = document.getElementById("save-text").value; recipeStr = document.getElementById("save-text").value;
if (!recipeName) { if (!recipeName) {
this.app.alert("Please enter a recipe name", "danger", 2000); this.app.alert("Please enter a recipe name", "danger", 2000);
return; return;
} }
var savedRecipes = localStorage.savedRecipes ? var savedRecipes = localStorage.savedRecipes ?
JSON.parse(localStorage.savedRecipes) : [], JSON.parse(localStorage.savedRecipes) : [],
recipeId = localStorage.recipeId || 0; recipeId = localStorage.recipeId || 0;
savedRecipes.push({ savedRecipes.push({
id: ++recipeId, id: ++recipeId,
name: recipeName, name: recipeName,
recipe: recipeStr recipe: recipeStr
}); });
localStorage.savedRecipes = JSON.stringify(savedRecipes); localStorage.savedRecipes = JSON.stringify(savedRecipes);
localStorage.recipeId = recipeId; localStorage.recipeId = recipeId;
this.app.alert("Recipe saved as \"" + recipeName + "\".", "success", 2000); this.app.alert("Recipe saved as \"" + recipeName + "\".", "success", 2000);
}; };
@ -269,7 +269,7 @@ ControlsWaiter.prototype.saveButtonClick = function() {
*/ */
ControlsWaiter.prototype.populateLoadRecipesList = function() { ControlsWaiter.prototype.populateLoadRecipesList = function() {
var loadNameEl = document.getElementById("load-name"); var loadNameEl = document.getElementById("load-name");
// Remove current recipes from select // Remove current recipes from select
var i = loadNameEl.options.length; var i = loadNameEl.options.length;
while (i--) { while (i--) {
@ -279,15 +279,15 @@ ControlsWaiter.prototype.populateLoadRecipesList = function() {
// Add recipes to select // Add recipes to select
var savedRecipes = localStorage.savedRecipes ? var savedRecipes = localStorage.savedRecipes ?
JSON.parse(localStorage.savedRecipes) : []; JSON.parse(localStorage.savedRecipes) : [];
for (i = 0; i < savedRecipes.length; i++) { for (i = 0; i < savedRecipes.length; i++) {
var opt = document.createElement("option"); var opt = document.createElement("option");
opt.value = savedRecipes[i].id; opt.value = savedRecipes[i].id;
opt.innerHTML = savedRecipes[i].name; opt.innerHTML = savedRecipes[i].name;
loadNameEl.appendChild(opt); loadNameEl.appendChild(opt);
} }
// Populate textarea with first recipe // Populate textarea with first recipe
document.getElementById("load-text").value = savedRecipes.length ? savedRecipes[0].recipe : ""; document.getElementById("load-text").value = savedRecipes.length ? savedRecipes[0].recipe : "";
}; };
@ -300,11 +300,11 @@ ControlsWaiter.prototype.loadDeleteClick = function() {
var id = parseInt(document.getElementById("load-name").value, 10), var id = parseInt(document.getElementById("load-name").value, 10),
savedRecipes = localStorage.savedRecipes ? savedRecipes = localStorage.savedRecipes ?
JSON.parse(localStorage.savedRecipes) : []; JSON.parse(localStorage.savedRecipes) : [];
savedRecipes = savedRecipes.filter(function(r) { savedRecipes = savedRecipes.filter(function(r) {
return r.id !== id; return r.id !== id;
}); });
localStorage.savedRecipes = JSON.stringify(savedRecipes); localStorage.savedRecipes = JSON.stringify(savedRecipes);
this.populateLoadRecipesList(); this.populateLoadRecipesList();
}; };
@ -318,11 +318,11 @@ ControlsWaiter.prototype.loadNameChange = function(e) {
savedRecipes = localStorage.savedRecipes ? savedRecipes = localStorage.savedRecipes ?
JSON.parse(localStorage.savedRecipes) : [], JSON.parse(localStorage.savedRecipes) : [],
id = parseInt(el.value, 10); id = parseInt(el.value, 10);
var recipe = savedRecipes.filter(function(r) { var recipe = savedRecipes.filter(function(r) {
return r.id === id; return r.id === id;
})[0]; })[0];
document.getElementById("load-text").value = recipe.recipe; document.getElementById("load-text").value = recipe.recipe;
}; };
@ -336,7 +336,7 @@ ControlsWaiter.prototype.loadButtonClick = function() {
this.app.setRecipeConfig(recipeConfig); this.app.setRecipeConfig(recipeConfig);
$("#rec-list [data-toggle=popover]").popover(); $("#rec-list [data-toggle=popover]").popover();
} catch(e) { } catch (e) {
this.app.alert("Invalid recipe", "danger", 2000); this.app.alert("Invalid recipe", "danger", 2000);
} }
}; };

View File

@ -362,13 +362,13 @@ HTMLApp.prototype.loadURIParams = function() {
try { try {
var recipeConfig = JSON.parse(this.queryString.recipe); var recipeConfig = JSON.parse(this.queryString.recipe);
this.setRecipeConfig(recipeConfig); this.setRecipeConfig(recipeConfig);
} catch(err) {} } catch (err) {}
} else if (this.queryString.op) { } else if (this.queryString.op) {
// If there's no recipe, look for single operations // If there's no recipe, look for single operations
this.manager.recipe.clearRecipe(); this.manager.recipe.clearRecipe();
try { try {
this.manager.recipe.addOperation(this.queryString.op); this.manager.recipe.addOperation(this.queryString.op);
} catch(err) { } catch (err) {
// If no exact match, search for nearest match and add that // If no exact match, search for nearest match and add that
var matchedOps = this.manager.ops.filterOperations(this.queryString.op, false); var matchedOps = this.manager.ops.filterOperations(this.queryString.op, false);
if (matchedOps.length) { if (matchedOps.length) {
@ -388,7 +388,7 @@ HTMLApp.prototype.loadURIParams = function() {
try { try {
var inputData = Utils.fromBase64(this.queryString.input); var inputData = Utils.fromBase64(this.queryString.input);
this.setInput(inputData); this.setInput(inputData);
} catch(err) {} } catch (err) {}
} }
// Restore auto-bake state // Restore auto-bake state

View File

@ -40,11 +40,11 @@ HTMLCategory.prototype.toHtml = function() {
</a>\ </a>\
<div id='" + catName + "' class='panel-collapse collapse\ <div id='" + catName + "' class='panel-collapse collapse\
" + (this.selected ? " in" : "") + "'><ul class='op-list'>"; " + (this.selected ? " in" : "") + "'><ul class='op-list'>";
for (var i = 0; i < this.opList.length; i++) { for (var i = 0; i < this.opList.length; i++) {
html += this.opList[i].toStubHtml(); html += this.opList[i].toStubHtml();
} }
html += "</ul></div></div>"; html += "</ul></div></div>";
return html; return html;
}; };

View File

@ -13,7 +13,7 @@
var HTMLIngredient = function(config, app, manager) { var HTMLIngredient = function(config, app, manager) {
this.app = app; this.app = app;
this.manager = manager; this.manager = manager;
this.name = config.name; this.name = config.name;
this.type = config.type; this.type = config.type;
this.value = config.value; this.value = config.value;
@ -39,11 +39,11 @@ HTMLIngredient.prototype.toHtml = function() {
this.type === "binaryShortString"), this.type === "binaryShortString"),
html = inline ? "" : "<div class='clearfix'>&nbsp;</div>", html = inline ? "" : "<div class='clearfix'>&nbsp;</div>",
i, m; i, m;
html += "<div class='arg-group" + (inline ? " inline-args" : "") + html += "<div class='arg-group" + (inline ? " inline-args" : "") +
(this.type === "text" ? " arg-group-text" : "") + "'><label class='arg-label' for='" + (this.type === "text" ? " arg-group-text" : "") + "'><label class='arg-label' for='" +
this.id + "'>" + this.name + "</label>"; this.id + "'>" + this.name + "</label>";
switch (this.type) { switch (this.type) {
case "string": case "string":
case "binaryString": case "binaryString":
@ -83,7 +83,7 @@ HTMLIngredient.prototype.toHtml = function() {
html += "<input type='checkbox' id='" + this.id + "'class='arg' arg-name='" + html += "<input type='checkbox' id='" + this.id + "'class='arg' arg-name='" +
this.name + "'" + (this.value ? " checked='checked' " : "") + this.name + "'" + (this.value ? " checked='checked' " : "") +
(this.disabled ? " disabled='disabled'" : "") + ">"; (this.disabled ? " disabled='disabled'" : "") + ">";
if (this.disableArgs) { if (this.disableArgs) {
this.manager.addDynamicListener("#" + this.id, "click", this.toggleDisableArgs, this); this.manager.addDynamicListener("#" + this.id, "click", this.toggleDisableArgs, this);
} }
@ -116,7 +116,7 @@ HTMLIngredient.prototype.toHtml = function() {
} }
} }
html += "</select>"; html += "</select>";
this.manager.addDynamicListener("#" + this.id, "change", this.populateOptionChange, this); this.manager.addDynamicListener("#" + this.id, "change", this.populateOptionChange, this);
break; break;
case "editableOption": case "editableOption":
@ -132,8 +132,8 @@ HTMLIngredient.prototype.toHtml = function() {
(this.disabled ? " disabled='disabled'" : "") + (this.disabled ? " disabled='disabled'" : "") +
(this.placeholder ? " placeholder='" + this.placeholder + "'" : "") + ">"; (this.placeholder ? " placeholder='" + this.placeholder + "'" : "") + ">";
html += "</div>"; html += "</div>";
this.manager.addDynamicListener("#sel-" + this.id, "change", this.editableOptionChange, this); this.manager.addDynamicListener("#sel-" + this.id, "change", this.editableOptionChange, this);
break; break;
case "text": case "text":
@ -146,7 +146,7 @@ HTMLIngredient.prototype.toHtml = function() {
break; break;
} }
html += "</div>"; html += "</div>";
return html; return html;
}; };
@ -162,10 +162,10 @@ HTMLIngredient.prototype.toggleDisableArgs = function(e) {
op = el.parentNode.parentNode, op = el.parentNode.parentNode,
args = op.querySelectorAll(".arg-group"), args = op.querySelectorAll(".arg-group"),
els; els;
for (var i = 0; i < this.disableArgs.length; i++) { for (var i = 0; i < this.disableArgs.length; i++) {
els = args[this.disableArgs[i]].querySelectorAll("input, select, button"); els = args[this.disableArgs[i]].querySelectorAll("input, select, button");
for (var j = 0; j < els.length; j++) { for (var j = 0; j < els.length; j++) {
if (els[j].getAttribute("disabled")) { if (els[j].getAttribute("disabled")) {
els[j].removeAttribute("disabled"); els[j].removeAttribute("disabled");
@ -174,7 +174,7 @@ HTMLIngredient.prototype.toggleDisableArgs = function(e) {
} }
} }
} }
this.manager.recipe.ingChange(); this.manager.recipe.ingChange();
}; };
@ -191,7 +191,7 @@ HTMLIngredient.prototype.populateOptionChange = function(e) {
target = op.querySelectorAll(".arg-group")[this.target].querySelector("input, select, textarea"); target = op.querySelectorAll(".arg-group")[this.target].querySelector("input, select, textarea");
target.value = el.childNodes[el.selectedIndex].getAttribute("populate-value"); target.value = el.childNodes[el.selectedIndex].getAttribute("populate-value");
this.manager.recipe.ingChange(); this.manager.recipe.ingChange();
}; };
@ -207,6 +207,6 @@ HTMLIngredient.prototype.editableOptionChange = function(e) {
input = select.nextSibling; input = select.nextSibling;
input.value = select.childNodes[select.selectedIndex].value; input.value = select.childNodes[select.selectedIndex].value;
this.manager.recipe.ingChange(); this.manager.recipe.ingChange();
}; };

View File

@ -14,13 +14,13 @@
var HTMLOperation = function(name, config, app, manager) { var HTMLOperation = function(name, config, app, manager) {
this.app = app; this.app = app;
this.manager = manager; this.manager = manager;
this.name = name; this.name = name;
this.description = config.description; this.description = config.description;
this.manualBake = config.manualBake || false; this.manualBake = config.manualBake || false;
this.config = config; this.config = config;
this.ingList = []; this.ingList = [];
for (var i = 0; i < config.args.length; i++) { for (var i = 0; i < config.args.length; i++) {
var ing = new HTMLIngredient(config.args[i], this.app, this.manager); var ing = new HTMLIngredient(config.args[i], this.app, this.manager);
this.ingList.push(ing); this.ingList.push(ing);
@ -45,25 +45,25 @@ HTMLOperation.REMOVE_ICON = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABwkl
*/ */
HTMLOperation.prototype.toStubHtml = function(removeIcon) { HTMLOperation.prototype.toStubHtml = function(removeIcon) {
var html = "<li class='operation'"; var html = "<li class='operation'";
if (this.description) { if (this.description) {
html += " data-container='body' data-toggle='popover' data-placement='auto right'\ html += " data-container='body' data-toggle='popover' data-placement='auto right'\
data-content=\"" + this.description + "\" data-html='true' data-trigger='hover'"; data-content=\"" + this.description + "\" data-html='true' data-trigger='hover'";
} }
html += ">" + this.name; html += ">" + this.name;
if (removeIcon) { if (removeIcon) {
html += "<img src='data:image/png;base64," + HTMLOperation.REMOVE_ICON + html += "<img src='data:image/png;base64," + HTMLOperation.REMOVE_ICON +
"' class='op-icon remove-icon'>"; "' class='op-icon remove-icon'>";
} }
if (this.description) { if (this.description) {
html += "<img src='data:image/png;base64," + HTMLOperation.INFO_ICON + "' class='op-icon'>"; html += "<img src='data:image/png;base64," + HTMLOperation.INFO_ICON + "' class='op-icon'>";
} }
html += "</li>"; html += "</li>";
return html; return html;
}; };
@ -79,15 +79,15 @@ HTMLOperation.prototype.toFullHtml = function() {
for (var i = 0; i < this.ingList.length; i++) { for (var i = 0; i < this.ingList.length; i++) {
html += this.ingList[i].toHtml(); html += this.ingList[i].toHtml();
} }
html += "<div class='recip-icons'>\ html += "<div class='recip-icons'>\
<div class='breakpoint' title='Set breakpoint' break='false'></div>\ <div class='breakpoint' title='Set breakpoint' break='false'></div>\
<div class='disable-icon recip-icon' title='Disable operation'\ <div class='disable-icon recip-icon' title='Disable operation'\
disabled='false'></div>"; disabled='false'></div>";
html += "</div>\ html += "</div>\
<div class='clearfix'>&nbsp;</div>"; <div class='clearfix'>&nbsp;</div>";
return html; return html;
}; };
@ -105,7 +105,7 @@ HTMLOperation.prototype.highlightSearchString = function(searchStr, namePos, des
this.name.slice(namePos, namePos + searchStr.length) + "</u></b>" + this.name.slice(namePos, namePos + searchStr.length) + "</u></b>" +
this.name.slice(namePos + searchStr.length); this.name.slice(namePos + searchStr.length);
} }
if (this.description && descPos >= 0) { if (this.description && descPos >= 0) {
this.description = this.description.slice(0, descPos) + "<b><u>" + this.description = this.description.slice(0, descPos) + "<b><u>" +
this.description.slice(descPos, descPos + searchStr.length) + "</u></b>" + this.description.slice(descPos, descPos + searchStr.length) + "</u></b>" +

View File

@ -12,7 +12,7 @@
var InputWaiter = function(app, manager) { var InputWaiter = function(app, manager) {
this.app = app; this.app = app;
this.manager = manager; this.manager = manager;
// Define keys that don't change the input so we don't have to autobake when they are pressed // Define keys that don't change the input so we don't have to autobake when they are pressed
this.badKeys = [ this.badKeys = [
16, //Shift 16, //Shift
@ -65,10 +65,10 @@ InputWaiter.prototype.set = function(input) {
InputWaiter.prototype.setInputInfo = function(length, lines) { InputWaiter.prototype.setInputInfo = function(length, lines) {
var width = length.toString().length; var width = length.toString().length;
width = width < 2 ? 2 : width; width = width < 2 ? 2 : width;
var lengthStr = Utils.pad(length.toString(), width, " ").replace(/ /g, "&nbsp;"); var lengthStr = Utils.pad(length.toString(), width, " ").replace(/ /g, "&nbsp;");
var linesStr = Utils.pad(lines.toString(), width, " ").replace(/ /g, "&nbsp;"); var linesStr = Utils.pad(lines.toString(), width, " ").replace(/ /g, "&nbsp;");
document.getElementById("input-info").innerHTML = "length: " + lengthStr + "<br>lines: " + linesStr; document.getElementById("input-info").innerHTML = "length: " + lengthStr + "<br>lines: " + linesStr;
}; };
@ -84,17 +84,17 @@ InputWaiter.prototype.setInputInfo = function(length, lines) {
InputWaiter.prototype.inputChange = function(e) { InputWaiter.prototype.inputChange = function(e) {
// Remove highlighting from input and output panes as the offsets might be different now // Remove highlighting from input and output panes as the offsets might be different now
this.manager.highlighter.removeHighlights(); this.manager.highlighter.removeHighlights();
// Reset recipe progress as any previous processing will be redundant now // Reset recipe progress as any previous processing will be redundant now
this.app.progress = 0; this.app.progress = 0;
// Update the input metadata info // Update the input metadata info
var inputText = this.get(), var inputText = this.get(),
lines = inputText.count("\n") + 1; lines = inputText.count("\n") + 1;
this.setInputInfo(inputText.length, lines); this.setInputInfo(inputText.length, lines);
if (this.badKeys.indexOf(e.keyCode) < 0) { if (this.badKeys.indexOf(e.keyCode) < 0) {
// Fire the statechange event as the input has been modified // Fire the statechange event as the input has been modified
window.dispatchEvent(this.manager.statechange); window.dispatchEvent(this.manager.statechange);
@ -112,7 +112,7 @@ InputWaiter.prototype.inputDragover = function(e) {
// This will be set if we're dragging an operation // This will be set if we're dragging an operation
if (e.dataTransfer.effectAllowed === "move") if (e.dataTransfer.effectAllowed === "move")
return false; return false;
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
e.target.classList.add("dropping-file"); e.target.classList.add("dropping-file");
@ -142,10 +142,10 @@ InputWaiter.prototype.inputDrop = function(e) {
// This will be set if we're dragging an operation // This will be set if we're dragging an operation
if (e.dataTransfer.effectAllowed === "move") if (e.dataTransfer.effectAllowed === "move")
return false; return false;
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
var el = e.target, var el = e.target,
file = e.dataTransfer.files[0], file = e.dataTransfer.files[0],
text = e.dataTransfer.getData("Text"), text = e.dataTransfer.getData("Text"),
@ -153,23 +153,23 @@ InputWaiter.prototype.inputDrop = function(e) {
inputCharcode = "", inputCharcode = "",
offset = 0, offset = 0,
CHUNK_SIZE = 20480; // 20KB CHUNK_SIZE = 20480; // 20KB
var setInput = function() { var setInput = function() {
if (inputCharcode.length > 100000 && this.app.autoBake_) { if (inputCharcode.length > 100000 && this.app.autoBake_) {
this.manager.controls.setAutoBake(false); this.manager.controls.setAutoBake(false);
this.app.alert("Turned off Auto Bake as the input is large", "warning", 5000); this.app.alert("Turned off Auto Bake as the input is large", "warning", 5000);
} }
this.set(inputCharcode); this.set(inputCharcode);
var recipeConfig = this.app.getRecipeConfig(); var recipeConfig = this.app.getRecipeConfig();
if (!recipeConfig[0] || recipeConfig[0].op !== "From Hex") { if (!recipeConfig[0] || recipeConfig[0].op !== "From Hex") {
recipeConfig.unshift({op:"From Hex", args:["Space"]}); recipeConfig.unshift({op:"From Hex", args:["Space"]});
this.app.setRecipeConfig(recipeConfig); this.app.setRecipeConfig(recipeConfig);
} }
el.classList.remove("loadingFile"); el.classList.remove("loadingFile");
}.bind(this); }.bind(this);
var seek = function() { var seek = function() {
if (offset >= file.size) { if (offset >= file.size) {
setInput(); setInput();
@ -179,17 +179,17 @@ InputWaiter.prototype.inputDrop = function(e) {
var slice = file.slice(offset, offset + CHUNK_SIZE); var slice = file.slice(offset, offset + CHUNK_SIZE);
reader.readAsArrayBuffer(slice); reader.readAsArrayBuffer(slice);
}; };
reader.onload = function(e) { reader.onload = function(e) {
var data = new Uint8Array(reader.result); var data = new Uint8Array(reader.result);
inputCharcode += Utils.toHexFast(data); inputCharcode += Utils.toHexFast(data);
offset += CHUNK_SIZE; offset += CHUNK_SIZE;
seek(); seek();
}; };
el.classList.remove("dropping-file"); el.classList.remove("dropping-file");
if (file) { if (file) {
el.classList.add("loadingFile"); el.classList.add("loadingFile");
seek(); seek();

View File

@ -10,7 +10,7 @@
*/ */
var Manager = function(app) { var Manager = function(app) {
this.app = app; this.app = app;
// Define custom events // Define custom events
/** /**
* @event Manager#appstart * @event Manager#appstart
@ -32,7 +32,7 @@ var Manager = function(app) {
* @event Manager#statechange * @event Manager#statechange
*/ */
this.statechange = new CustomEvent("statechange", {bubbles: true}); this.statechange = new CustomEvent("statechange", {bubbles: true});
// Define Waiter objects to handle various areas // Define Waiter objects to handle various areas
this.window = new WindowWaiter(this.app); this.window = new WindowWaiter(this.app);
this.controls = new ControlsWaiter(this.app, this); this.controls = new ControlsWaiter(this.app, this);
@ -43,10 +43,10 @@ var Manager = function(app) {
this.options = new OptionsWaiter(this.app); this.options = new OptionsWaiter(this.app);
this.highlighter = new HighlighterWaiter(this.app); this.highlighter = new HighlighterWaiter(this.app);
this.seasonal = new SeasonalWaiter(this.app, this); this.seasonal = new SeasonalWaiter(this.app, this);
// Object to store dynamic handlers to fire on elements that may not exist yet // Object to store dynamic handlers to fire on elements that may not exist yet
this.dynamicHandlers = {}; this.dynamicHandlers = {};
this.initialiseEventListeners(); this.initialiseEventListeners();
}; };
@ -71,7 +71,7 @@ Manager.prototype.initialiseEventListeners = function() {
window.addEventListener("focus", this.window.windowFocus.bind(this.window)); window.addEventListener("focus", this.window.windowFocus.bind(this.window));
window.addEventListener("statechange", this.app.stateChange.bind(this.app)); window.addEventListener("statechange", this.app.stateChange.bind(this.app));
window.addEventListener("popstate", this.app.popState.bind(this.app)); window.addEventListener("popstate", this.app.popState.bind(this.app));
// Controls // Controls
document.getElementById("bake").addEventListener("click", this.controls.bakeClick.bind(this.controls)); document.getElementById("bake").addEventListener("click", this.controls.bakeClick.bind(this.controls));
document.getElementById("auto-bake").addEventListener("change", this.controls.autoBakeChange.bind(this.controls)); document.getElementById("auto-bake").addEventListener("change", this.controls.autoBakeChange.bind(this.controls));
@ -88,7 +88,7 @@ Manager.prototype.initialiseEventListeners = function() {
document.getElementById("load-button").addEventListener("click", this.controls.loadButtonClick.bind(this.controls)); document.getElementById("load-button").addEventListener("click", this.controls.loadButtonClick.bind(this.controls));
document.getElementById("support").addEventListener("click", this.controls.supportButtonClick.bind(this.controls)); document.getElementById("support").addEventListener("click", this.controls.supportButtonClick.bind(this.controls));
this.addMultiEventListener("#save-text", "keyup paste", this.controls.saveTextChange, this.controls); this.addMultiEventListener("#save-text", "keyup paste", this.controls.saveTextChange, this.controls);
// Operations // Operations
this.addMultiEventListener("#search", "keyup paste search", this.ops.searchOperations, this.ops); this.addMultiEventListener("#search", "keyup paste search", this.ops.searchOperations, this.ops);
this.addDynamicListener(".op-list li.operation", "dblclick", this.ops.operationDblclick, this.ops); this.addDynamicListener(".op-list li.operation", "dblclick", this.ops.operationDblclick, this.ops);
@ -99,7 +99,7 @@ Manager.prototype.initialiseEventListeners = function() {
this.addDynamicListener(".op-list .op-icon", "mouseleave", this.ops.opIconMouseleave, this.ops); this.addDynamicListener(".op-list .op-icon", "mouseleave", this.ops.opIconMouseleave, this.ops);
this.addDynamicListener(".op-list", "oplistcreate", this.ops.opListCreate, this.ops); this.addDynamicListener(".op-list", "oplistcreate", this.ops.opListCreate, this.ops);
this.addDynamicListener("li.operation", "operationadd", this.recipe.opAdd.bind(this.recipe)); this.addDynamicListener("li.operation", "operationadd", this.recipe.opAdd.bind(this.recipe));
// Recipe // Recipe
this.addDynamicListener(".arg", "keyup", this.recipe.ingChange, this.recipe); this.addDynamicListener(".arg", "keyup", this.recipe.ingChange, this.recipe);
this.addDynamicListener(".arg", "change", this.recipe.ingChange, this.recipe); this.addDynamicListener(".arg", "change", this.recipe.ingChange, this.recipe);
@ -109,7 +109,7 @@ Manager.prototype.initialiseEventListeners = function() {
this.addDynamicListener("#rec-list li.operation > div", "dblclick", this.recipe.operationChildDblclick, this.recipe); this.addDynamicListener("#rec-list li.operation > div", "dblclick", this.recipe.operationChildDblclick, this.recipe);
this.addDynamicListener("#rec-list .input-group .dropdown-menu a", "click", this.recipe.dropdownToggleClick, this.recipe); this.addDynamicListener("#rec-list .input-group .dropdown-menu a", "click", this.recipe.dropdownToggleClick, this.recipe);
this.addDynamicListener("#rec-list", "operationremove", this.recipe.opRemove.bind(this.recipe)); this.addDynamicListener("#rec-list", "operationremove", this.recipe.opRemove.bind(this.recipe));
// Input // Input
this.addMultiEventListener("#input-text", "keyup paste", this.input.inputChange, this.input); this.addMultiEventListener("#input-text", "keyup paste", this.input.inputChange, this.input);
document.getElementById("reset-layout").addEventListener("click", this.app.resetLayout.bind(this.app)); document.getElementById("reset-layout").addEventListener("click", this.app.resetLayout.bind(this.app));
@ -121,7 +121,7 @@ Manager.prototype.initialiseEventListeners = function() {
document.getElementById("input-text").addEventListener("mouseup", this.highlighter.inputMouseup.bind(this.highlighter)); document.getElementById("input-text").addEventListener("mouseup", this.highlighter.inputMouseup.bind(this.highlighter));
document.getElementById("input-text").addEventListener("mousemove", this.highlighter.inputMousemove.bind(this.highlighter)); document.getElementById("input-text").addEventListener("mousemove", this.highlighter.inputMousemove.bind(this.highlighter));
this.addMultiEventListener("#input-text", "mousedown dblclick select", this.highlighter.inputMousedown, this.highlighter); this.addMultiEventListener("#input-text", "mousedown dblclick select", this.highlighter.inputMousedown, this.highlighter);
// Output // Output
document.getElementById("save-to-file").addEventListener("click", this.output.saveClick.bind(this.output)); document.getElementById("save-to-file").addEventListener("click", this.output.saveClick.bind(this.output));
document.getElementById("switch").addEventListener("click", this.output.switchClick.bind(this.output)); document.getElementById("switch").addEventListener("click", this.output.switchClick.bind(this.output));
@ -134,7 +134,7 @@ Manager.prototype.initialiseEventListeners = function() {
document.getElementById("output-html").addEventListener("mousemove", this.highlighter.outputHtmlMousemove.bind(this.highlighter)); document.getElementById("output-html").addEventListener("mousemove", this.highlighter.outputHtmlMousemove.bind(this.highlighter));
this.addMultiEventListener("#output-text", "mousedown dblclick select", this.highlighter.outputMousedown, this.highlighter); this.addMultiEventListener("#output-text", "mousedown dblclick select", this.highlighter.outputMousedown, this.highlighter);
this.addMultiEventListener("#output-html", "mousedown dblclick select", this.highlighter.outputHtmlMousedown, this.highlighter); this.addMultiEventListener("#output-html", "mousedown dblclick select", this.highlighter.outputHtmlMousedown, this.highlighter);
// Options // Options
document.getElementById("options").addEventListener("click", this.options.optionsClick.bind(this.options)); document.getElementById("options").addEventListener("click", this.options.optionsClick.bind(this.options));
document.getElementById("reset-options").addEventListener("click", this.options.resetOptionsClick.bind(this.options)); document.getElementById("reset-options").addEventListener("click", this.options.resetOptionsClick.bind(this.options));
@ -143,7 +143,7 @@ Manager.prototype.initialiseEventListeners = function() {
this.addDynamicListener(".option-item input[type=number]", "keyup", this.options.numberChange, this.options); this.addDynamicListener(".option-item input[type=number]", "keyup", this.options.numberChange, this.options);
this.addDynamicListener(".option-item input[type=number]", "change", this.options.numberChange, this.options); this.addDynamicListener(".option-item input[type=number]", "change", this.options.numberChange, this.options);
this.addDynamicListener(".option-item select", "change", this.options.selectChange, this.options); this.addDynamicListener(".option-item select", "change", this.options.selectChange, this.options);
// Misc // Misc
document.getElementById("alert-close").addEventListener("click", this.app.alertCloseClick.bind(this.app)); document.getElementById("alert-close").addEventListener("click", this.app.alertCloseClick.bind(this.app));
}; };
@ -231,7 +231,7 @@ Manager.prototype.addDynamicListener = function(selector, eventType, callback, s
selector: selector, selector: selector,
callback: callback.bind(scope || this) callback: callback.bind(scope || this)
}; };
if (this.dynamicHandlers.hasOwnProperty(eventType)) { if (this.dynamicHandlers.hasOwnProperty(eventType)) {
// Listener already exists, add new handler to the appropriate list // Listener already exists, add new handler to the appropriate list
this.dynamicHandlers[eventType].push(eventConfig); this.dynamicHandlers[eventType].push(eventConfig);
@ -256,7 +256,7 @@ Manager.prototype.dynamicListenerHandler = function(e) {
e.target.mozMatchesSelector || e.target.mozMatchesSelector ||
e.target.msMatchesSelector || e.target.msMatchesSelector ||
e.target.oMatchesSelector; e.target.oMatchesSelector;
for (var i = 0; i < handlers.length; i++) { for (var i = 0; i < handlers.length; i++) {
if (matches && e.target[matches.name](handlers[i].selector)) { if (matches && e.target[matches.name](handlers[i].selector)) {
handlers[i].callback(e); handlers[i].callback(e);

View File

@ -14,7 +14,7 @@
var OperationsWaiter = function(app, manager) { var OperationsWaiter = function(app, manager) {
this.app = app; this.app = app;
this.manager = manager; this.manager = manager;
this.options = {}; this.options = {};
this.removeIntent = false; this.removeIntent = false;
}; };
@ -28,7 +28,7 @@ var OperationsWaiter = function(app, manager) {
*/ */
OperationsWaiter.prototype.searchOperations = function(e) { OperationsWaiter.prototype.searchOperations = function(e) {
var ops, selected; var ops, selected;
if (e.type === "search") { // Search if (e.type === "search") { // Search
e.preventDefault(); e.preventDefault();
ops = document.querySelectorAll("#search-results li"); ops = document.querySelectorAll("#search-results li");
@ -40,7 +40,7 @@ OperationsWaiter.prototype.searchOperations = function(e) {
} }
} }
} }
if (e.keyCode === 13) { // Return if (e.keyCode === 13) { // Return
e.preventDefault(); e.preventDefault();
} else if (e.keyCode === 40) { // Down } else if (e.keyCode === 40) { // Down
@ -69,21 +69,21 @@ OperationsWaiter.prototype.searchOperations = function(e) {
var searchResultsEl = document.getElementById("search-results"), var searchResultsEl = document.getElementById("search-results"),
el = e.target, el = e.target,
str = el.value; str = el.value;
while (searchResultsEl.firstChild) { while (searchResultsEl.firstChild) {
$(searchResultsEl.firstChild).popover("destroy"); $(searchResultsEl.firstChild).popover("destroy");
searchResultsEl.removeChild(searchResultsEl.firstChild); searchResultsEl.removeChild(searchResultsEl.firstChild);
} }
$("#categories .in").collapse("hide"); $("#categories .in").collapse("hide");
if (str) { if (str) {
var matchedOps = this.filterOperations(str, true), var matchedOps = this.filterOperations(str, true),
matchedOpsHtml = ""; matchedOpsHtml = "";
for (var i = 0; i < matchedOps.length; i++) { for (var i = 0; i < matchedOps.length; i++) {
matchedOpsHtml += matchedOps[i].toStubHtml(); matchedOpsHtml += matchedOps[i].toStubHtml();
} }
searchResultsEl.innerHTML = matchedOpsHtml; searchResultsEl.innerHTML = matchedOpsHtml;
searchResultsEl.dispatchEvent(this.manager.oplistcreate); searchResultsEl.dispatchEvent(this.manager.oplistcreate);
} }
@ -102,20 +102,20 @@ OperationsWaiter.prototype.searchOperations = function(e) {
OperationsWaiter.prototype.filterOperations = function(searchStr, highlight) { OperationsWaiter.prototype.filterOperations = function(searchStr, highlight) {
var matchedOps = [], var matchedOps = [],
matchedDescs = []; matchedDescs = [];
searchStr = searchStr.toLowerCase(); searchStr = searchStr.toLowerCase();
for (var opName in this.app.operations) { for (var opName in this.app.operations) {
var op = this.app.operations[opName], var op = this.app.operations[opName],
namePos = opName.toLowerCase().indexOf(searchStr), namePos = opName.toLowerCase().indexOf(searchStr),
descPos = op.description.toLowerCase().indexOf(searchStr); descPos = op.description.toLowerCase().indexOf(searchStr);
if (namePos >= 0 || descPos >= 0) { if (namePos >= 0 || descPos >= 0) {
var operation = new HTMLOperation(opName, this.app.operations[opName], this.app, this.manager); var operation = new HTMLOperation(opName, this.app.operations[opName], this.app, this.manager);
if (highlight) { if (highlight) {
operation.highlightSearchString(searchStr, namePos, descPos); operation.highlightSearchString(searchStr, namePos, descPos);
} }
if (namePos < 0) { if (namePos < 0) {
matchedOps.push(operation); matchedOps.push(operation);
} else { } else {
@ -123,7 +123,7 @@ OperationsWaiter.prototype.filterOperations = function(searchStr, highlight) {
} }
} }
} }
return matchedDescs.concat(matchedOps); return matchedDescs.concat(matchedOps);
}; };
@ -165,7 +165,7 @@ OperationsWaiter.prototype.opListCreate = function(e) {
*/ */
OperationsWaiter.prototype.operationDblclick = function(e) { OperationsWaiter.prototype.operationDblclick = function(e) {
var li = e.target; var li = e.target;
this.manager.recipe.addOperation(li.textContent); this.manager.recipe.addOperation(li.textContent);
this.app.autoBake(); this.app.autoBake();
}; };
@ -180,23 +180,23 @@ OperationsWaiter.prototype.operationDblclick = function(e) {
OperationsWaiter.prototype.editFavouritesClick = function(e) { OperationsWaiter.prototype.editFavouritesClick = function(e) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
// Add favourites to modal // Add favourites to modal
var favCat = this.app.categories.filter(function(c) { var favCat = this.app.categories.filter(function(c) {
return c.name === "Favourites"; return c.name === "Favourites";
})[0]; })[0];
var html = ""; var html = "";
for (var i = 0; i < favCat.ops.length; i++) { for (var i = 0; i < favCat.ops.length; i++) {
var opName = favCat.ops[i]; var opName = favCat.ops[i];
var operation = new HTMLOperation(opName, this.app.operations[opName], this.app, this.manager); var operation = new HTMLOperation(opName, this.app.operations[opName], this.app, this.manager);
html += operation.toStubHtml(true); html += operation.toStubHtml(true);
} }
var editFavouritesList = document.getElementById("edit-favourites-list"); var editFavouritesList = document.getElementById("edit-favourites-list");
editFavouritesList.innerHTML = html; editFavouritesList.innerHTML = html;
this.removeIntent = false; this.removeIntent = false;
var editableList = Sortable.create(editFavouritesList, { var editableList = Sortable.create(editFavouritesList, {
filter: ".remove-icon", filter: ".remove-icon",
onFilter: function (evt) { onFilter: function (evt) {
@ -210,15 +210,15 @@ OperationsWaiter.prototype.editFavouritesClick = function(e) {
if (this.removeIntent) evt.item.remove(); if (this.removeIntent) evt.item.remove();
}.bind(this), }.bind(this),
}); });
Sortable.utils.on(editFavouritesList, "dragleave", function() { Sortable.utils.on(editFavouritesList, "dragleave", function() {
this.removeIntent = true; this.removeIntent = true;
}.bind(this)); }.bind(this));
Sortable.utils.on(editFavouritesList, "dragover", function() { Sortable.utils.on(editFavouritesList, "dragover", function() {
this.removeIntent = false; this.removeIntent = false;
}.bind(this)); }.bind(this));
$("#edit-favourites-list [data-toggle=popover]").popover(); $("#edit-favourites-list [data-toggle=popover]").popover();
$("#favourites-modal").modal(); $("#favourites-modal").modal();
}; };
@ -231,7 +231,7 @@ OperationsWaiter.prototype.editFavouritesClick = function(e) {
OperationsWaiter.prototype.saveFavouritesClick = function() { OperationsWaiter.prototype.saveFavouritesClick = function() {
var favouritesList = [], var favouritesList = [],
favs = document.querySelectorAll("#edit-favourites-list li"); favs = document.querySelectorAll("#edit-favourites-list li");
for (var i = 0; i < favs.length; i++) { for (var i = 0; i < favs.length; i++) {
favouritesList.push(favs[i].textContent); favouritesList.push(favs[i].textContent);
} }
@ -276,7 +276,7 @@ OperationsWaiter.prototype.opIconMouseover = function(e) {
OperationsWaiter.prototype.opIconMouseleave = function(e) { OperationsWaiter.prototype.opIconMouseleave = function(e) {
var opEl = e.target.parentNode, var opEl = e.target.parentNode,
toEl = e.toElement || e.relatedElement; toEl = e.toElement || e.relatedElement;
if (e.target.getAttribute("data-toggle") === "popover" && toEl === opEl) { if (e.target.getAttribute("data-toggle") === "popover" && toEl === opEl) {
$(opEl).popover("show"); $(opEl).popover("show");
} }

View File

@ -23,11 +23,11 @@ OptionsWaiter.prototype.load = function(options) {
size: "small", size: "small",
animate: false, animate: false,
}); });
for (var option in options) { for (var option in options) {
this.app.options[option] = options[option]; this.app.options[option] = options[option];
} }
// Set options to match object // Set options to match object
var cboxes = document.querySelectorAll("#options-body input[type=checkbox]"); var cboxes = document.querySelectorAll("#options-body input[type=checkbox]");
for (var i = 0; i < cboxes.length; i++) { for (var i = 0; i < cboxes.length; i++) {
@ -39,7 +39,7 @@ OptionsWaiter.prototype.load = function(options) {
nboxes[i].value = this.app.options[nboxes[i].getAttribute("option")]; nboxes[i].value = this.app.options[nboxes[i].getAttribute("option")];
nboxes[i].dispatchEvent(new CustomEvent("change", {bubbles: true})); nboxes[i].dispatchEvent(new CustomEvent("change", {bubbles: true}));
} }
var selects = document.querySelectorAll("#options-body select"); var selects = document.querySelectorAll("#options-body select");
for (i = 0; i < selects.length; i++) { for (i = 0; i < selects.length; i++) {
selects[i].value = this.app.options[selects[i].getAttribute("option")]; selects[i].value = this.app.options[selects[i].getAttribute("option")];
@ -76,7 +76,7 @@ OptionsWaiter.prototype.resetOptionsClick = function() {
OptionsWaiter.prototype.switchChange = function(e, state) { OptionsWaiter.prototype.switchChange = function(e, state) {
var el = e.target, var el = e.target,
option = el.getAttribute("option"); option = el.getAttribute("option");
this.app.options[option] = state; this.app.options[option] = state;
localStorage.setItem("options", JSON.stringify(this.app.options)); localStorage.setItem("options", JSON.stringify(this.app.options));
}; };
@ -91,7 +91,7 @@ OptionsWaiter.prototype.switchChange = function(e, state) {
OptionsWaiter.prototype.numberChange = function(e) { OptionsWaiter.prototype.numberChange = function(e) {
var el = e.target, var el = e.target,
option = el.getAttribute("option"); option = el.getAttribute("option");
this.app.options[option] = parseInt(el.value, 10); this.app.options[option] = parseInt(el.value, 10);
localStorage.setItem("options", JSON.stringify(this.app.options)); localStorage.setItem("options", JSON.stringify(this.app.options));
}; };
@ -106,7 +106,7 @@ OptionsWaiter.prototype.numberChange = function(e) {
OptionsWaiter.prototype.selectChange = function(e) { OptionsWaiter.prototype.selectChange = function(e) {
var el = e.target, var el = e.target,
option = el.getAttribute("option"); option = el.getAttribute("option");
this.app.options[option] = el.value; this.app.options[option] = el.value;
localStorage.setItem("options", JSON.stringify(this.app.options)); localStorage.setItem("options", JSON.stringify(this.app.options));
}; };
@ -121,7 +121,7 @@ OptionsWaiter.prototype.setWordWrap = function() {
document.getElementById("output-html").classList.remove("word-wrap"); document.getElementById("output-html").classList.remove("word-wrap");
document.getElementById("input-highlighter").classList.remove("word-wrap"); document.getElementById("input-highlighter").classList.remove("word-wrap");
document.getElementById("output-highlighter").classList.remove("word-wrap"); document.getElementById("output-highlighter").classList.remove("word-wrap");
if (!this.app.options.wordWrap) { if (!this.app.options.wordWrap) {
document.getElementById("input-text").classList.add("word-wrap"); document.getElementById("input-text").classList.add("word-wrap");
document.getElementById("output-text").classList.add("word-wrap"); document.getElementById("output-text").classList.add("word-wrap");

View File

@ -43,10 +43,10 @@ OutputWaiter.prototype.set = function(dataStr, type, duration) {
outputHtml.style.display = "block"; outputHtml.style.display = "block";
outputHighlighter.display = "none"; outputHighlighter.display = "none";
inputHighlighter.display = "none"; inputHighlighter.display = "none";
outputText.value = ""; outputText.value = "";
outputHtml.innerHTML = dataStr; outputHtml.innerHTML = dataStr;
// Execute script sections // Execute script sections
var scriptElements = outputHtml.querySelectorAll("script"); var scriptElements = outputHtml.querySelectorAll("script");
for (var i = 0; i < scriptElements.length; i++) { for (var i = 0; i < scriptElements.length; i++) {
@ -61,11 +61,11 @@ OutputWaiter.prototype.set = function(dataStr, type, duration) {
outputHtml.style.display = "none"; outputHtml.style.display = "none";
outputHighlighter.display = "block"; outputHighlighter.display = "block";
inputHighlighter.display = "block"; inputHighlighter.display = "block";
outputText.value = Utils.printable(dataStr, true); outputText.value = Utils.printable(dataStr, true);
outputHtml.innerHTML = ""; outputHtml.innerHTML = "";
} }
this.manager.highlighter.removeHighlights(); this.manager.highlighter.removeHighlights();
var lines = dataStr.count("\n") + 1; var lines = dataStr.count("\n") + 1;
this.setOutputInfo(dataStr.length, lines, duration); this.setOutputInfo(dataStr.length, lines, duration);
@ -82,11 +82,11 @@ OutputWaiter.prototype.set = function(dataStr, type, duration) {
OutputWaiter.prototype.setOutputInfo = function(length, lines, duration) { OutputWaiter.prototype.setOutputInfo = function(length, lines, duration) {
var width = length.toString().length; var width = length.toString().length;
width = width < 4 ? 4 : width; width = width < 4 ? 4 : width;
var lengthStr = Utils.pad(length.toString(), width, " ").replace(/ /g, "&nbsp;"); var lengthStr = Utils.pad(length.toString(), width, " ").replace(/ /g, "&nbsp;");
var linesStr = Utils.pad(lines.toString(), width, " ").replace(/ /g, "&nbsp;"); var linesStr = Utils.pad(lines.toString(), width, " ").replace(/ /g, "&nbsp;");
var timeStr = Utils.pad(duration.toString() + "ms", width, " ").replace(/ /g, "&nbsp;"); var timeStr = Utils.pad(duration.toString() + "ms", width, " ").replace(/ /g, "&nbsp;");
document.getElementById("output-info").innerHTML = "time: " + timeStr + document.getElementById("output-info").innerHTML = "time: " + timeStr +
"<br>length: " + lengthStr + "<br>length: " + lengthStr +
"<br>lines: " + linesStr; "<br>lines: " + linesStr;
@ -105,7 +105,7 @@ OutputWaiter.prototype.adjustWidth = function() {
switchIO = document.getElementById("switch"), switchIO = document.getElementById("switch"),
undoSwitch = document.getElementById("undo-switch"), undoSwitch = document.getElementById("undo-switch"),
maximiseOutput = document.getElementById("maximise-output"); maximiseOutput = document.getElementById("maximise-output");
if (output.clientWidth < 680) { if (output.clientWidth < 680) {
saveToFile.childNodes[1].nodeValue = ""; saveToFile.childNodes[1].nodeValue = "";
switchIO.childNodes[1].nodeValue = ""; switchIO.childNodes[1].nodeValue = "";
@ -128,16 +128,16 @@ OutputWaiter.prototype.adjustWidth = function() {
OutputWaiter.prototype.saveClick = function() { OutputWaiter.prototype.saveClick = function() {
var data = Utils.toBase64(this.app.dishStr), var data = Utils.toBase64(this.app.dishStr),
filename = window.prompt("Please enter a filename:", "download.dat"); filename = window.prompt("Please enter a filename:", "download.dat");
if (filename) { if (filename) {
var el = document.createElement("a"); var el = document.createElement("a");
el.setAttribute("href", "data:application/octet-stream;base64;charset=utf-8," + data); el.setAttribute("href", "data:application/octet-stream;base64;charset=utf-8," + data);
el.setAttribute("download", filename); el.setAttribute("download", filename);
// Firefox requires that the element be added to the DOM before it can be clicked // Firefox requires that the element be added to the DOM before it can be clicked
el.style.display = "none"; el.style.display = "none";
document.body.appendChild(el); document.body.appendChild(el);
el.click(); el.click();
el.remove(); el.remove();
} }

View File

@ -23,8 +23,8 @@ var RecipeWaiter = function(app, manager) {
*/ */
RecipeWaiter.prototype.initialiseOperationDragNDrop = function() { RecipeWaiter.prototype.initialiseOperationDragNDrop = function() {
var recList = document.getElementById("rec-list"); var recList = document.getElementById("rec-list");
// Recipe list // Recipe list
Sortable.create(recList, { Sortable.create(recList, {
group: "recipe", group: "recipe",
@ -42,11 +42,11 @@ RecipeWaiter.prototype.initialiseOperationDragNDrop = function() {
} }
}.bind(this) }.bind(this)
}); });
Sortable.utils.on(recList, "dragover", function() { Sortable.utils.on(recList, "dragover", function() {
this.removeIntent = false; this.removeIntent = false;
}.bind(this)); }.bind(this));
Sortable.utils.on(recList, "dragleave", function() { Sortable.utils.on(recList, "dragleave", function() {
this.removeIntent = true; this.removeIntent = true;
this.app.progress = 0; this.app.progress = 0;
@ -58,7 +58,7 @@ RecipeWaiter.prototype.initialiseOperationDragNDrop = function() {
this.removeIntent = !recList.contains(target); this.removeIntent = !recList.contains(target);
}.bind(this)); }.bind(this));
// Favourites category // Favourites category
document.querySelector("#categories a").addEventListener("dragover", this.favDragover.bind(this)); document.querySelector("#categories a").addEventListener("dragover", this.favDragover.bind(this));
document.querySelector("#categories a").addEventListener("dragleave", this.favDragleave.bind(this)); document.querySelector("#categories a").addEventListener("dragleave", this.favDragleave.bind(this));
@ -106,16 +106,16 @@ RecipeWaiter.prototype.opSortEnd = function(evt) {
} }
return; return;
} }
// Reinitialise the popover on the original element in the ops list because for some reason it // Reinitialise the popover on the original element in the ops list because for some reason it
// gets destroyed and recreated. // gets destroyed and recreated.
$(evt.clone).popover(); $(evt.clone).popover();
$(evt.clone).children("[data-toggle=popover]").popover(); $(evt.clone).children("[data-toggle=popover]").popover();
if (evt.item.parentNode.id !== "rec-list") { if (evt.item.parentNode.id !== "rec-list") {
return; return;
} }
this.buildRecipeOperation(evt.item); this.buildRecipeOperation(evt.item);
evt.item.dispatchEvent(this.manager.operationadd); evt.item.dispatchEvent(this.manager.operationadd);
}; };
@ -131,7 +131,7 @@ RecipeWaiter.prototype.opSortEnd = function(evt) {
RecipeWaiter.prototype.favDragover = function(e) { RecipeWaiter.prototype.favDragover = function(e) {
if (e.dataTransfer.effectAllowed !== "move") if (e.dataTransfer.effectAllowed !== "move")
return false; return false;
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
if (e.target.className && e.target.className.indexOf("category-title") > -1) { if (e.target.className && e.target.className.indexOf("category-title") > -1) {
@ -170,7 +170,7 @@ RecipeWaiter.prototype.favDrop = function(e) {
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
e.target.classList.remove("favourites-hover"); e.target.classList.remove("favourites-hover");
var opName = e.dataTransfer.getData("Text"); var opName = e.dataTransfer.getData("Text");
this.app.addFavourite(opName); this.app.addFavourite(opName);
}; };
@ -195,7 +195,7 @@ RecipeWaiter.prototype.ingChange = function() {
*/ */
RecipeWaiter.prototype.disableClick = function(e) { RecipeWaiter.prototype.disableClick = function(e) {
var icon = e.target; var icon = e.target;
if (icon.getAttribute("disabled") === "false") { if (icon.getAttribute("disabled") === "false") {
icon.setAttribute("disabled", "true"); icon.setAttribute("disabled", "true");
icon.classList.add("disable-icon-selected"); icon.classList.add("disable-icon-selected");
@ -205,7 +205,7 @@ RecipeWaiter.prototype.disableClick = function(e) {
icon.classList.remove("disable-icon-selected"); icon.classList.remove("disable-icon-selected");
icon.parentNode.parentNode.classList.remove("disabled"); icon.parentNode.parentNode.classList.remove("disabled");
} }
this.app.progress = 0; this.app.progress = 0;
window.dispatchEvent(this.manager.statechange); window.dispatchEvent(this.manager.statechange);
}; };
@ -228,7 +228,7 @@ RecipeWaiter.prototype.breakpointClick = function(e) {
bp.setAttribute("break", "false"); bp.setAttribute("break", "false");
bp.classList.remove("breakpoint-selected"); bp.classList.remove("breakpoint-selected");
} }
window.dispatchEvent(this.manager.statechange); window.dispatchEvent(this.manager.statechange);
}; };
@ -267,13 +267,13 @@ RecipeWaiter.prototype.operationChildDblclick = function(e) {
RecipeWaiter.prototype.getConfig = function() { RecipeWaiter.prototype.getConfig = function() {
var config = [], ingredients, ingList, disabled, bp, item, var config = [], ingredients, ingList, disabled, bp, item,
operations = document.querySelectorAll("#rec-list li.operation"); operations = document.querySelectorAll("#rec-list li.operation");
for (var i = 0; i < operations.length; i++) { for (var i = 0; i < operations.length; i++) {
ingredients = []; ingredients = [];
disabled = operations[i].querySelector(".disable-icon"); disabled = operations[i].querySelector(".disable-icon");
bp = operations[i].querySelector(".breakpoint"); bp = operations[i].querySelector(".breakpoint");
ingList = operations[i].querySelectorAll(".arg"); ingList = operations[i].querySelectorAll(".arg");
for (var j = 0; j < ingList.length; j++) { for (var j = 0; j < ingList.length; j++) {
if (ingList[j].getAttribute("type") === "checkbox") { if (ingList[j].getAttribute("type") === "checkbox") {
// checkbox // checkbox
@ -289,23 +289,23 @@ RecipeWaiter.prototype.getConfig = function() {
ingredients[j] = ingList[j].value; ingredients[j] = ingList[j].value;
} }
} }
item = { item = {
op: operations[i].querySelector(".arg-title").textContent, op: operations[i].querySelector(".arg-title").textContent,
args: ingredients args: ingredients
}; };
if (disabled && disabled.getAttribute("disabled") === "true") { if (disabled && disabled.getAttribute("disabled") === "true") {
item.disabled = true; item.disabled = true;
} }
if (bp && bp.getAttribute("break") === "true") { if (bp && bp.getAttribute("break") === "true") {
item.breakpoint = true; item.breakpoint = true;
} }
config.push(item); config.push(item);
} }
return config; return config;
}; };
@ -337,11 +337,11 @@ RecipeWaiter.prototype.buildRecipeOperation = function(el) {
var opName = el.textContent; var opName = el.textContent;
var op = new HTMLOperation(opName, this.app.operations[opName], this.app, this.manager); var op = new HTMLOperation(opName, this.app.operations[opName], this.app, this.manager);
el.innerHTML = op.toFullHtml(); el.innerHTML = op.toFullHtml();
if (this.app.operations[opName].flowControl) { if (this.app.operations[opName].flowControl) {
el.classList.add("flow-control-op"); el.classList.add("flow-control-op");
} }
// Disable auto-bake if this is a manual op - this should be moved to the 'operationadd' // Disable auto-bake if this is a manual op - this should be moved to the 'operationadd'
// handler after event restructuring // handler after event restructuring
if (op.manualBake && this.app.autoBake_) { if (op.manualBake && this.app.autoBake_) {
@ -359,12 +359,12 @@ RecipeWaiter.prototype.buildRecipeOperation = function(el) {
*/ */
RecipeWaiter.prototype.addOperation = function(name) { RecipeWaiter.prototype.addOperation = function(name) {
var item = document.createElement("li"); var item = document.createElement("li");
item.classList.add("operation"); item.classList.add("operation");
item.innerHTML = name; item.innerHTML = name;
this.buildRecipeOperation(item); this.buildRecipeOperation(item);
document.getElementById("rec-list").appendChild(item); document.getElementById("rec-list").appendChild(item);
item.dispatchEvent(this.manager.operationadd); item.dispatchEvent(this.manager.operationadd);
return item; return item;
}; };
@ -393,7 +393,7 @@ RecipeWaiter.prototype.clearRecipe = function() {
RecipeWaiter.prototype.dropdownToggleClick = function(e) { RecipeWaiter.prototype.dropdownToggleClick = function(e) {
var el = e.target, var el = e.target,
button = el.parentNode.parentNode.previousSibling; button = el.parentNode.parentNode.previousSibling;
button.innerHTML = el.textContent + " <span class='caret'></span>"; button.innerHTML = el.textContent + " <span class='caret'></span>";
this.ingChange(); this.ingChange();
}; };

View File

@ -227,7 +227,7 @@ SeasonalWaiter.treeWalk = (function() {
while (node && node !== parent) { while (node && node !== parent) {
if (allNodes || node.nodeType === 1) { if (allNodes || node.nodeType === 1) {
if (fn(node) === false) { if (fn(node) === false) {
return(false); return false;
} }
} }
// If it's an element && // If it's an element &&

View File

@ -22,7 +22,7 @@ var main = function() {
"Entropy", "Entropy",
"Fork" "Fork"
]; ];
var defaultOptions = { var defaultOptions = {
updateUrl : true, updateUrl : true,
showHighlighter : true, showHighlighter : true,