uglifyjs 15 KB

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