#! /usr/bin/env node // -*- js -*- "use strict"; var fs = require("fs"); var info = require("../package.json"); var path = require("path"); var program = require("commander"); var UglifyJS = require("../tools/node"); var files = {}; var options = { compress: false, mangle: false }; program._name = info.name; program.version(info.version); program.parseArgv = program.parse; program.parse = undefined; program.option("-p, --parse ", "Specify parser options.", parseJS("parse", true)); program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parseJS("compress", true)); program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parseJS("mangle", true)); program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parseJS("mangle-props", true)); program.option("-b, --beautify [options]", "Beautify output/specify output options.", parseJS("beautify", true)); program.option("-o, --output ", "Output file (default STDOUT)."); program.option("--comments [filter]", "Preserve copyright comments in the output."); program.option("--config-file ", "Read minify() options from JSON file."); program.option("-d, --define [=value]", "Global definitions.", parseJS("define")); program.option("--ie8", "Support non-standard Internet Explorer 8."); program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name."); program.option("--self", "Build UglifyJS2 as a library (implies --wrap UglifyJS)"); program.option("--source-map [options]", "Enable source map/specify source map options.", parseSourceMap()); program.option("--stats", "Display operations run time on STDERR.") program.option("--toplevel", "Compress and/or mangle variables in toplevel scope."); program.option("--verbose", "Print informational/diagnostic messages."); program.option("--wrap ", "Embed everything as a function with “exports” corresponding to “name” globally."); program.arguments("[files...]").parseArgv(process.argv); if (program.configFile) { options = JSON.parse(readFile(program.configFile)); } if (!program.output && program.sourceMap && program.sourceMap.url != "inline") { fatal("ERROR: cannot write source map to STDOUT"); } [ "compress", "ie8", "mangle", "sourceMap", "toplevel", "wrap" ].forEach(function(name) { if (name in program) { options[name] = program[name]; } }); if (program.beautify) { options.output = typeof program.beautify == "object" ? program.beautify : {}; if (!("beautify" in options.output)) { options.output.beautify = true; } } if (program.comments) { if (typeof options.output != "object") options.output = {}; options.output.comments = typeof program.comments == "string" ? program.comments : "some"; } if (program.define) { if (typeof options.compress != "object") options.compress = {}; if (typeof options.compress.global_defs != "object") options.compress.global_defs = {}; for (var expr in program.define) { options.compress.global_defs[expr] = program.define[expr]; } } if (program.keepFnames) { options.keep_fnames = true; } if (program.mangleProps) { if (typeof options.mangle != "object") options.mangle = {}; options.mangle.properties = program.mangleProps; } if (program.parse) { if (program.parse.acorn || program.parse.spidermonkey) { if (program.sourceMap) fatal("ERROR: inline source map only works with built-in parser"); } else { options.parse = program.parse; } } if (program.verbose && options.compress) { if (typeof options.compress != "object") options.compress = {}; options.compress.warnings = "verbose"; } if (program.self) { if (program.args.length) { console.error("WARN: Ignoring input files since --self was passed"); } if (!options.wrap) options.wrap = "UglifyJS"; simple_glob(UglifyJS.FILES).forEach(function(path) { files[path] = readFile(path); }); run(); } else if (program.args.length) { simple_glob(program.args).forEach(function(path) { files[path] = readFile(path); }); run(); } else { var chunks = []; process.stdin.setEncoding("utf8"); process.stdin.on("data", function (chunk) { chunks.push(chunk); }).on("end", function () { files = [ chunks.join("") ]; run(); }); process.stdin.resume(); } function convert_ast(fn) { return UglifyJS.AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null)); } function run() { UglifyJS.AST_Node.warn_function = function(msg) { console.error("WARN:", msg); }; if (program.stats) program.stats = Date.now(); try { if (program.parse) { if (program.parse.acorn) { files = convert_ast(function(toplevel, name) { return require("acorn").parse(files[name], { locations: true, program: toplevel, sourceFile: name }); }); } else if (program.parse.spidermonkey) { files = convert_ast(function(toplevel, name) { var obj = JSON.parse(files[name]); if (!toplevel) return obj; toplevel.body = toplevel.body.concat(obj.body); return toplevel; }); } } var result = UglifyJS.minify(files, options); } catch (ex) { if (ex instanceof UglifyJS.JS_Parse_Error) { console.error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col); var col = ex.col; var line = files[ex.filename].split(/\r?\n/)[ex.line - (col ? 1 : 2)]; if (line) { if (col > 40) { line = line.slice(col - 40); col = 40; } if (col) { console.error(line.slice(0, 80)); console.error(line.slice(0, col).replace(/\S/g, " ") + "^"); } else { console.error(line.slice(-40)); console.error(line.slice(-40).replace(/\S/g, " ") + "^"); } } } fatal("ERROR: " + ex.message); } if (program.output == "spidermonkey") { console.log(JSON.stringify(UglifyJS.parse(result.code).to_mozilla_ast(), null, 2)); } else if (program.output) { fs.writeFileSync(program.output, result.code); if (result.map) { fs.writeFileSync(program.output + ".map", result.map); } } else { console.log(result.code); } if (program.stats) console.error("Elapsed:", Date.now() - program.stats); } function fatal(message) { console.error(message); process.exit(1); } // A file glob function that only supports "*" and "?" wildcards in the basename. // Example: "foo/bar/*baz??.*.js" // Argument `glob` may be a string or an array of strings. // Returns an array of strings. Garbage in, garbage out. function simple_glob(glob) { if (Array.isArray(glob)) { return [].concat.apply([], glob.map(simple_glob)); } if (glob.match(/\*|\?/)) { var dir = path.dirname(glob); try { var entries = fs.readdirSync(dir); } catch (ex) {} if (entries) { var pattern = "^" + path.basename(glob) .replace(/[.+^$[\]\\(){}]/g, "\\$&") .replace(/\*/g, "[^/\\\\]*") .replace(/\?/g, "[^/\\\\]") + "$"; var mod = process.platform === "win32" ? "i" : ""; var rx = new RegExp(pattern, mod); var results = entries.filter(function(name) { return rx.test(name); }).map(function(name) { return path.join(dir, name); }); if (results.length) return results; } } return [ glob ]; } function readFile(path) { try { return fs.readFileSync(path, "utf8"); } catch (ex) { fatal("ERROR: " + ex.message); } } function parseJS(flag, constants) { return function(value, options) { options = options || {}; try { UglifyJS.parse(value, { expression: true }).walk(new UglifyJS.TreeWalker(function(node) { if (node instanceof UglifyJS.AST_Assign) { var name = node.left.print_to_string(); var value = node.right; if (!constants) { options[name] = value; } else if (value instanceof UglifyJS.AST_Constant) { options[name] = value.getValue(); } else { options[name] = value.print_to_string(); } return true; } if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_PropAccess) { var name = node.print_to_string(); options[name] = true; return true; } if (!(node instanceof UglifyJS.AST_Sequence)) throw node; })); } catch(ex) { fatal("Error parsing arguments for '" + flag + "': " + value); } return options; } } function parseSourceMap() { var parse = parseJS("sourceMap", true); return function(value, options) { var hasContent = options && options.sourceMap && "content" in options.sourceMap; var settings = parse(value, options); if (!hasContent && settings.content && settings.content != "inline") { console.error("INFO: Using input source map:", settings.content); settings.content = readFile(settings.content); } return settings; } }