amberc.js 11 KB

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