2
0

amberc.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. /**
  2. * This is a "compiler" for Amber code.
  3. * Put the following code into compiler.js:
  4. * var amberc = require('amberc');
  5. * var compiler = new amberc.Compiler('path/to/amber', ['/optional/path/to/compiler.jar]);
  6. * compiler.main();
  7. *
  8. * Execute 'node compiler.js' without arguments or with -h / --help for help.
  9. */
  10. /**
  11. * Map the async filter function onto array and evaluate callback, once all have finished.
  12. * Taken from: http://howtonode.org/control-flow-part-iii
  13. */
  14. function async_map(array, filter, callback) {
  15. if (0 === array.length) {
  16. callback(null, null);
  17. return;
  18. }
  19. var counter = array.length;
  20. var new_array = [];
  21. array.forEach(function (item, index) {
  22. filter(item, function (err, result) {
  23. if (err) { callback(err); return; }
  24. new_array[index] = result;
  25. counter--;
  26. if (counter === 0) {
  27. callback(null, new_array);
  28. }
  29. });
  30. });
  31. }
  32. /**
  33. * Always evaluates the callback parameter.
  34. * Used by Combo blocks to always call the next function,
  35. * even if all of the other functions did not run.
  36. */
  37. function always_resolve(callback) {
  38. callback();
  39. }
  40. /**
  41. * Helper for concatenating Amber generated AMD modules.
  42. * The produced output can be exported and run as an independent program.
  43. *
  44. * var concatenator = createConcatenator();
  45. * concatenator.start(); // write the required AMD define header
  46. * concatenator.add(module1);
  47. * concatenator.addId(module1_ID);
  48. * //...
  49. * concatenator.finish("//some last code");
  50. * var concatenation = concatenator.toString();
  51. * // The variable concatenation contains the concatenated result
  52. * // which can either be stored in a file or interpreted with eval().
  53. */
  54. function createConcatenator () {
  55. return {
  56. elements: [],
  57. ids: [],
  58. add: function () {
  59. this.elements.push.apply(this.elements, arguments);
  60. },
  61. addId: function () {
  62. this.ids.push.apply(this.ids, arguments);
  63. },
  64. forEach: function () {
  65. this.elements.forEach.apply(this.elements, arguments);
  66. },
  67. start: function () {
  68. this.add(
  69. 'var define = (' + require('amdefine') + ')(), requirejs = define.require;',
  70. 'define("amber_vm/browser-compatibility", [], {});'
  71. );
  72. },
  73. finish: function (realWork) {
  74. this.add(
  75. 'define("amber_vm/_init", ["amber_vm/smalltalk","' + this.ids.join('","') + '"], function (smalltalk) {',
  76. 'smalltalk.initialize();',
  77. realWork,
  78. '});',
  79. 'requirejs("amber_vm/_init");'
  80. );
  81. },
  82. toString: function () {
  83. return this.elements.join('\n');
  84. }
  85. };
  86. }
  87. /**
  88. * Combine several async functions and evaluate callback once all of them have finished.
  89. * Taken from: http://howtonode.org/control-flow
  90. */
  91. function Combo(callback) {
  92. this.callback = callback;
  93. this.items = 0;
  94. this.results = [];
  95. }
  96. Combo.prototype = {
  97. add: function () {
  98. var self = this,
  99. id = this.items;
  100. this.items++;
  101. return function () {
  102. self.check(id, arguments);
  103. };
  104. },
  105. check: function (id, arguments) {
  106. this.results[id] = Array.prototype.slice.call(arguments);
  107. this.items--;
  108. if (this.items == 0) {
  109. this.callback.apply(this, this.results);
  110. }
  111. }
  112. };
  113. var path = require('path'),
  114. util = require('util'),
  115. fs = require('fs'),
  116. exec = require('child_process').exec;
  117. /**
  118. * AmberC constructor function.
  119. * amber_dir: points to the location of an amber installation
  120. * closure_jar: location of compiler.jar (can be left undefined)
  121. */
  122. function AmberC(amber_dir, closure_jar) {
  123. this.amber_dir = amber_dir;
  124. this.closure_jar = closure_jar || '';
  125. this.kernel_libraries = ['@boot', '@smalltalk', '@nil', '@_st', 'Kernel-Objects', 'Kernel-Classes', 'Kernel-Methods',
  126. 'Kernel-Collections', 'Kernel-Infrastructure', 'Kernel-Exceptions', 'Kernel-Transcript',
  127. 'Kernel-Announcements'];
  128. this.compiler_libraries = this.kernel_libraries.concat(['@parser', 'Importer-Exporter', 'Compiler-Exceptions',
  129. 'Compiler-Core', 'Compiler-AST', 'Compiler-Exceptions', 'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic']);
  130. }
  131. /**
  132. * Default values.
  133. */
  134. var createDefaults = function(amber_dir, finished_callback){
  135. if (undefined === amber_dir) {
  136. throw new Error('createDefaults() function needs a valid amber_dir parameter');
  137. }
  138. return {
  139. 'load': [],
  140. 'main': undefined,
  141. 'mainfile': undefined,
  142. 'stFiles': [],
  143. 'jsFiles': [],
  144. 'jsGlobals': [],
  145. 'amd_namespace': 'amber_core',
  146. 'closure': false,
  147. 'closure_parts': false,
  148. 'closure_full': false,
  149. 'closure_options': ' --language_in=ECMASCRIPT5 ',
  150. 'suffix': '',
  151. 'loadsuffix': '',
  152. 'suffix_used': '',
  153. 'deploy': false,
  154. 'libraries': [],
  155. 'compile': [],
  156. 'compiled': [],
  157. 'program': undefined,
  158. 'output_dir': undefined,
  159. 'verbose': false,
  160. 'finished_callback': finished_callback
  161. };
  162. };
  163. /**
  164. * Main function for executing the compiler.
  165. * If check_configuration_ok() returns successfully the configuration is set on the current compiler
  166. * instance and check_for_closure_compiler() gets called.
  167. * The last step is to call collect_files().
  168. */
  169. AmberC.prototype.main = function(configuration, finished_callback) {
  170. console.time('Compile Time');
  171. if (undefined !== finished_callback) {
  172. configuration.finished_callback = finished_callback;
  173. }
  174. if (configuration.closure || configuration.closure_parts || configuration.closure_full) {
  175. configuration.deploy = true;
  176. }
  177. if (configuration.amd_namespace.length == 0) {
  178. configuration.amd_namespace = 'amber_core';
  179. }
  180. console.ambercLog = console.log;
  181. if (false === configuration.verbose) {
  182. console.log = function() {};
  183. }
  184. if (this.check_configuration_ok(configuration)) {
  185. this.defaults = configuration;
  186. this.defaults.smalltalk = {}; // the evaluated compiler will be stored in this variable (see create_compiler)
  187. var self = this;
  188. this.check_for_closure_compiler(function(){
  189. self.collect_files(self.defaults.stFiles, self.defaults.jsFiles)
  190. });
  191. }
  192. };
  193. /**
  194. * Check if the passed in configuration object has sufficient/nonconflicting values
  195. */
  196. AmberC.prototype.check_configuration_ok = function(configuration) {
  197. if (undefined === configuration) {
  198. throw new Error('AmberC.check_configuration_ok(): missing configuration object');
  199. }
  200. if (0 === configuration.jsFiles.length && 0 === configuration.stFiles.lenght) {
  201. throw new Error('AmberC.check_configuration_ok(): no files to compile/link specified in configuration object');
  202. }
  203. return true;
  204. };
  205. /**
  206. * Checks if the java executable exists and afterwards,
  207. * if compiler.jar exists at the path stored in this.closure_jar.
  208. * All closure related entries are set to false upon failure.
  209. *
  210. * callback gets called in any case.
  211. */
  212. AmberC.prototype.check_for_closure_compiler = function(callback) {
  213. var defaults = this.defaults;
  214. var self = this;
  215. if (defaults.closure) {
  216. exec('which java', function(error, stdout, stderr) {
  217. // stdout contains path to java executable
  218. if (null !== error) {
  219. console.warn('java is not installed but is needed for running the Closure compiler (-O, -A or -o flags).');
  220. defaults.closure = false;
  221. defaults.closure_parts = false;
  222. defaults.closure_full = false;
  223. callback();
  224. return;
  225. }
  226. fs.exists(self.closure_jar, function(exists) {
  227. if (!exists) {
  228. console.warn('Can not find Closure compiler at: ' + self.closure_jar);
  229. defaults.closure = false;
  230. defaults.closure_parts = false;
  231. defaults.closure_full = false;
  232. } else {
  233. console.warn('Closure compiler found at: ' + self.closure_jar);
  234. }
  235. callback();
  236. return;
  237. });
  238. });
  239. } else {
  240. callback();
  241. }
  242. };
  243. /**
  244. * Check if the file given as parameter exists in the local directory or in $AMBER/js/.
  245. * '.js' is appended first.
  246. *
  247. * @param filename name of a file without '.js' prefix
  248. * @param callback gets called on success with path to .js file as parameter
  249. */
  250. AmberC.prototype.resolve_js = function(filename, callback) {
  251. var special = filename[0] == "@";
  252. if (special) {
  253. filename = filename.slice(1);
  254. }
  255. var baseName = path.basename(filename, '.js');
  256. var jsFile = baseName + this.defaults.loadsuffix + '.js';
  257. var amberJsFile = path.join(this.amber_dir, special?'support':'js', jsFile);
  258. console.log('Resolving: ' + jsFile);
  259. fs.exists(jsFile, function(exists) {
  260. if (exists) {
  261. callback(jsFile);
  262. } else {
  263. fs.exists(amberJsFile, function(exists) {
  264. if (exists) {
  265. callback(amberJsFile);
  266. } else {
  267. throw(new Error('JavaScript file not found: ' + jsFile));
  268. }
  269. });
  270. }
  271. });
  272. };
  273. /**
  274. * Collect libraries and Smalltalk files looking
  275. * both locally and in $AMBER/js and $AMBER/st.
  276. * Followed by resolve_libraries().
  277. */
  278. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  279. var self = this;
  280. var collected_files = new Combo(function() {
  281. self.resolve_libraries();
  282. });
  283. if (0 !== stFiles.length) {
  284. self.collect_st_files(stFiles, collected_files.add());
  285. }
  286. if (0 !== jsFiles.length) {
  287. self.collect_js_files(jsFiles, collected_files.add());
  288. }
  289. };
  290. /**
  291. * Resolve st files given by stFiles and add them to defaults.compile.
  292. * Respective categories get added to defaults.compile_categories.
  293. * callback is evaluated afterwards.
  294. */
  295. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  296. var defaults = this.defaults;
  297. var self = this;
  298. var collected_st_files = new Combo(function() {
  299. Array.prototype.slice.call(arguments).forEach(function(data) {
  300. var stFile = data[0];
  301. defaults.compile.push(stFile);
  302. });
  303. callback();
  304. });
  305. stFiles.forEach(function(stFile) {
  306. var _callback = collected_st_files.add();
  307. console.log('Checking: ' + stFile);
  308. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  309. fs.exists(stFile, function(exists) {
  310. if (exists) {
  311. _callback(stFile);
  312. } else {
  313. console.log('Checking: ' + amberStFile);
  314. fs.exists(amberStFile, function(exists) {
  315. if (exists) {
  316. _callback(amberStFile);
  317. } else {
  318. throw(new Error('Smalltalk file not found: ' + amberStFile));
  319. }
  320. });
  321. }
  322. });
  323. });
  324. };
  325. /**
  326. * Resolve js files given by jsFiles and add them to defaults.libraries.
  327. * callback is evaluated afterwards.
  328. */
  329. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  330. var self = this;
  331. var collected_js_files = new Combo(function() {
  332. Array.prototype.slice.call(arguments).forEach(function(file) {
  333. self.defaults.libraries.push(file[0]);
  334. });
  335. callback();
  336. });
  337. jsFiles.forEach(function(jsFile) {
  338. self.resolve_js(jsFile, collected_js_files.add());
  339. });
  340. };
  341. /**
  342. * Resolve kernel and compiler files.
  343. * Followed by resolve_init().
  344. */
  345. AmberC.prototype.resolve_libraries = function() {
  346. // Resolve libraries listed in this.kernel_libraries
  347. var self = this;
  348. var all_resolved = new Combo(function(resolved_kernel_files, resolved_compiler_files) {
  349. self.create_compiler(resolved_compiler_files[0]);
  350. });
  351. this.resolve_kernel(all_resolved.add());
  352. this.resolve_compiler(all_resolved.add());
  353. };
  354. /**
  355. * Resolve .js files needed by kernel
  356. * callback is evaluated afterwards.
  357. */
  358. AmberC.prototype.resolve_kernel = function(callback) {
  359. var self = this;
  360. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  361. var kernel_resolved = new Combo(function() {
  362. var foundLibraries = [];
  363. Array.prototype.slice.call(arguments).forEach(function(file) {
  364. if (undefined !== file[0]) {
  365. foundLibraries.push(file[0]);
  366. }
  367. });
  368. // boot.js and Kernel files need to be used first
  369. // otherwise the global smalltalk object is undefined
  370. self.defaults.libraries = foundLibraries.concat(self.defaults.libraries);
  371. callback(null);
  372. });
  373. kernel_files.forEach(function(file) {
  374. self.resolve_js(file, kernel_resolved.add());
  375. });
  376. always_resolve(kernel_resolved.add());
  377. };
  378. /**
  379. * Resolve .js files needed by compiler.
  380. * callback is evaluated afterwards with resolved files as argument.
  381. */
  382. AmberC.prototype.resolve_compiler = function(callback) {
  383. // Resolve compiler libraries
  384. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  385. var compiler_resolved = new Combo(function() {
  386. var compilerFiles = [];
  387. Array.prototype.slice.call(arguments).forEach(function(file) {
  388. if (undefined !== file[0]) {
  389. compilerFiles.push(file[0]);
  390. }
  391. });
  392. callback(compilerFiles);
  393. });
  394. var self = this
  395. compiler_files.forEach(function(file) {
  396. self.resolve_js(file, compiler_resolved.add());
  397. });
  398. always_resolve(compiler_resolved.add());
  399. };
  400. /**
  401. * Read all .js files needed by compiler and eval() them.
  402. * The finished Compiler gets stored in defaults.smalltalk.
  403. * Followed by compile().
  404. */
  405. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  406. var self = this;
  407. var compiler_files = new Combo(function() {
  408. var builder = createConcatenator();
  409. builder.add('(function() {');
  410. builder.start();
  411. Array.prototype.slice.call(arguments).forEach(function(data) {
  412. // data is an array where index 0 is the error code and index 1 contains the data
  413. builder.add(data[1]);
  414. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  415. var match = ('' + data[1]).match(/^define\("([^"]*)"/);
  416. if (match) {
  417. builder.addId(match[1]);
  418. }
  419. });
  420. // store the generated smalltalk env in self.defaults.smalltalk
  421. builder.finish('self.defaults.smalltalk = smalltalk;');
  422. builder.add('})();');
  423. eval(builder.toString());
  424. console.log('Compiler loaded');
  425. self.defaults.smalltalk.ErrorHandler._setCurrent_(self.defaults.smalltalk.RethrowErrorHandler._new());
  426. if(0 != self.defaults.jsGlobals.length) {
  427. var jsGlobalVariables = self.defaults.smalltalk.globalJsVariables;
  428. jsGlobalVariables.push.apply(jsGlobalVariables, self.defaults.jsGlobals);
  429. }
  430. self.compile();
  431. });
  432. compilerFilesArray.forEach(function(file) {
  433. console.log('Loading file: ' + file);
  434. fs.readFile(file, compiler_files.add());
  435. });
  436. };
  437. /**
  438. * Compile all given .st files by importing them.
  439. * Followed by category_export().
  440. */
  441. AmberC.prototype.compile = function() {
  442. console.log('Compiling collected .st files')
  443. // import .st files
  444. var self = this;
  445. var imports = new Combo(function() {
  446. Array.prototype.slice.call(arguments).forEach(function(code) {
  447. if (undefined !== code[0]) {
  448. // get element 0 of code since all return values are stored inside an array by Combo
  449. self.defaults.smalltalk.Importer._new()._import_(code[0]._stream());
  450. }
  451. });
  452. self.category_export();
  453. });
  454. this.defaults.compile.forEach(function(stFile) {
  455. var callback = imports.add();
  456. if (/\.st/.test(stFile)) {
  457. console.ambercLog('Importing: ' + stFile);
  458. fs.readFile(stFile, 'utf8', function(err, data) {
  459. if (!err)
  460. callback(data);
  461. else
  462. throw new Error('Could not import: ' + stFile);
  463. });
  464. }
  465. });
  466. always_resolve(imports.add());
  467. };
  468. /**
  469. * Export compiled categories to JavaScript files.
  470. * Followed by verify().
  471. */
  472. AmberC.prototype.category_export = function() {
  473. var defaults = this.defaults;
  474. var self = this;
  475. // export categories as .js
  476. async_map(defaults.compile, function(stFile, callback) {
  477. var category = path.basename(stFile, '.st');
  478. var jsFilePath = defaults.output_dir;
  479. if (undefined === jsFilePath) {
  480. jsFilePath = path.dirname(stFile);
  481. }
  482. var jsFile = category + defaults.suffix_used + '.js';
  483. jsFile = path.join(jsFilePath, jsFile);
  484. defaults.compiled.push(jsFile);
  485. var jsFileDeploy = category + defaults.suffix_used + '.deploy.js';
  486. jsFileDeploy = path.join(jsFilePath, jsFileDeploy);
  487. console.log('Exporting ' + (defaults.deploy ? '(debug + deploy)' : '(debug)')
  488. + ' category ' + category + ' as ' + jsFile
  489. + (defaults.deploy ? ' and ' + jsFileDeploy : ''));
  490. var smalltalk = defaults.smalltalk;
  491. var pluggableExporter = smalltalk.PluggableExporter;
  492. var packageObject = smalltalk.Package._named_(category);
  493. packageObject._amdNamespace_(defaults.amd_namespace);
  494. fs.writeFile(jsFile, smalltalk.String._streamContents_(function (stream) {
  495. pluggableExporter._forRecipe_(smalltalk.Exporter._default()._amdRecipe())._exportPackage_on_(packageObject, stream); }), function(err) {
  496. if (defaults.deploy) {
  497. fs.writeFile(jsFileDeploy, smalltalk.String._streamContents_(function (stream) {
  498. pluggableExporter._forRecipe_(smalltalk.StrippedExporter._default()._amdRecipe())._exportPackage_on_(packageObject, stream); }), callback);
  499. } else {
  500. callback(null, null);
  501. }
  502. });
  503. }, function(err, result){
  504. self.verify();
  505. });
  506. };
  507. /**
  508. * Verify if all .st files have been compiled.
  509. * Followed by compose_js_files() and optimize().
  510. */
  511. AmberC.prototype.verify = function() {
  512. console.log('Verifying if all .st files were compiled');
  513. var self = this;
  514. // copy array
  515. var compiledFiles = this.defaults.compiled.slice(0);
  516. // append deploy files if necessary
  517. if (true === this.defaults.deploy) {
  518. this.defaults.compiled.forEach(function(file) {
  519. compiledFiles.push(file.replace(/\.js/g, '.deploy.js'));
  520. });
  521. }
  522. async_map(compiledFiles,
  523. function(file, callback) {
  524. fs.exists(file, function(exists) {
  525. if (exists)
  526. callback(null, null);
  527. else
  528. throw(new Error('Compilation failed of: ' + file));
  529. });
  530. }, function(err, result) {
  531. self.compose_js_files();
  532. });
  533. };
  534. /**
  535. * Synchronous function.
  536. * Concatenates compiled JavaScript files into one file in the correct order.
  537. * The name of the produced file is given by defaults.program (set by the last commandline option).
  538. */
  539. AmberC.prototype.compose_js_files = function() {
  540. var defaults = this.defaults;
  541. var self = this;
  542. var programFile = defaults.program;
  543. if (undefined === programFile) {
  544. self.optimize();
  545. return;
  546. }
  547. if (undefined !== defaults.output_dir) {
  548. programFile = path.join(defaults.output_dir, programFile);
  549. }
  550. var program_files = [];
  551. if (0 !== defaults.libraries.length) {
  552. console.log('Collecting libraries: ' + defaults.libraries);
  553. program_files.push.apply(program_files, defaults.libraries);
  554. }
  555. if (0 !== defaults.compiled.length) {
  556. var compiledFiles = defaults.compiled.slice(0);
  557. if (true === defaults.deploy) {
  558. compiledFiles = compiledFiles.map(function(file) {
  559. return file.replace(/\.js$/g, '.deploy.js');
  560. });
  561. }
  562. console.log('Collecting compiled files: ' + compiledFiles);
  563. program_files.push.apply(program_files, compiledFiles);
  564. }
  565. console.ambercLog('Writing program file: %s.js', programFile);
  566. var fileStream = fs.createWriteStream(programFile + defaults.suffix_used + '.js');
  567. fileStream.on('error', function(error) {
  568. fileStream.end();
  569. console.ambercLog(error);
  570. });
  571. fileStream.on('close', function(){
  572. self.optimize();
  573. });
  574. var builder = createConcatenator();
  575. builder.start();
  576. program_files.forEach(function(file) {
  577. if(fs.existsSync(file)) {
  578. console.log('Adding : ' + file);
  579. var buffer = fs.readFileSync(file);
  580. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  581. var match = buffer.toString().match(/^define\("([^"]*)"/);
  582. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  583. builder.addId(match[1]);
  584. }
  585. builder.add(buffer);
  586. } else {
  587. fileStream.end();
  588. throw(new Error('Can not find file ' + file));
  589. }
  590. });
  591. var mainFunctionOrFile = '';
  592. if (undefined !== defaults.main) {
  593. console.log('Adding call to: %s>>main', defaults.main);
  594. mainFunctionOrFile += 'smalltalk.' + defaults.main + '._main();';
  595. }
  596. if (undefined !== defaults.mainfile && fs.existsSync(defaults.mainfile)) {
  597. console.log('Adding main file: ' + defaults.mainfile);
  598. mainFunctionOrFile += '\n' + fs.readFileSync(defaults.mainfile);
  599. }
  600. builder.finish(mainFunctionOrFile);
  601. console.log('Writing...');
  602. builder.forEach(function (element) {
  603. fileStream.write(element);
  604. fileStream.write('\n');
  605. });
  606. console.log('Done.');
  607. fileStream.end();
  608. };
  609. /**
  610. * Optimize created JavaScript files with Google Closure compiler depending
  611. * on the flags: defaults.closure_parts, defaults.closure_full.
  612. */
  613. AmberC.prototype.optimize = function() {
  614. var defaults = this.defaults;
  615. var self = this;
  616. var optimization_done = new Combo(function() {
  617. console.log = console.ambercLog;
  618. console.timeEnd('Compile Time');
  619. if (undefined !== defaults.finished_callback) {
  620. defaults.finished_callback();
  621. }
  622. });
  623. if (defaults.closure_parts) {
  624. console.log('Compiling all js files using Google closure compiler.');
  625. defaults.compiled.forEach(function(file) {
  626. var deployFile = file.replace(/\.js$/g, '.deploy.js');
  627. console.log('Compiling ' + deployFile + ' file using Google closure compiler.');
  628. var minifiedName = deployFile.replace(/\.js$/g, '.min.js');
  629. self.closure_compile(deployFile, minifiedName, optimization_done.add());
  630. });
  631. }
  632. if (defaults.closure_full && (undefined !== defaults.program)) {
  633. var programFile = defaults.program;
  634. if (undefined !== defaults.output_dir) {
  635. programFile = path.join(defaults.output_dir, programFile);
  636. }
  637. console.log('Compiling ' + programFile + '.js file using Google closure compiler.');
  638. self.closure_compile(programFile + '.js', programFile + '.min.js', optimization_done.add());
  639. }
  640. always_resolve(optimization_done.add());
  641. };
  642. /**
  643. * Compile sourceFile into minifiedFile with Google Closure compiler.
  644. * callback gets executed once finished.
  645. */
  646. AmberC.prototype.closure_compile = function(sourceFile, minifiedFile, callback) {
  647. // exec is asynchronous
  648. var self = this;
  649. exec(
  650. 'java -jar ' +
  651. self.closure_jar + ' ' +
  652. self.defaults.closure_options +
  653. ' --js '+ sourceFile +
  654. ' --js_output_file '+ minifiedFile,
  655. function (error, stdout, stderr) {
  656. if (error) {
  657. console.log(stderr);
  658. } else {
  659. console.log(stdout);
  660. console.log('Minified: '+ minifiedFile);
  661. }
  662. callback();
  663. }
  664. );
  665. };
  666. module.exports.Compiler = AmberC;
  667. module.exports.createDefaults = createDefaults;
  668. module.exports.Combo = Combo;
  669. module.exports.map = async_map;