uglifyjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. #! /usr/bin/env node
  2. // -*- js -*-
  3. "use strict";
  4. var UglifyJS = require("../tools/node");
  5. var sys = require("util");
  6. var yargs = require("yargs");
  7. var fs = require("fs");
  8. var path = require("path");
  9. var acorn;
  10. var screw_ie8 = true;
  11. var ARGS = yargs
  12. .usage("$0 input1.js [input2.js ...] [options]\n\
  13. Use a single dash to read input from the standard input.\
  14. \n\n\
  15. NOTE: by default there is no mangling/compression.\n\
  16. Without [options] it will simply parse input files and dump the AST\n\
  17. with whitespace and comments discarded. To achieve compression and\n\
  18. mangling you need to use `-c` and `-m`.\
  19. ")
  20. .describe("source-map", "Specify an output file where to generate source map.")
  21. .describe("source-map-root", "The path to the original source to be included in the source map.")
  22. .describe("source-map-url", "The path to the source map to be added in //# sourceMappingURL. Defaults to the value passed with --source-map.")
  23. .describe("source-map-inline", "Write base64-encoded source map to the end of js output. Disabled by default")
  24. .describe("source-map-include-sources", "Pass this flag if you want to include the content of source files in the source map as sourcesContent property.")
  25. .describe("in-source-map", "Input source map, useful if you're compressing JS that was generated from some other original code.")
  26. .describe("screw-ie8", "Do not support Internet Explorer 6/7/8. This flag is enabled by default.")
  27. .describe("support-ie8", "Support non-standard Internet Explorer 6/7/8 javascript.")
  28. .describe("expr", "Parse a single expression, rather than a program (for parsing JSON)")
  29. .describe("p", "Skip prefix for original filenames that appear in source maps. \
  30. For example -p 3 will drop 3 directories from file names and ensure they are relative paths. \
  31. You can also specify -p relative, which will make UglifyJS figure out itself the relative paths between original sources, \
  32. the source map and the output file.")
  33. .describe("o", "Output file (default STDOUT).")
  34. .describe("b", "Beautify output/specify output options.")
  35. .describe("m", "Mangle names/pass mangler options.")
  36. .describe("r", "Reserved names to exclude from mangling.")
  37. .describe("c", "Enable compressor/pass compressor options. \
  38. Pass options like -c hoist_vars=false,if_return=false. \
  39. Use -c with no argument to use the default compression options.")
  40. .describe("d", "Global definitions")
  41. .describe("e", "Embed everything in a big function, with a configurable parameter/argument list.")
  42. .describe("comments", "Preserve copyright comments in the output. \
  43. By default this works like Google Closure, keeping JSDoc-style comments that contain \"@license\" or \"@preserve\". \
  44. You can optionally pass one of the following arguments to this flag:\n\
  45. - \"all\" to keep all comments\n\
  46. - a valid JS RegExp like `/foo/`or `/^!/` to keep only matching comments.\n\
  47. \
  48. Note that currently not *all* comments can be kept when compression is on, \
  49. because of dead code removal or cascading statements into sequences.")
  50. .describe("preamble", "Preamble to prepend to the output. You can use this to insert a \
  51. comment, for example for licensing information. This will not be \
  52. parsed, but the source map will adjust for its presence.")
  53. .describe("stats", "Display operations run time on STDERR.")
  54. .describe("acorn", "Use Acorn for parsing.")
  55. .describe("spidermonkey", "Assume input files are SpiderMonkey AST format (as JSON).")
  56. .describe("self", "Build itself (UglifyJS2) as a library (implies --wrap=UglifyJS --export-all)")
  57. .describe("wrap", "Embed everything in a big function, making the “exports” and “global” variables available. \
  58. You need to pass an argument to this option to specify the name that your module will take when included in, say, a browser.")
  59. .describe("export-all", "Only used when --wrap, this tells UglifyJS to add code to automatically export all globals.")
  60. .describe("lint", "Display some scope warnings")
  61. .describe("v", "Verbose")
  62. .describe("V", "Print version number and exit.")
  63. .describe("noerr", "Don't throw an error for unknown options in -c, -b or -m.")
  64. .describe("bare-returns", "Allow return outside of functions. Useful when minifying CommonJS modules.")
  65. .describe("keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name.")
  66. .describe("quotes", "Quote style (0 - auto, 1 - single, 2 - double, 3 - original)")
  67. .describe("reserved-file", "File containing reserved names")
  68. .describe("reserve-domprops", "Make (most?) DOM properties reserved for --mangle-props")
  69. .describe("mangle-props", "Mangle property names (0 - disabled, 1 - mangle all properties, 2 - mangle unquoted properies)")
  70. .describe("mangle-regex", "Only mangle property names matching the regex")
  71. .describe("name-cache", "File to hold mangled names mappings")
  72. .describe("pure-funcs", "List of functions that can be safely removed if their return value is not used")
  73. .describe("dump-spidermonkey-ast", "Dump SpiderMonkey AST to stdout.")
  74. .describe("wrap-iife", "Wrap IIFEs in parenthesis. Note: this disables the negate_iife compression option")
  75. .alias("p", "prefix")
  76. .alias("o", "output")
  77. .alias("v", "verbose")
  78. .alias("b", "beautify")
  79. .alias("m", "mangle")
  80. .alias("c", "compress")
  81. .alias("d", "define")
  82. .alias("r", "reserved")
  83. .alias("V", "version")
  84. .alias("e", "enclose")
  85. .alias("q", "quotes")
  86. .string("source-map")
  87. .string("source-map-root")
  88. .string("source-map-url")
  89. .string("b")
  90. .string("beautify")
  91. .string("m")
  92. .string("mangle")
  93. .string("mangle-props-debug")
  94. .string("c")
  95. .string("compress")
  96. .string("d")
  97. .string("define")
  98. .string("e")
  99. .string("enclose")
  100. .string("comments")
  101. .string("wrap")
  102. .string("p")
  103. .string("prefix")
  104. .string("name-cache")
  105. .array("reserved-file")
  106. .array("pure-funcs")
  107. .boolean("expr")
  108. .boolean("source-map-inline")
  109. .boolean("source-map-include-sources")
  110. .boolean("screw-ie8")
  111. .boolean("support-ie8")
  112. .boolean("export-all")
  113. .boolean("self")
  114. .boolean("v")
  115. .boolean("verbose")
  116. .boolean("stats")
  117. .boolean("acorn")
  118. .boolean("spidermonkey")
  119. .boolean("dump-spidermonkey-ast")
  120. .boolean("lint")
  121. .boolean("V")
  122. .boolean("version")
  123. .boolean("noerr")
  124. .boolean("bare-returns")
  125. .boolean("keep-fnames")
  126. .boolean("reserve-domprops")
  127. .boolean("wrap-iife")
  128. .wrap(80)
  129. .argv
  130. ;
  131. normalize(ARGS);
  132. if (ARGS.noerr) {
  133. UglifyJS.DefaultsError.croak = function(msg, defs) {
  134. print_error("WARN: " + msg);
  135. };
  136. }
  137. if (ARGS.version || ARGS.V) {
  138. var json = require("../package.json");
  139. print(json.name + ' ' + json.version);
  140. process.exit(0);
  141. }
  142. if (ARGS.ast_help) {
  143. var desc = UglifyJS.describe_ast();
  144. print(typeof desc == "string" ? desc : JSON.stringify(desc, null, 2));
  145. process.exit(0);
  146. }
  147. if (ARGS.h || ARGS.help) {
  148. print(yargs.help());
  149. process.exit(0);
  150. }
  151. if (ARGS.acorn) {
  152. acorn = require("acorn");
  153. }
  154. var COMPRESS = getOptions("c", true);
  155. var MANGLE = getOptions("m", true);
  156. var BEAUTIFY = getOptions("b", true);
  157. var RESERVED = null;
  158. if (ARGS.reserved_file) ARGS.reserved_file.forEach(function(filename){
  159. RESERVED = UglifyJS.readReservedFile(filename, RESERVED);
  160. });
  161. if (ARGS.reserve_domprops) {
  162. RESERVED = UglifyJS.readDefaultReservedFile(RESERVED);
  163. }
  164. if (ARGS.d) {
  165. if (COMPRESS) COMPRESS.global_defs = getOptions("d");
  166. }
  167. if (ARGS.pure_funcs) {
  168. if (COMPRESS) COMPRESS.pure_funcs = ARGS.pure_funcs;
  169. }
  170. if (ARGS.r) {
  171. if (MANGLE) MANGLE.except = ARGS.r.replace(/^\s+|\s+$/g).split(/\s*,+\s*/);
  172. }
  173. if (RESERVED && MANGLE) {
  174. if (!MANGLE.except) MANGLE.except = RESERVED.vars;
  175. else MANGLE.except = MANGLE.except.concat(RESERVED.vars);
  176. }
  177. function readNameCache(key) {
  178. return UglifyJS.readNameCache(ARGS.name_cache, key);
  179. }
  180. function writeNameCache(key, cache) {
  181. return UglifyJS.writeNameCache(ARGS.name_cache, key, cache);
  182. }
  183. function extractRegex(str) {
  184. if (/^\/.*\/[a-zA-Z]*$/.test(str)) {
  185. var regex_pos = str.lastIndexOf("/");
  186. return new RegExp(str.substr(1, regex_pos - 1), str.substr(regex_pos + 1));
  187. } else {
  188. throw new Error("Invalid regular expression: " + str);
  189. }
  190. }
  191. if (ARGS.quotes === true) {
  192. ARGS.quotes = 3;
  193. }
  194. if (ARGS.mangle_props === true) {
  195. ARGS.mangle_props = 1;
  196. } else if (ARGS.mangle_props === "unquoted") {
  197. ARGS.mangle_props = 2;
  198. }
  199. var OUTPUT_OPTIONS = {
  200. beautify : BEAUTIFY ? true : false,
  201. max_line_len : 32000,
  202. preamble : ARGS.preamble || null,
  203. quote_style : ARGS.quotes != null ? ARGS.quotes : 0,
  204. };
  205. if (ARGS.mangle_props == 2) {
  206. OUTPUT_OPTIONS.keep_quoted_props = true;
  207. if (COMPRESS && !("properties" in COMPRESS))
  208. COMPRESS.properties = false;
  209. }
  210. if (ARGS.support_ie8 === true && ARGS.screw_ie8 !== true) {
  211. screw_ie8 = false;
  212. }
  213. if (COMPRESS) COMPRESS.screw_ie8 = screw_ie8;
  214. if (MANGLE) MANGLE.screw_ie8 = screw_ie8;
  215. OUTPUT_OPTIONS.screw_ie8 = screw_ie8;
  216. if (ARGS.keep_fnames) {
  217. if (COMPRESS) COMPRESS.keep_fnames = true;
  218. if (MANGLE) MANGLE.keep_fnames = true;
  219. }
  220. if (ARGS.wrap_iife) {
  221. if (COMPRESS) COMPRESS.negate_iife = false;
  222. OUTPUT_OPTIONS.wrap_iife = true;
  223. }
  224. if (BEAUTIFY)
  225. UglifyJS.merge(OUTPUT_OPTIONS, BEAUTIFY);
  226. if (ARGS.comments === "") {
  227. OUTPUT_OPTIONS.comments = "some";
  228. } else {
  229. OUTPUT_OPTIONS.comments = ARGS.comments;
  230. }
  231. var files = ARGS._.slice();
  232. if (process.platform === "win32")
  233. files = UglifyJS.simple_glob(files);
  234. if (ARGS.self) {
  235. if (files.length > 0) {
  236. print_error("WARN: Ignoring input files since --self was passed");
  237. }
  238. files = UglifyJS.FILES;
  239. if (!ARGS.wrap) ARGS.wrap = "UglifyJS";
  240. }
  241. var ORIG_MAP = ARGS.in_source_map;
  242. if (ORIG_MAP && ORIG_MAP != "inline") {
  243. ORIG_MAP = JSON.parse(fs.readFileSync(ORIG_MAP));
  244. if (files.length == 0) {
  245. print_error("INFO: Using file from the input source map: " + ORIG_MAP.file);
  246. files = [ ORIG_MAP.file ];
  247. }
  248. }
  249. if (files.length == 0) {
  250. files = [ "-" ];
  251. }
  252. if (ORIG_MAP == "inline") {
  253. if (files.length > 1) {
  254. print_error("ERROR: Inline source map only works with singular input");
  255. process.exit(1);
  256. }
  257. if (ARGS.acorn || ARGS.spidermonkey) {
  258. print_error("ERROR: Inline source map only works with built-in parser");
  259. process.exit(1);
  260. }
  261. }
  262. if (files.indexOf("-") >= 0 && ARGS.source_map) {
  263. print_error("ERROR: Source map doesn't work with input from STDIN");
  264. process.exit(1);
  265. }
  266. if (files.filter(function(el){ return el == "-" }).length > 1) {
  267. print_error("ERROR: Can read a single file from STDIN (two or more dashes specified)");
  268. process.exit(1);
  269. }
  270. var STATS = {};
  271. var TOPLEVEL = null;
  272. var P_RELATIVE = ARGS.p && ARGS.p == "relative";
  273. var SOURCES_CONTENT = {};
  274. var index = 0;
  275. !function cb() {
  276. if (index == files.length) return done();
  277. var file = files[index++];
  278. read_whole_file(file, function (err, code) {
  279. if (err) {
  280. print_error("ERROR: can't read file: " + file);
  281. process.exit(1);
  282. }
  283. if (ORIG_MAP == "inline") {
  284. ORIG_MAP = read_source_map(code);
  285. }
  286. if (ARGS.p != null) {
  287. if (P_RELATIVE) {
  288. file = path.relative(path.dirname(ARGS.source_map), file).replace(/\\/g, '/');
  289. } else {
  290. var p = parseInt(ARGS.p, 10);
  291. if (!isNaN(p)) {
  292. file = file.replace(/^\/+/, "").split(/\/+/).slice(ARGS.p).join("/");
  293. }
  294. }
  295. }
  296. SOURCES_CONTENT[file] = code;
  297. time_it("parse", function(){
  298. if (ARGS.spidermonkey) {
  299. var program = JSON.parse(code);
  300. if (!TOPLEVEL) TOPLEVEL = program;
  301. else TOPLEVEL.body = TOPLEVEL.body.concat(program.body);
  302. }
  303. else if (ARGS.acorn) {
  304. TOPLEVEL = acorn.parse(code, {
  305. locations : true,
  306. sourceFile : file,
  307. program : TOPLEVEL
  308. });
  309. }
  310. else {
  311. try {
  312. TOPLEVEL = UglifyJS.parse(code, {
  313. filename : file,
  314. toplevel : TOPLEVEL,
  315. expression : ARGS.expr,
  316. bare_returns : ARGS.bare_returns,
  317. });
  318. } catch(ex) {
  319. if (ex instanceof UglifyJS.JS_Parse_Error) {
  320. print_error("Parse error at " + file + ":" + ex.line + "," + ex.col);
  321. var col = ex.col;
  322. var lines = code.split(/\r?\n/);
  323. var line = lines[ex.line - 1];
  324. if (!line && !col) {
  325. line = lines[ex.line - 2];
  326. col = line.length;
  327. }
  328. if (line) {
  329. if (col > 40) {
  330. line = line.slice(col - 40);
  331. col = 40;
  332. }
  333. print_error(line.slice(0, 80));
  334. print_error(line.slice(0, col).replace(/\S/g, " ") + "^");
  335. }
  336. print_error(ex.stack);
  337. process.exit(1);
  338. }
  339. throw ex;
  340. }
  341. };
  342. });
  343. cb();
  344. });
  345. }();
  346. function done() {
  347. var OUTPUT_FILE = ARGS.o;
  348. var SOURCE_MAP = (ARGS.source_map || ARGS.source_map_inline) ? UglifyJS.SourceMap({
  349. file: P_RELATIVE ? path.relative(path.dirname(ARGS.source_map), OUTPUT_FILE) : OUTPUT_FILE,
  350. root: ARGS.source_map_root || ORIG_MAP && ORIG_MAP.sourceRoot,
  351. orig: ORIG_MAP,
  352. }) : null;
  353. OUTPUT_OPTIONS.source_map = SOURCE_MAP;
  354. try {
  355. var output = UglifyJS.OutputStream(OUTPUT_OPTIONS);
  356. var compressor = COMPRESS && UglifyJS.Compressor(COMPRESS);
  357. } catch(ex) {
  358. if (ex instanceof UglifyJS.DefaultsError) {
  359. print_error(ex.message);
  360. print_error("Supported options:");
  361. print_error(sys.inspect(ex.defs));
  362. process.exit(1);
  363. }
  364. }
  365. if (ARGS.acorn || ARGS.spidermonkey) time_it("convert_ast", function(){
  366. TOPLEVEL = UglifyJS.AST_Node.from_mozilla_ast(TOPLEVEL);
  367. });
  368. if (ARGS.wrap != null) {
  369. TOPLEVEL = TOPLEVEL.wrap_commonjs(ARGS.wrap, ARGS.export_all);
  370. }
  371. if (ARGS.enclose != null) {
  372. var arg_parameter_list = ARGS.enclose;
  373. if (arg_parameter_list === true) {
  374. arg_parameter_list = [];
  375. }
  376. else if (!(arg_parameter_list instanceof Array)) {
  377. arg_parameter_list = [arg_parameter_list];
  378. }
  379. TOPLEVEL = TOPLEVEL.wrap_enclose(arg_parameter_list);
  380. }
  381. if (ARGS.mangle_props || ARGS.name_cache) (function(){
  382. var reserved = RESERVED ? RESERVED.props : null;
  383. var cache = readNameCache("props");
  384. var regex;
  385. try {
  386. regex = ARGS.mangle_regex ? extractRegex(ARGS.mangle_regex) : null;
  387. } catch (e) {
  388. print_error("ERROR: Invalid --mangle-regex: " + e.message);
  389. process.exit(1);
  390. }
  391. TOPLEVEL = UglifyJS.mangle_properties(TOPLEVEL, {
  392. reserved : reserved,
  393. cache : cache,
  394. only_cache : !ARGS.mangle_props,
  395. regex : regex,
  396. ignore_quoted : ARGS.mangle_props == 2,
  397. debug : typeof ARGS.mangle_props_debug === "undefined" ? false : ARGS.mangle_props_debug
  398. });
  399. writeNameCache("props", cache);
  400. })();
  401. var SCOPE_IS_NEEDED = COMPRESS || MANGLE || ARGS.lint
  402. var TL_CACHE = readNameCache("vars");
  403. if (MANGLE) MANGLE.cache = TL_CACHE;
  404. if (SCOPE_IS_NEEDED) {
  405. time_it("scope", function(){
  406. TOPLEVEL.figure_out_scope(MANGLE || { screw_ie8: screw_ie8, cache: TL_CACHE });
  407. if (ARGS.lint) {
  408. TOPLEVEL.scope_warnings();
  409. }
  410. });
  411. }
  412. if (COMPRESS) {
  413. time_it("squeeze", function(){
  414. TOPLEVEL = compressor.compress(TOPLEVEL);
  415. });
  416. }
  417. if (SCOPE_IS_NEEDED) {
  418. time_it("scope", function(){
  419. TOPLEVEL.figure_out_scope(MANGLE || { screw_ie8: screw_ie8, cache: TL_CACHE });
  420. if (MANGLE && !TL_CACHE) {
  421. TOPLEVEL.compute_char_frequency(MANGLE);
  422. }
  423. });
  424. }
  425. if (MANGLE) time_it("mangle", function(){
  426. TOPLEVEL.mangle_names(MANGLE);
  427. });
  428. writeNameCache("vars", TL_CACHE);
  429. if (ARGS.source_map_include_sources) {
  430. for (var file in SOURCES_CONTENT) {
  431. if (SOURCES_CONTENT.hasOwnProperty(file)) {
  432. SOURCE_MAP.get().setSourceContent(file, SOURCES_CONTENT[file]);
  433. }
  434. }
  435. }
  436. if (ARGS.dump_spidermonkey_ast) {
  437. print(JSON.stringify(TOPLEVEL.to_mozilla_ast(), null, 2));
  438. } else {
  439. time_it("generate", function(){
  440. TOPLEVEL.print(output);
  441. });
  442. output = output.get();
  443. if (SOURCE_MAP) {
  444. if (ARGS.source_map_inline) {
  445. var base64_string = new Buffer(SOURCE_MAP.toString()).toString('base64');
  446. output += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + base64_string;
  447. } else {
  448. fs.writeFileSync(ARGS.source_map, SOURCE_MAP, "utf8");
  449. var source_map_url = ARGS.source_map_url || (
  450. P_RELATIVE
  451. ? path.relative(path.dirname(OUTPUT_FILE), ARGS.source_map)
  452. : ARGS.source_map
  453. );
  454. output += "\n//# sourceMappingURL=" + source_map_url;
  455. }
  456. }
  457. if (OUTPUT_FILE) {
  458. fs.writeFileSync(OUTPUT_FILE, output, "utf8");
  459. } else {
  460. print(output);
  461. }
  462. }
  463. if (ARGS.stats) {
  464. print_error(UglifyJS.string_template("Timing information (compressed {count} files):", {
  465. count: files.length
  466. }));
  467. for (var i in STATS) if (STATS.hasOwnProperty(i)) {
  468. print_error(UglifyJS.string_template("- {name}: {time}s", {
  469. name: i,
  470. time: (STATS[i] / 1000).toFixed(3)
  471. }));
  472. }
  473. }
  474. }
  475. /* -----[ functions ]----- */
  476. function normalize(o) {
  477. for (var i in o) if (o.hasOwnProperty(i) && /-/.test(i)) {
  478. o[i.replace(/-/g, "_")] = o[i];
  479. delete o[i];
  480. }
  481. }
  482. function getOptions(flag, constants) {
  483. var x = ARGS[flag];
  484. if (x == null || x === false) return null;
  485. var ret = {};
  486. if (x !== "") {
  487. if (Array.isArray(x)) x = x.map(function (v) { return "(" + v + ")"; }).join(", ");
  488. var ast;
  489. try {
  490. ast = UglifyJS.parse(x, { cli: true, expression: true });
  491. } catch(ex) {
  492. if (ex instanceof UglifyJS.JS_Parse_Error) {
  493. print_error("Error parsing arguments for flag `" + flag + "': " + x);
  494. process.exit(1);
  495. }
  496. }
  497. ast.walk(new UglifyJS.TreeWalker(function(node){
  498. if (node instanceof UglifyJS.AST_Seq) return; // descend
  499. if (node instanceof UglifyJS.AST_Assign) {
  500. var name = node.left.print_to_string().replace(/-/g, "_");
  501. var value = node.right;
  502. if (constants)
  503. value = new Function("return (" + value.print_to_string() + ")")();
  504. ret[name] = value;
  505. return true; // no descend
  506. }
  507. if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_Binary) {
  508. var name = node.print_to_string().replace(/-/g, "_");
  509. ret[name] = true;
  510. return true; // no descend
  511. }
  512. print_error(node.TYPE)
  513. print_error("Error parsing arguments for flag `" + flag + "': " + x);
  514. process.exit(1);
  515. }));
  516. }
  517. return ret;
  518. }
  519. function read_whole_file(filename, cb) {
  520. if (filename == "-") {
  521. var chunks = [];
  522. process.stdin.setEncoding('utf-8');
  523. process.stdin.on('data', function (chunk) {
  524. chunks.push(chunk);
  525. }).on('end', function () {
  526. cb(null, chunks.join(""));
  527. });
  528. process.openStdin();
  529. } else {
  530. fs.readFile(filename, "utf-8", cb);
  531. }
  532. }
  533. function read_source_map(code) {
  534. var match = /\n\/\/# sourceMappingURL=data:application\/json(;.*?)?;base64,(.*)/.exec(code);
  535. if (!match) {
  536. print_error("WARN: inline source map not found");
  537. return null;
  538. }
  539. return JSON.parse(new Buffer(match[2], "base64"));
  540. }
  541. function time_it(name, cont) {
  542. var t1 = new Date().getTime();
  543. var ret = cont();
  544. if (ARGS.stats) {
  545. var spent = new Date().getTime() - t1;
  546. if (STATS[name]) STATS[name] += spent;
  547. else STATS[name] = spent;
  548. }
  549. return ret;
  550. }
  551. function print_error(msg) {
  552. console.error("%s", msg);
  553. }
  554. function print(txt) {
  555. console.log("%s", txt);
  556. }