You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

uglifyjs 16KB

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