amberc.js 11 KB

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