utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. const {encode} = require('html-entities');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const webpack = require('webpack');
  5. const CleanCSS = require('clean-css');
  6. const uglifyjs = require('uglify-js');
  7. const {lib_paths, css_paths, js_paths} = require('./src/static-assets.js');
  8. /**
  9. * Builds the application by performing various tasks such as cleaning the distribution directory,
  10. * merging and minifying JavaScript and CSS files, bundling GUI core files, handling images,
  11. * and preparing the final distribution package. The process involves concatenating library
  12. * scripts, optimizing them for production, and copying essential assets to the distribution
  13. * directory. The function also supports a verbose mode for logging detailed information during
  14. * the build process.
  15. *
  16. * @param {Object} [options] - Optional parameters to customize the build process.
  17. * @param {boolean} [options.verbose=false] - Specifies whether to log detailed information during the build.
  18. *
  19. * @async
  20. * @returns {Promise<void>} A promise that resolves when the build process is complete.
  21. *
  22. * @example
  23. * build({ verbose: true }).then(() => {
  24. * console.log('Build process completed successfully.');
  25. * }).catch(error => {
  26. * console.error('Build process failed:', error);
  27. * });
  28. */
  29. async function build(options){
  30. // -----------------------------------------------
  31. // Delete ./dist/ directory if it exists and create a new one
  32. // -----------------------------------------------
  33. if(fs.existsSync(path.join(__dirname, 'dist'))){
  34. fs.rmSync(path.join(__dirname, 'dist'), {recursive: true});
  35. }
  36. fs.mkdirSync(path.join(__dirname, 'dist'));
  37. // -----------------------------------------------
  38. // Concat/merge the JS libraries and save them to ./dist/libs.js
  39. // -----------------------------------------------
  40. let js = '';
  41. for(let i = 0; i < lib_paths.length; i++){
  42. const file = path.join(__dirname, 'src', lib_paths[i]);
  43. // js
  44. if(file.endsWith('.js') && !file.endsWith('.min.js')){
  45. let minified_code = await uglifyjs.minify(fs.readFileSync(file).toString(), {mangle: false});
  46. if(minified_code && minified_code.code){
  47. js += minified_code.code;
  48. if(options?.verbose)
  49. console.log('minified: ', file);
  50. }
  51. }else{
  52. js += fs.readFileSync(file);
  53. if(options?.verbose)
  54. console.log('skipped minification: ', file);
  55. }
  56. js += '\n\n\n';
  57. }
  58. // -----------------------------------------------
  59. // Combine all images into a single js file
  60. // -----------------------------------------------
  61. let icons = 'window.icons = [];\n\n\n';
  62. fs.readdirSync(path.join(__dirname, 'src/icons')).forEach(file => {
  63. // skip dotfiles
  64. if(file.startsWith('.'))
  65. return;
  66. // load image
  67. let buff = new Buffer.from(fs.readFileSync(path.join(__dirname, 'src/icons') + '/' + file));
  68. // convert to base64
  69. let base64data = buff.toString('base64');
  70. // add to `window.icons`
  71. if(file.endsWith('.png'))
  72. icons += `window.icons['${file}'] = "data:image/png;base64,${base64data}";\n`;
  73. else if(file.endsWith('.svg'))
  74. icons += `window.icons['${file}'] = "data:image/svg+xml;base64,${base64data}";\n`;
  75. });
  76. // -----------------------------------------------
  77. // concat/merge the CSS files and save them to ./dist/bundle.min.css
  78. // -----------------------------------------------
  79. let css = '';
  80. for(let i = 0; i < css_paths.length; i++){
  81. let fullpath = path.join(__dirname, 'src', css_paths[i]);
  82. // minify CSS files if not already minified, then concatenate
  83. if(css_paths[i].endsWith('.css') && !css_paths[i].endsWith('.min.css')){
  84. const minified_css = new CleanCSS({}).minify(fs.readFileSync(fullpath).toString());
  85. css += minified_css.styles;
  86. }
  87. // otherwise, just concatenate the file
  88. else
  89. css += fs.readFileSync(path.join(__dirname, 'src', css_paths[i]));
  90. // add newlines between files
  91. css += '\n\n\n';
  92. }
  93. fs.writeFileSync(path.join(__dirname, 'dist', 'bundle.min.css'), css);
  94. // -----------------------------------------------
  95. // Bundle GUI core and merge all files into a single JS file
  96. // -----------------------------------------------
  97. let main_array = [];
  98. for(let i = 0; i < js_paths.length; i++){
  99. main_array.push(path.join(__dirname, 'src', js_paths[i]));
  100. }
  101. webpack({
  102. mode: 'production',
  103. entry: {
  104. main: main_array,
  105. },
  106. output: {
  107. path: path.resolve(__dirname, 'dist'),
  108. filename: '[name].js',
  109. },
  110. optimization: {
  111. minimize: true,
  112. },
  113. }, (err, stats) => {
  114. if(err){
  115. console.error(err);
  116. return;
  117. }
  118. if(options?.verbose)
  119. console.log(stats.toString());
  120. // write to ./dist/bundle.min.js
  121. fs.writeFileSync(path.join(__dirname, 'dist', 'bundle.min.js'), icons + '\n\n\n' + js + '\n\n\n' + fs.readFileSync(path.join(__dirname, 'dist', 'main.js')));
  122. // remove ./dist/main.js
  123. fs.unlinkSync(path.join(__dirname, 'dist', 'main.js'));
  124. });
  125. // Copy index.js to dist/gui.js
  126. // Prepend `window.gui_env="prod";` to `./dist/gui.js`
  127. fs.writeFileSync(
  128. path.join(__dirname, 'dist', 'gui.js'),
  129. `window.gui_env="prod"; \n\n` + fs.readFileSync(path.join(__dirname, 'src', 'index.js'))
  130. );
  131. const copy_these = [
  132. 'images', 'favicons',
  133. 'browserconfig.xml', 'manifest.json', 'favicon.ico',
  134. ];
  135. const recursive_copy = (src, dest) => {
  136. const stat = fs.statSync(src);
  137. if ( stat.isDirectory() ) {
  138. if( ! fs.existsSync(dest) ) fs.mkdirSync(dest);
  139. const files = fs.readdirSync(src);
  140. for ( const file of files ) {
  141. recursive_copy(path.join(src, file), path.join(dest, file));
  142. }
  143. } else {
  144. fs.copyFileSync(src, dest);
  145. }
  146. };
  147. for ( const to_copy of copy_these ) {
  148. recursive_copy(path.join(__dirname, 'src', to_copy), path.join(__dirname, 'dist', to_copy));
  149. }
  150. }
  151. /**
  152. * Generates the HTML content for the GUI based on the specified configuration options. The function
  153. * creates a new HTML document with the specified title, description, and other metadata. The function
  154. * also includes the necessary CSS and JavaScript files, as well as the required meta tags for social
  155. * media sharing and search engine optimization. The function is designed to be used in development
  156. * environments to generate the HTML content for the GUI.
  157. *
  158. * @param {Object} options - The configuration options for the GUI.
  159. * @param {string} options.env - The environment in which the GUI is running (e.g., "dev" or "prod").
  160. * @param {string} options.api_origin - The origin of the API server.
  161. * @param {string} options.title - The title of the GUI.
  162. * @param {string} options.company - The name of the company or organization.
  163. * @param {string} options.description - The description of the GUI.
  164. * @param {string} options.app_description - The description of the application.
  165. * @param {string} options.short_description - The short description of the GUI.
  166. * @param {string} options.origin - The origin of the GUI.
  167. * @param {string} options.social_card - The URL of the social media card image.
  168. * @returns {string} The HTML content for the GUI based on the specified configuration options.
  169. *
  170. */
  171. function generateDevHtml(options){
  172. let start_t = Date.now();
  173. // final html string
  174. let h = '';
  175. h += `<!DOCTYPE html>`;
  176. h += `<html lang="en">`;
  177. h += `<head>`;
  178. h += `<title>${encode((options.title))}</title>`
  179. h += `<meta name="author" content="${encode(options.company)}">`
  180. // description
  181. let description = options.description;
  182. // if app_description is set, use that instead
  183. if(options.app_description){
  184. description = options.app_description;
  185. }
  186. // if no app_description is set, use short_description if set
  187. else if(options.short_description){
  188. description = options.short_description;
  189. }
  190. // description
  191. h += `<meta name="description" content="${encode((description).replace(/\n/g, " "))}">`
  192. // facebook domain verification
  193. h += `<meta name="facebook-domain-verification" content="e29w3hjbnnnypf4kzk2cewcdaxym1y" />`;
  194. // canonical url
  195. h += `<link rel="canonical" href="${options.origin}">`;
  196. // DEV: load every CSS file individually
  197. if(options.env === 'dev'){
  198. for(let i = 0; i < css_paths.length; i++){
  199. h += `<link rel="stylesheet" href="${css_paths[i]}">`;
  200. }
  201. }
  202. // Facebook meta tags
  203. h += `<meta property="og:url" content="https://${options.domain}">`;
  204. h += `<meta property="og:type" content="website">`;
  205. h += `<meta property="og:title" content="${encode(options.title)}">`;
  206. h += `<meta property="og:description" content="${encode((options.short_description).replace(/\n/g, " "))}">`;
  207. h += `<meta property="og:image" content="${options.social_card}">`;
  208. // Twitter meta tags
  209. h += `<meta name="twitter:card" content="summary_large_image">`;
  210. h += `<meta property="twitter:domain" content="${options.domain}">`;
  211. h += `<meta property="twitter:url" content="https://${options.domain}">`;
  212. h += `<meta name="twitter:title" content="${encode(options.title)}">`;
  213. h += `<meta name="twitter:description" content="${encode((options.short_description).replace(/\n/g, " "))}">`;
  214. h += `<meta name="twitter:image" content="${options.social_card}">`;
  215. // favicons
  216. h += `
  217. <link rel="apple-touch-icon" sizes="57x57" href="/favicons/apple-icon-57x57.png">
  218. <link rel="apple-touch-icon" sizes="60x60" href="/favicons/apple-icon-60x60.png">
  219. <link rel="apple-touch-icon" sizes="72x72" href="/favicons/apple-icon-72x72.png">
  220. <link rel="apple-touch-icon" sizes="76x76" href="/favicons/apple-icon-76x76.png">
  221. <link rel="apple-touch-icon" sizes="114x114" href="/favicons/apple-icon-114x114.png">
  222. <link rel="apple-touch-icon" sizes="120x120" href="/favicons/apple-icon-120x120.png">
  223. <link rel="apple-touch-icon" sizes="144x144" href="/favicons/apple-icon-144x144.png">
  224. <link rel="apple-touch-icon" sizes="152x152" href="/favicons/apple-icon-152x152.png">
  225. <link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-icon-180x180.png">
  226. <link rel="icon" type="image/png" sizes="192x192" href="/favicons/android-icon-192x192.png">
  227. <link rel="icon" type="image/png" sizes="32x32" href="/favicons/favicon-32x32.png">
  228. <link rel="icon" type="image/png" sizes="96x96" href="/favicons/favicon-96x96.png">
  229. <link rel="icon" type="image/png" sizes="16x16" href="/favicons/favicon-16x16.png">
  230. <link rel="manifest" href="/manifest.json">
  231. <meta name="msapplication-TileColor" content="#ffffff">
  232. <meta name="msapplication-TileImage" content="/favicons/ms-icon-144x144.png">
  233. <meta name="theme-color" content="#ffffff">`;
  234. // preload images when applicable
  235. h += `<link rel="preload" as="image" href="./images/wallpaper.webp">`;
  236. h += `</head>`;
  237. h += `<body>`;
  238. // To indicate that the GUI is running to any 3rd-party scripts that may be running on the page
  239. // specifically, the `puter.js` script
  240. // This line is also present verbatim in `src/index.js` for production builds
  241. h += `<script>window.puter_gui_enabled = true;</script>`;
  242. // DEV: load every JS library individually
  243. if(options.env === 'dev'){
  244. for(let i = 0; i < lib_paths.length; i++){
  245. h += `<script src="${lib_paths[i]}"></script>`;
  246. }
  247. }
  248. // load images and icons as base64 for performance
  249. if(options.env === 'dev'){
  250. h += `<script>`;
  251. h += `window.icons = {};`
  252. fs.readdirSync(path.join(__dirname, 'src/icons')).forEach(file => {
  253. // skip dotfiles
  254. if(file.startsWith('.'))
  255. return;
  256. // load image
  257. let buff = new Buffer.from(fs.readFileSync(path.join(__dirname, 'src/icons') + '/' + file));
  258. // convert to base64
  259. let base64data = buff.toString('base64');
  260. // add to `window.icons`
  261. if(file.endsWith('.png'))
  262. h += `window.icons['${file}'] = "data:image/png;base64,${base64data}";\n`;
  263. else if(file.endsWith('.svg'))
  264. h += `window.icons['${file}'] = "data:image/svg+xml;base64,${base64data}";\n`;
  265. });
  266. h += `</script>`;
  267. }
  268. // PROD: gui.js
  269. if(options.env === 'prod'){
  270. h += `<script src="/dist/gui.js"></script>`;
  271. }
  272. // DEV: load every JS file individually
  273. else{
  274. for(let i = 0; i < js_paths.length; i++){
  275. h += `<script type="module" src="${js_paths[i]}"></script>`;
  276. }
  277. // load GUI
  278. h += `<script type="module" src="/index.js"></script>`;
  279. }
  280. // ----------------------------------------
  281. // Initialize GUI with config options
  282. // ----------------------------------------
  283. h += `
  284. <script type="text/javascript">
  285. window.addEventListener('load', function() {`
  286. h += `gui()`;
  287. h += `});
  288. </script>`;
  289. h += `</body>
  290. </html>`;
  291. console.log(`/index.js: ` + (Date.now() - start_t)/1000);
  292. return h;
  293. }
  294. // export
  295. module.exports = {generateDevHtml, build};