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.

484 lines
16 KiB

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