You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

359 line
9.0 KiB

  1. /*eslint-disable no-console */
  2. const path = require('path');
  3. const fs = require('fs');
  4. const babel = require('babel-core');
  5. const less = require('less');
  6. const chokidar = require('chokidar');
  7. const path_join = path.resolve;
  8. // for file watcher
  9. const app = require('express')();
  10. const http = require('http').Server(app);
  11. const io = require('socket.io')(http);
  12. const touch = require("touch");
  13. // basic setup
  14. const sites_path = path_join(__dirname, '..', '..', '..', 'sites');
  15. const apps_path = path_join(__dirname, '..', '..', '..', 'apps'); // the apps folder
  16. const apps_contents = fs.readFileSync(path_join(sites_path, 'apps.txt'), 'utf8');
  17. const apps = apps_contents.split('\n');
  18. const app_paths = apps.map(app => path_join(apps_path, app, app)) // base_path of each app
  19. const assets_path = path_join(sites_path, 'assets');
  20. let build_map = make_build_map();
  21. let compiled_js_cache = {}; // cache each js file after it is compiled
  22. const file_watcher_port = get_conf().file_watcher_port;
  23. // command line args
  24. const action = process.argv[2] || '--build';
  25. if (['--build', '--watch'].indexOf(action) === -1) {
  26. console.log('Invalid argument: ', action);
  27. process.exit();
  28. }
  29. if (action === '--build') {
  30. const minify = process.argv[3] === '--minify' ? true : false;
  31. build(minify);
  32. }
  33. if (action === '--watch') {
  34. watch();
  35. }
  36. function build(minify) {
  37. for (const output_path in build_map) {
  38. pack(output_path, build_map[output_path], minify);
  39. }
  40. touch(path_join(sites_path, '.build'), {force:true});
  41. }
  42. let socket_connection = false;
  43. function watch() {
  44. http.listen(file_watcher_port, function () {
  45. console.log('file watching on *:', file_watcher_port);
  46. });
  47. if (process.env.CI) {
  48. // don't watch inside CI
  49. return;
  50. }
  51. compile_less().then(() => {
  52. build();
  53. watch_less(function (filename) {
  54. if(socket_connection) {
  55. io.emit('reload_css', filename);
  56. }
  57. });
  58. watch_js(//function (filename) {
  59. // if(socket_connection) {
  60. // io.emit('reload_js', filename);
  61. // }
  62. //}
  63. );
  64. watch_build_json();
  65. });
  66. io.on('connection', function (socket) {
  67. socket_connection = true;
  68. socket.on('disconnect', function() {
  69. socket_connection = false;
  70. })
  71. });
  72. }
  73. function pack(output_path, inputs, minify, file_changed) {
  74. let output_txt = '';
  75. for (const file of inputs) {
  76. if (!fs.existsSync(file)) {
  77. console.log('File not found: ', file);
  78. continue;
  79. }
  80. let force_compile = false;
  81. if (file_changed) {
  82. // if file_changed is passed and is equal to file, force_compile it
  83. force_compile = file_changed === file;
  84. }
  85. let file_content = get_compiled_file(file, output_path, minify, force_compile);
  86. if(!minify) {
  87. output_txt += `\n/*\n *\t${file}\n */\n`
  88. }
  89. output_txt += file_content;
  90. output_txt = output_txt.replace(/['"]use strict['"];/, '');
  91. }
  92. const target = path_join(assets_path, output_path);
  93. try {
  94. fs.writeFileSync(target, output_txt);
  95. console.log(`Wrote ${output_path} - ${get_file_size(target)}`);
  96. return target;
  97. } catch (e) {
  98. console.log('Error writing to file', output_path);
  99. console.log(e);
  100. }
  101. }
  102. function get_compiled_file(file, output_path, minify, force_compile) {
  103. const output_type = output_path.split('.').pop();
  104. let file_content;
  105. if (force_compile === false) {
  106. // force compile is false
  107. // attempt to get from cache
  108. file_content = compiled_js_cache[file];
  109. if (file_content) {
  110. return file_content;
  111. }
  112. }
  113. file_content = fs.readFileSync(file, 'utf-8');
  114. if (file.endsWith('.html') && output_type === 'js') {
  115. file_content = html_to_js_template(file, file_content);
  116. }
  117. if(file.endsWith('class.js')) {
  118. file_content = minify_js(file_content, file);
  119. }
  120. if (file.endsWith('.js') && !file.includes('/lib/') && output_type === 'js' && !file.endsWith('class.js')) {
  121. file_content = babelify(file_content, file, minify);
  122. }
  123. compiled_js_cache[file] = file_content;
  124. return file_content;
  125. }
  126. function babelify(content, path, minify) {
  127. let presets = ['env'];
  128. // Minification doesn't work when loading Frappe Desk
  129. // Avoid for now, trace the error and come back.
  130. try {
  131. return babel.transform(content, {
  132. presets: presets,
  133. comments: false
  134. }).code;
  135. } catch (e) {
  136. console.log('Cannot babelify', path);
  137. console.log(e);
  138. return content;
  139. }
  140. }
  141. function minify_js(content, path) {
  142. try {
  143. return babel.transform(content, {
  144. comments: false
  145. }).code;
  146. } catch (e) {
  147. console.log('Cannot minify', path);
  148. console.log(e);
  149. return content;
  150. }
  151. }
  152. function make_build_map() {
  153. const build_map = {};
  154. for (const app_path of app_paths) {
  155. const build_json_path = path_join(app_path, 'public', 'build.json');
  156. if (!fs.existsSync(build_json_path)) continue;
  157. let build_json = fs.readFileSync(build_json_path);
  158. try {
  159. build_json = JSON.parse(build_json);
  160. } catch (e) {
  161. console.log(e);
  162. continue;
  163. }
  164. for (const target in build_json) {
  165. const sources = build_json[target];
  166. const new_sources = [];
  167. for (const source of sources) {
  168. const s = path_join(app_path, source);
  169. new_sources.push(s);
  170. }
  171. if (new_sources.length)
  172. build_json[target] = new_sources;
  173. else
  174. delete build_json[target];
  175. }
  176. Object.assign(build_map, build_json);
  177. }
  178. return build_map;
  179. }
  180. function compile_less() {
  181. return new Promise(function (resolve) {
  182. const promises = [];
  183. for (const app_path of app_paths) {
  184. const public_path = path_join(app_path, 'public');
  185. const less_path = path_join(public_path, 'less');
  186. if (!fs.existsSync(less_path)) continue;
  187. const files = fs.readdirSync(less_path);
  188. for (const file of files) {
  189. if(file.includes('variables.less')) continue;
  190. promises.push(compile_less_file(file, less_path, public_path))
  191. }
  192. }
  193. Promise.all(promises).then(() => {
  194. console.log('Less files compiled');
  195. resolve();
  196. });
  197. });
  198. }
  199. function compile_less_file(file, less_path, public_path) {
  200. const file_content = fs.readFileSync(path_join(less_path, file), 'utf8');
  201. const output_file = file.split('.')[0] + '.css';
  202. console.log('compiling', file);
  203. return less.render(file_content, {
  204. paths: [less_path],
  205. filename: file,
  206. sourceMap: false
  207. }).then(output => {
  208. const out_css = path_join(public_path, 'css', output_file);
  209. fs.writeFileSync(out_css, output.css);
  210. return out_css;
  211. }).catch(e => {
  212. console.log('Error compiling ', file);
  213. console.log(e);
  214. });
  215. }
  216. function watch_less(ondirty) {
  217. const less_paths = app_paths.map(path => path_join(path, 'public', 'less'));
  218. const to_watch = filter_valid_paths(less_paths);
  219. chokidar.watch(to_watch).on('change', (filename) => {
  220. console.log(filename, 'dirty');
  221. var last_index = filename.lastIndexOf('/');
  222. const less_path = filename.slice(0, last_index);
  223. const public_path = path_join(less_path, '..');
  224. filename = filename.split('/').pop();
  225. compile_less_file(filename, less_path, public_path)
  226. .then(css_file_path => {
  227. // build the target css file for which this css file is input
  228. for (const target in build_map) {
  229. const sources = build_map[target];
  230. if (sources.includes(css_file_path)) {
  231. pack(target, sources);
  232. ondirty && ondirty(target);
  233. break;
  234. }
  235. }
  236. });
  237. touch(path_join(sites_path, '.build'), {force:true});
  238. });
  239. }
  240. function watch_js(ondirty) {
  241. chokidar.watch([
  242. path_join(apps_path, '**', '*.js'),
  243. path_join(apps_path, '**', '*.html')
  244. ]).on('change', (filename) => {
  245. // build the target js file for which this js/html file is input
  246. for (const target in build_map) {
  247. const sources = build_map[target];
  248. if (sources.includes(filename)) {
  249. console.log(filename, 'dirty');
  250. pack(target, sources, null, filename);
  251. ondirty && ondirty(target);
  252. // break;
  253. }
  254. }
  255. touch(path_join(sites_path, '.build'), {force:true});
  256. });
  257. }
  258. function watch_build_json() {
  259. const build_json_paths = app_paths.map(path => path_join(path, 'public', 'build.json'));
  260. const to_watch = filter_valid_paths(build_json_paths);
  261. chokidar.watch(to_watch).on('change', (filename) => {
  262. console.log(filename, 'updated');
  263. build_map = make_build_map();
  264. });
  265. }
  266. function filter_valid_paths(paths) {
  267. return paths.filter(path => fs.existsSync(path));
  268. }
  269. function html_to_js_template(path, content) {
  270. let key = path.split('/');
  271. key = key[key.length - 1];
  272. key = key.split('.')[0];
  273. content = scrub_html_template(content);
  274. return `frappe.templates['${key}'] = '${content}';\n`;
  275. }
  276. function scrub_html_template(content) {
  277. content = content.replace(/\s/g, ' ');
  278. content = content.replace(/(<!--.*?-->)/g, '');
  279. return content.replace("'", "\'");
  280. }
  281. function get_file_size(filepath) {
  282. const stats = fs.statSync(filepath);
  283. const size = stats.size;
  284. // convert it to humanly readable format.
  285. const i = Math.floor(Math.log(size) / Math.log(1024));
  286. return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
  287. }
  288. function get_conf() {
  289. // defaults
  290. var conf = {
  291. file_watcher_port: 6787
  292. };
  293. var read_config = function(path) {
  294. if (!fs.existsSync(path)) return;
  295. var bench_config = JSON.parse(fs.readFileSync(path));
  296. for (var key in bench_config) {
  297. if (bench_config[key]) {
  298. conf[key] = bench_config[key];
  299. }
  300. }
  301. }
  302. read_config(path_join(sites_path, 'common_site_config.json'));
  303. return conf;
  304. }