1
0

utils.js 15 KB

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