amberc.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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');
  6. * var options = amberc.createDefaults();
  7. * // edit options entries
  8. * compiler.main(options);
  9. */
  10. var path = require('path'),
  11. fs = require('fs'),
  12. requirejs = require('requirejs');
  13. /**
  14. * AmberCompiler constructor function.
  15. * amber_dir: points to the location of an amber installation
  16. */
  17. function AmberCompiler(amber_dir) {
  18. if (amber_dir == null || !fs.existsSync(amber_dir)) {
  19. throw new Error('amber_dir needs to be a valid directory');
  20. }
  21. this.amber_dir = amber_dir;
  22. }
  23. /**
  24. * Default values.
  25. */
  26. var createDefaultConfiguration = function () {
  27. return {
  28. paths: {},
  29. configFile: null,
  30. load: [],
  31. stFiles: [],
  32. jsGlobals: [],
  33. amdNamespace: 'amber_core',
  34. compile: [],
  35. compiled: [],
  36. outputDir: undefined,
  37. verbose: false
  38. };
  39. };
  40. /**
  41. * Main function for executing the compiler.
  42. * If check_configuration_ok() returns successfully
  43. * the configuration is used to trigger the following compilation steps.
  44. */
  45. AmberCompiler.prototype.main = function (configuration, finished_callback) {
  46. console.time('Compile Time');
  47. if (configuration.amdNamespace.length === 0) {
  48. configuration.amdNamespace = 'amber_core';
  49. }
  50. console.ambercLog = console.log;
  51. if (false === configuration.verbose) {
  52. console.log = function () {
  53. };
  54. }
  55. // the evaluated compiler will be stored in this variable (see create_compiler)
  56. configuration.core = {};
  57. configuration.globals = {};
  58. configuration.amber_dir = this.amber_dir;
  59. var rjsConfig;
  60. if (configuration.configFile) {
  61. var configSrc = fs.readFileSync(configuration.configFile, "utf8");
  62. rjsConfig = (function () {
  63. var require, requirejs;
  64. requirejs = require = {
  65. config: function (x) {
  66. requirejs = require = x;
  67. }
  68. };
  69. eval(configSrc);
  70. return require;
  71. })();
  72. } else {
  73. rjsConfig = {
  74. paths: configuration.paths
  75. };
  76. }
  77. if (!rjsConfig.paths.amber) {
  78. rjsConfig.paths.amber = path.join(this.amber_dir, 'base');
  79. }
  80. if (!rjsConfig.paths.amber_core) rjsConfig.paths.amber_core = path.join(this.amber_dir, 'src');
  81. rjsConfig.paths['text'] = require.resolve('requirejs-text').replace(/\.js$/, "");
  82. rjsConfig.paths['amber/without-imports'] = path.join(__dirname, 'without-imports');
  83. rjsConfig.nodeRequire = require;
  84. rjsConfig.context = "amberc";
  85. configuration.requirejs = requirejs.config(rjsConfig);
  86. check_configuration(configuration)
  87. .then(collect_st_files)
  88. .then(create_compiler)
  89. .then(compile)
  90. .then(category_export)
  91. .then(verify)
  92. .then(function () {
  93. console.timeEnd('Compile Time');
  94. }, function (error) {
  95. console.error(error);
  96. })
  97. .then(function () {
  98. console.log = console.ambercLog;
  99. finished_callback && finished_callback();
  100. });
  101. };
  102. /**
  103. * Check if the passed in configuration object has sufficient/nonconflicting values.
  104. * Returns a Promise which resolves into the configuration object.
  105. */
  106. function check_configuration(configuration) {
  107. return new Promise(function (resolve, reject) {
  108. if (configuration == null) {
  109. reject(Error('AmberCompiler.check_configuration_ok(): missing configuration object'));
  110. }
  111. if (0 === configuration.stFiles.length) {
  112. reject(Error('AmberCompiler.check_configuration_ok(): no files to compile specified in configuration object'));
  113. }
  114. resolve(configuration);
  115. });
  116. }
  117. /**
  118. * Check if the file given as parameter exists in any of the following directories:
  119. * 1. current local directory
  120. * 2. $AMBER/
  121. *
  122. * @param filename name of a .st file
  123. * @param configuration the main amberc configuration object
  124. */
  125. function resolve_st(filename, configuration) {
  126. return resolve_file(filename, [configuration.amber_dir]);
  127. }
  128. /**
  129. * Resolve the location of a file given as parameter filename.
  130. * First check if the file exists at given location,
  131. * then check in each of the directories specified in parameter searchDirectories.
  132. */
  133. function resolve_file(filename, searchDirectories) {
  134. return new Promise(function (resolve, reject) {
  135. console.log('Resolving: ' + filename);
  136. fs.exists(filename, function (exists) {
  137. if (exists) {
  138. resolve(filename);
  139. } else {
  140. var alternativeFile = '';
  141. // check for filename in any of the given searchDirectories
  142. var found = searchDirectories.some(function (directory) {
  143. alternativeFile = path.join(directory, filename);
  144. return fs.existsSync(alternativeFile);
  145. });
  146. if (found) {
  147. resolve(alternativeFile);
  148. } else {
  149. reject(Error('File not found: ' + alternativeFile));
  150. }
  151. }
  152. });
  153. });
  154. }
  155. /**
  156. * Resolve st files given by stFiles and add them to configuration.compile.
  157. * Returns a Promise which resolves into the configuration object.
  158. */
  159. function collect_st_files(configuration) {
  160. return Promise.all(
  161. configuration.stFiles.map(function (stFile) {
  162. return resolve_st(stFile, configuration);
  163. })
  164. )
  165. .then(function (data) {
  166. configuration.compile = configuration.compile.concat(data);
  167. return configuration;
  168. });
  169. }
  170. /**
  171. * Resolve .js files needed by compiler, read and eval() them.
  172. * The finished Compiler gets stored in configuration.{core,globals}.
  173. * Returns a Promise object which resolves into the configuration object.
  174. */
  175. function create_compiler(configuration) {
  176. var include_files = configuration.load;
  177. return new Promise(configuration.requirejs.bind(null, ["amber/lang", "amber_core/Platform-Node"]))
  178. .then(function (boot) {
  179. configuration.core = boot.api;
  180. configuration.globals = boot.globals;
  181. return boot.api.initialize();
  182. })
  183. .then(function () {
  184. var pluginPrefixedLibraries = include_files.map(function (each) {
  185. return 'amber/without-imports!' + each;
  186. });
  187. return new Promise(configuration.requirejs.bind(null, pluginPrefixedLibraries));
  188. })
  189. .then(function () {
  190. return configuration.globals.Smalltalk._adoptPackageDescriptors();
  191. })
  192. .then(function () {
  193. console.log('Compiler loaded');
  194. configuration.jsGlobals.forEach(function (each) {
  195. configuration.globals.Smalltalk._addGlobalJsVariable_(each);
  196. });
  197. return configuration;
  198. });
  199. }
  200. /**
  201. * Compile all given .st files by importing them.
  202. * Returns a Promise object that resolves into the configuration object.
  203. */
  204. function compile(configuration) {
  205. // return function which does the actual work
  206. // and use the compile function to reference the configuration object
  207. return Promise.all(
  208. configuration.compile.map(function (stFile) {
  209. return new Promise(function (resolve, reject) {
  210. if (/\.st/.test(stFile)) {
  211. console.ambercLog('Reading: ' + stFile);
  212. fs.readFile(stFile, 'utf8', function (err, data) {
  213. if (!err)
  214. resolve(data);
  215. else
  216. reject(Error('Could not read: ' + stFile));
  217. });
  218. }
  219. });
  220. })
  221. )
  222. .then(function (fileContents) {
  223. console.log('Compiling collected .st files');
  224. // import/compile content of .st files
  225. return Promise.all(
  226. fileContents.map(function (code) {
  227. return new Promise(function (resolve, reject) {
  228. var importer = configuration.globals.Importer._new();
  229. try {
  230. importer._import_(code._stream());
  231. resolve(true);
  232. } catch (ex) {
  233. reject(Error("Compiler error in section:\n" +
  234. importer._lastSection() + "\n\n" +
  235. "while processing chunk:\n" +
  236. importer._lastChunk() + "\n\n" +
  237. (ex._messageText && ex._messageText() || ex.message || ex))
  238. );
  239. }
  240. });
  241. })
  242. );
  243. })
  244. .then(function () {
  245. return configuration;
  246. });
  247. }
  248. /**
  249. * Export compiled categories to JavaScript files.
  250. * Returns a Promise() that resolves into the configuration object.
  251. */
  252. function category_export(configuration) {
  253. return Promise.all(
  254. configuration.compile.map(function (stFile) {
  255. return new Promise(function (resolve, reject) {
  256. var category = path.basename(stFile, '.st');
  257. var jsFilePath = configuration.outputDir;
  258. if (jsFilePath == null) {
  259. jsFilePath = path.dirname(stFile);
  260. }
  261. var jsFile = category + '.js';
  262. jsFile = path.join(jsFilePath, jsFile);
  263. configuration.compiled.push(jsFile);
  264. var smalltalkGlobals = configuration.globals;
  265. var packageObject = smalltalkGlobals.Package._named_(category);
  266. packageObject._transport()._namespace_(configuration.amdNamespace);
  267. fs.writeFile(jsFile, smalltalkGlobals.String._streamContents_(function (stream) {
  268. smalltalkGlobals.AmdExporter._new()._exportPackage_on_(packageObject, stream);
  269. }), function (err) {
  270. if (err)
  271. reject(err);
  272. else
  273. resolve(true);
  274. });
  275. });
  276. })
  277. )
  278. .then(function () {
  279. return configuration;
  280. });
  281. }
  282. /**
  283. * Verify if all .st files have been compiled.
  284. * Returns a Promise() that resolves into the configuration object.
  285. */
  286. function verify(configuration) {
  287. console.log('Verifying if all .st files were compiled');
  288. return Promise.all(
  289. configuration.compiled.map(function (file) {
  290. return new Promise(function (resolve, reject) {
  291. fs.exists(file, function (exists) {
  292. if (exists)
  293. resolve(true);
  294. else
  295. reject(Error('Compilation failed of: ' + file));
  296. });
  297. });
  298. })
  299. )
  300. .then(function () {
  301. return configuration;
  302. });
  303. }
  304. module.exports.Compiler = AmberCompiler;
  305. module.exports.createDefaultConfiguration = createDefaultConfiguration;