Unpack and Beautify JavaScript

Those familiar with Dean Edward’s packer will have seen JavaScript files starting with eval(function(p,a,c,k,e,r){. Most of these files contain a single such “pack”. If you want to study these files, you’ll want to unpack them with, for example, the JS Beautifier.

Unfortunately, if a JavaScript file contains more than one pack, or contains code before, after, or between the packs, the JS Beautifier won’t work. Recently, I had to use a JavaScript toolkit whose JavaScript files contain many packs, so I wrote a little function to unpack and beautify these exceptional cases. See it in action:

function unpack_and_beautify(value) {
var position = 0,
open_string = "eval(function(",
open_index = -1,
close_string = "'.split('|'),0,{}))",
close_index = -1,
close_length = close_string.length,
string = '',
pack;

while (true) {
open_index = value.indexOf(open_string, open_index + 1);
close_index = value.indexOf(close_string, close_index + 1);
if (open_index == -1 || close_index == -1) {
string += value.substring(position, value.length);
break;
}
else {
string += value.substring(position, open_index);
pack = value.substring(open_index, close_index + close_length);
try {
eval("var tmp = String" + pack.substring(4));
string += tmp;
}
catch (e) {
window.console && console.log && console.log(e, pack);
string += pack;
}
position = close_index + close_length;
}
};
return js_beautify(string, {
indent_size: 2,
space_after_anon_function: true,
});
}

Beautify