uglifyjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. #! /usr/bin/env node
  2. // -*- js -*-
  3. "use strict";
  4. require("../tools/exit");
  5. var fs = require("fs");
  6. var info = require("../package.json");
  7. var path = require("path");
  8. var program = require("commander");
  9. var UglifyJS = require("../tools/node");
  10. var skip_keys = [ "cname", "inlined", "parent_scope", "scope", "uses_eval", "uses_with" ];
  11. var files = {};
  12. var options = {
  13. compress: false,
  14. mangle: false
  15. };
  16. program.version(info.name + " " + info.version);
  17. program.parseArgv = program.parse;
  18. program.parse = undefined;
  19. if (process.argv.indexOf("ast") >= 0) program.helpInformation = UglifyJS.describe_ast;
  20. else if (process.argv.indexOf("options") >= 0) program.helpInformation = function() {
  21. var text = [];
  22. var options = UglifyJS.default_options();
  23. for (var option in options) {
  24. text.push("--" + (option == "output" ? "beautify" : option == "sourceMap" ? "source-map" : option) + " options:");
  25. text.push(format_object(options[option]));
  26. text.push("");
  27. }
  28. return text.join("\n");
  29. };
  30. program.option("-p, --parse <options>", "Specify parser options.", parse_js());
  31. program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js());
  32. program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js());
  33. program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js());
  34. program.option("-b, --beautify [options]", "Beautify output/specify output options.", parse_js());
  35. program.option("-o, --output <file>", "Output file (default STDOUT).");
  36. program.option("--comments [filter]", "Preserve copyright comments in the output.");
  37. program.option("--config-file <file>", "Read minify() options from JSON file.");
  38. program.option("-d, --define <expr>[=value]", "Global definitions.", parse_js("define"));
  39. program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed everything in a big function, with configurable argument(s) & value(s).");
  40. program.option("--ie8", "Support non-standard Internet Explorer 8.");
  41. program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");
  42. program.option("--name-cache <file>", "File to hold mangled name mappings.");
  43. program.option("--rename", "Force symbol expansion.");
  44. program.option("--no-rename", "Disable symbol expansion.");
  45. program.option("--self", "Build UglifyJS as a library (implies --wrap UglifyJS)");
  46. program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js());
  47. program.option("--timings", "Display operations run time on STDERR.");
  48. program.option("--toplevel", "Compress and/or mangle variables in toplevel scope.");
  49. program.option("--verbose", "Print diagnostic messages.");
  50. program.option("--warn", "Print warning messages.");
  51. program.option("--wrap <name>", "Embed everything as a function with “exports” corresponding to “name” globally.");
  52. program.arguments("[files...]").parseArgv(process.argv);
  53. if (program.configFile) {
  54. options = JSON.parse(read_file(program.configFile));
  55. if (options.mangle && options.mangle.properties && options.mangle.properties.regex) {
  56. options.mangle.properties.regex = UglifyJS.parse(options.mangle.properties.regex, {
  57. expression: true
  58. }).getValue();
  59. }
  60. }
  61. if (!program.output && program.sourceMap && program.sourceMap.url != "inline") {
  62. fatal("cannot write source map to STDOUT");
  63. }
  64. [
  65. "compress",
  66. "enclose",
  67. "ie8",
  68. "mangle",
  69. "sourceMap",
  70. "toplevel",
  71. "wrap"
  72. ].forEach(function(name) {
  73. if (name in program) {
  74. options[name] = program[name];
  75. }
  76. });
  77. if (program.verbose) {
  78. options.warnings = "verbose";
  79. } else if (program.warn) {
  80. options.warnings = true;
  81. }
  82. if (options.warnings) {
  83. UglifyJS.AST_Node.log_function(print_error, options.warnings == "verbose");
  84. delete options.warnings;
  85. }
  86. if (program.beautify) {
  87. options.output = typeof program.beautify == "object" ? program.beautify : {};
  88. if (!("beautify" in options.output)) {
  89. options.output.beautify = true;
  90. }
  91. }
  92. if (program.comments) {
  93. if (typeof options.output != "object") options.output = {};
  94. options.output.comments = typeof program.comments == "string" ? program.comments : "some";
  95. }
  96. if (program.define) {
  97. if (typeof options.compress != "object") options.compress = {};
  98. if (typeof options.compress.global_defs != "object") options.compress.global_defs = {};
  99. for (var expr in program.define) {
  100. options.compress.global_defs[expr] = program.define[expr];
  101. }
  102. }
  103. if (program.keepFnames) {
  104. options.keep_fnames = true;
  105. }
  106. if (program.mangleProps) {
  107. if (program.mangleProps.domprops) {
  108. delete program.mangleProps.domprops;
  109. } else {
  110. if (typeof program.mangleProps != "object") program.mangleProps = {};
  111. if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = [];
  112. require("../tools/domprops").forEach(function(name) {
  113. UglifyJS.push_uniq(program.mangleProps.reserved, name);
  114. });
  115. }
  116. if (typeof options.mangle != "object") options.mangle = {};
  117. options.mangle.properties = program.mangleProps;
  118. }
  119. if (program.nameCache) {
  120. options.nameCache = JSON.parse(read_file(program.nameCache, "{}"));
  121. }
  122. if (program.output == "ast") {
  123. options.output = {
  124. ast: true,
  125. code: false
  126. };
  127. }
  128. if (program.parse) {
  129. if (!program.parse.acorn && !program.parse.spidermonkey) {
  130. options.parse = program.parse;
  131. } else if (program.sourceMap && program.sourceMap.content == "inline") {
  132. fatal("inline source map only works with built-in parser");
  133. }
  134. }
  135. if (~program.rawArgs.indexOf("--rename")) {
  136. options.rename = true;
  137. } else if (!program.rename) {
  138. options.rename = false;
  139. }
  140. var convert_path = function(name) {
  141. return name;
  142. };
  143. if (typeof program.sourceMap == "object" && "base" in program.sourceMap) {
  144. convert_path = function() {
  145. var base = program.sourceMap.base;
  146. delete options.sourceMap.base;
  147. return function(name) {
  148. return path.relative(base, name);
  149. };
  150. }();
  151. }
  152. if (program.self) {
  153. if (program.args.length) UglifyJS.AST_Node.warn("Ignoring input files since --self was passed");
  154. if (!options.wrap) options.wrap = "UglifyJS";
  155. simple_glob(UglifyJS.FILES).forEach(function(name) {
  156. files[convert_path(name)] = read_file(name);
  157. });
  158. run();
  159. } else if (program.args.length) {
  160. simple_glob(program.args).forEach(function(name) {
  161. files[convert_path(name)] = read_file(name);
  162. });
  163. run();
  164. } else {
  165. var chunks = [];
  166. process.stdin.setEncoding("utf8");
  167. process.stdin.on("data", function(chunk) {
  168. chunks.push(chunk);
  169. }).on("end", function() {
  170. files = [ chunks.join("") ];
  171. run();
  172. });
  173. process.stdin.resume();
  174. }
  175. function convert_ast(fn) {
  176. return UglifyJS.AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null));
  177. }
  178. function run() {
  179. var content = program.sourceMap && program.sourceMap.content;
  180. if (content && content != "inline") {
  181. UglifyJS.AST_Node.info("Using input source map: " + content);
  182. options.sourceMap.content = read_file(content, content);
  183. }
  184. if (program.timings) options.timings = true;
  185. try {
  186. if (program.parse) {
  187. if (program.parse.acorn) {
  188. files = convert_ast(function(toplevel, name) {
  189. return require("acorn").parse(files[name], {
  190. locations: true,
  191. program: toplevel,
  192. sourceFile: name
  193. });
  194. });
  195. } else if (program.parse.spidermonkey) {
  196. files = convert_ast(function(toplevel, name) {
  197. var obj = JSON.parse(files[name]);
  198. if (!toplevel) return obj;
  199. toplevel.body = toplevel.body.concat(obj.body);
  200. return toplevel;
  201. });
  202. }
  203. }
  204. } catch (ex) {
  205. fatal(ex);
  206. }
  207. var result = UglifyJS.minify(files, options);
  208. if (result.error) {
  209. var ex = result.error;
  210. if (ex.name == "SyntaxError") {
  211. print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col);
  212. var file = files[ex.filename];
  213. if (file) {
  214. var col = ex.col;
  215. var lines = file.split(/\r?\n/);
  216. var line = lines[ex.line - 1];
  217. if (!line && !col) {
  218. line = lines[ex.line - 2];
  219. col = line.length;
  220. }
  221. if (line) {
  222. var limit = 70;
  223. if (col > limit) {
  224. line = line.slice(col - limit);
  225. col = limit;
  226. }
  227. print_error(line.slice(0, 80));
  228. print_error(line.slice(0, col).replace(/\S/g, " ") + "^");
  229. }
  230. }
  231. } else if (ex.defs) {
  232. print_error("Supported options:");
  233. print_error(format_object(ex.defs));
  234. }
  235. fatal(ex);
  236. } else if (program.output == "ast") {
  237. if (!options.compress && !options.mangle) {
  238. result.ast.figure_out_scope({});
  239. }
  240. print(JSON.stringify(result.ast, function(key, value) {
  241. if (value) switch (key) {
  242. case "thedef":
  243. return symdef(value);
  244. case "enclosed":
  245. return value.length ? value.map(symdef) : undefined;
  246. case "variables":
  247. case "functions":
  248. case "globals":
  249. return value.size() ? value.map(symdef) : undefined;
  250. }
  251. if (skip_key(key)) return;
  252. if (value instanceof UglifyJS.AST_Token) return;
  253. if (value instanceof UglifyJS.Dictionary) return;
  254. if (value instanceof UglifyJS.AST_Node) {
  255. var result = {
  256. _class: "AST_" + value.TYPE
  257. };
  258. value.CTOR.PROPS.forEach(function(prop) {
  259. result[prop] = value[prop];
  260. });
  261. return result;
  262. }
  263. return value;
  264. }, 2));
  265. } else if (program.output == "spidermonkey") {
  266. print(JSON.stringify(UglifyJS.minify(result.code, {
  267. compress: false,
  268. mangle: false,
  269. output: {
  270. ast: true,
  271. code: false
  272. }
  273. }).ast.to_mozilla_ast(), null, 2));
  274. } else if (program.output) {
  275. fs.writeFileSync(program.output, result.code);
  276. if (result.map) {
  277. fs.writeFileSync(program.output + ".map", result.map);
  278. }
  279. } else {
  280. print(result.code);
  281. }
  282. if (program.nameCache) {
  283. fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache));
  284. }
  285. if (result.timings) for (var phase in result.timings) {
  286. print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s");
  287. }
  288. }
  289. function fatal(message) {
  290. if (message instanceof Error) {
  291. message = message.stack.replace(/^\S*?Error:/, "ERROR:")
  292. } else {
  293. message = "ERROR: " + message;
  294. }
  295. print_error(message);
  296. process.exit(1);
  297. }
  298. // A file glob function that only supports "*" and "?" wildcards in the basename.
  299. // Example: "foo/bar/*baz??.*.js"
  300. // Argument `glob` may be a string or an array of strings.
  301. // Returns an array of strings. Garbage in, garbage out.
  302. function simple_glob(glob) {
  303. if (Array.isArray(glob)) {
  304. return [].concat.apply([], glob.map(simple_glob));
  305. }
  306. if (glob.match(/\*|\?/)) {
  307. var dir = path.dirname(glob);
  308. try {
  309. var entries = fs.readdirSync(dir);
  310. } catch (ex) {}
  311. if (entries) {
  312. var pattern = "^" + path.basename(glob)
  313. .replace(/[.+^$[\]\\(){}]/g, "\\$&")
  314. .replace(/\*/g, "[^/\\\\]*")
  315. .replace(/\?/g, "[^/\\\\]") + "$";
  316. var mod = process.platform === "win32" ? "i" : "";
  317. var rx = new RegExp(pattern, mod);
  318. var results = entries.filter(function(name) {
  319. return rx.test(name);
  320. }).map(function(name) {
  321. return path.join(dir, name);
  322. });
  323. if (results.length) return results;
  324. }
  325. }
  326. return [ glob ];
  327. }
  328. function read_file(path, default_value) {
  329. try {
  330. return fs.readFileSync(path, "utf8");
  331. } catch (ex) {
  332. if (ex.code == "ENOENT" && default_value != null) return default_value;
  333. fatal(ex);
  334. }
  335. }
  336. function parse_js(flag) {
  337. return function(value, options) {
  338. options = options || {};
  339. try {
  340. UglifyJS.parse(value, {
  341. expression: true
  342. }).walk(new UglifyJS.TreeWalker(function(node) {
  343. if (node instanceof UglifyJS.AST_Assign) {
  344. var name = node.left.print_to_string();
  345. var value = node.right;
  346. if (flag) {
  347. options[name] = value;
  348. } else if (value instanceof UglifyJS.AST_Array) {
  349. options[name] = value.elements.map(to_string);
  350. } else {
  351. options[name] = to_string(value);
  352. }
  353. return true;
  354. }
  355. if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_PropAccess) {
  356. var name = node.print_to_string();
  357. options[name] = true;
  358. return true;
  359. }
  360. if (!(node instanceof UglifyJS.AST_Sequence)) throw node;
  361. function to_string(value) {
  362. return value instanceof UglifyJS.AST_Constant ? value.getValue() : value.print_to_string({
  363. quote_keys: true
  364. });
  365. }
  366. }));
  367. } catch (ex) {
  368. if (flag) {
  369. fatal("cannot parse arguments for '" + flag + "': " + value);
  370. } else {
  371. options[value] = null;
  372. }
  373. }
  374. return options;
  375. }
  376. }
  377. function skip_key(key) {
  378. return skip_keys.indexOf(key) >= 0;
  379. }
  380. function symdef(def) {
  381. var ret = (1e6 + def.id) + " " + def.name;
  382. if (def.mangled_name) ret += " " + def.mangled_name;
  383. return ret;
  384. }
  385. function format_object(obj) {
  386. var lines = [];
  387. var padding = "";
  388. Object.keys(obj).map(function(name) {
  389. if (padding.length < name.length) padding = Array(name.length + 1).join(" ");
  390. return [ name, JSON.stringify(obj[name]) ];
  391. }).forEach(function(tokens) {
  392. lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]);
  393. });
  394. return lines.join("\n");
  395. }
  396. function print_error(msg) {
  397. process.stderr.write(msg);
  398. process.stderr.write("\n");
  399. }
  400. function print(txt) {
  401. process.stdout.write(txt);
  402. process.stdout.write("\n");
  403. }