diff --git a/build/build-viewer.js b/build/build-viewer.js index 841bd78fea24..7693e4e7314b 100644 --- a/build/build-viewer.js +++ b/build/build-viewer.js @@ -6,106 +6,17 @@ 'use strict'; const fs = require('fs'); -const path = require('path'); -const {promisify} = require('util'); -const readFileAsync = promisify(fs.readFile); -const writeFileAsync = promisify(fs.writeFile); -const mkdir = fs.promises.mkdir; - const browserify = require('browserify'); -const cpy = require('cpy'); -const ghPages = require('gh-pages'); -const glob = promisify(require('glob')); -const lighthousePackage = require('../package.json'); -const rimraf = require('rimraf'); -const terser = require('terser'); +const GhPagesApp = require('./gh-pages-app.js'); const {minifyFileTransform} = require('./build-utils.js'); - const htmlReportAssets = require('../lighthouse-core/report/html/html-report-assets.js'); -const sourceDir = `${__dirname}/../lighthouse-viewer`; -const distDir = `${__dirname}/../dist/viewer`; - -const license = `/* -* @license Copyright 2018 The Lighthouse Authors. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express -* or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/`; - -/** - * Evaluates path glob and loads all identified files as an array of strings. - * @param {string} pattern - * @return {Promise>} - */ -async function loadFiles(pattern) { - const filePaths = await glob(pattern); - return Promise.all(filePaths.map(path => readFileAsync(path, {encoding: 'utf8'}))); -} - -/** - * Write a file to filePath, creating parent directories if needed. - * @param {string} filePath - * @param {string} data - * @return {Promise} - */ -async function safeWriteFileAsync(filePath, data) { - const fileDir = path.dirname(filePath); - await mkdir(fileDir, {recursive: true}); - return writeFileAsync(filePath, data); -} - -/** - * Copy static assets. - * @return {Promise} - */ -function copyAssets() { - return cpy([ - 'images/**/*', - 'sw.js', - 'manifest.json', - ], distDir, { - cwd: `${sourceDir}/app/`, - parents: true, - }); -} - -/** - * Concat report and viewer stylesheets into single viewer.css file. - * @return {Promise} - */ -async function css() { - const reportCss = htmlReportAssets.REPORT_CSS; - const viewerCss = await readFileAsync(`${sourceDir}/app/styles/viewer.css`, {encoding: 'utf8'}); - await safeWriteFileAsync(`${distDir}/styles/viewer.css`, [reportCss, viewerCss].join('\n')); -} - -/** - * Insert report templates into html and copy to dist. - * @return {Promise} - */ -async function html() { - let htmlSrc = await readFileAsync(`${sourceDir}/app/index.html`, {encoding: 'utf8'}); - htmlSrc = htmlSrc.replace(/%%LIGHTHOUSE_TEMPLATES%%/, htmlReportAssets.REPORT_TEMPLATES); - - await safeWriteFileAsync(`${distDir}/index.html`, htmlSrc); -} /** - * Combine multiple JS files into single viewer.js file. - * @return {Promise} + * Build viewer, optionally deploying to gh-pages if `--deploy` flag was set. */ -async function compileJs() { +async function run() { // JS bundle from browserified ReportGenerator. - const generatorFilename = `${sourceDir}/../lighthouse-core/report/report-generator.js`; + const generatorFilename = `${__dirname}/../lighthouse-core/report/report-generator.js`; const generatorBrowserify = browserify(generatorFilename, {standalone: 'ReportGenerator'}) .transform('@wardpeet/brfs', { readFileSyncTransform: minifyFileTransform, @@ -118,73 +29,31 @@ async function compileJs() { resolve(src.toString()); }); }); - const generatorJs = await generatorJsPromise; - - // Report renderer scripts. - const rendererJs = htmlReportAssets.REPORT_JAVASCRIPT; - - // idb-keyval dependency. - const idbKeyvalPath = require.resolve('idb-keyval/dist/idb-keyval-min.js'); - const idbKeyvalJs = await readFileAsync(idbKeyvalPath, 'utf8'); - - // Current Lighthouse version as a global variable. - const versionJs = `window.LH_CURRENT_VERSION = '${lighthousePackage.version}';`; - - // Viewer-specific JS files. - const viewJsFiles = await loadFiles(`${sourceDir}/app/src/*.js`); - - const contents = [ - `"use strict";`, - generatorJs, - rendererJs, - idbKeyvalJs, - versionJs, - ...viewJsFiles, - ]; - const options = { - output: {preamble: license}, // Insert license at top. - }; - const uglified = terser.minify(contents, options); - if (uglified.error || !uglified.code) { - throw uglified.error; - } - await safeWriteFileAsync(`${distDir}/src/viewer.js`, uglified.code); -} - -/** - * Publish viewer to gh-pages branch. - * @return {Promise} - */ -async function deploy() { - return new Promise((resolve, reject) => { - ghPages.publish(distDir, { - add: true, // keep existing files - dest: 'viewer', - message: `Update viewer to lighthouse@${lighthousePackage.version}`, - }, err => { - if (err) return reject(err); - resolve(); - }); + const app = new GhPagesApp({ + name: 'viewer', + appDir: `${__dirname}/../lighthouse-viewer/app`, + htmlReplacements: { + '%%LIGHTHOUSE_TEMPLATES%%': htmlReportAssets.REPORT_TEMPLATES, + }, + javascripts: [ + await generatorJsPromise, + htmlReportAssets.REPORT_JAVASCRIPT, + fs.readFileSync(require.resolve('idb-keyval/dist/idb-keyval-min.js'), 'utf8'), + ], + stylesheets: [ + htmlReportAssets.REPORT_CSS, + ], + assetPaths: [ + 'images/**/*', + ], }); -} -/** - * Build viewer, optionally deploying to gh-pages if `--deploy` flag was set. - */ -async function run() { - // Clean and build. - rimraf.sync(distDir); - await Promise.all([ - compileJs(), - html(), - css(), - copyAssets(), - ]); + await app.build(); const argv = process.argv.slice(2); if (argv.includes('--deploy')) { - await deploy(); + await app.deploy(); } } diff --git a/build/gh-pages-app.js b/build/gh-pages-app.js new file mode 100644 index 000000000000..285c1a6b28b9 --- /dev/null +++ b/build/gh-pages-app.js @@ -0,0 +1,163 @@ +/** + * @license Copyright 2020 The Lighthouse Authors. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const cpy = require('cpy'); +const ghPages = require('gh-pages'); +const glob = require('glob'); +const lighthousePackage = require('../package.json'); +const rimraf = require('rimraf'); +const terser = require('terser'); + +const ghPagesDistDir = `${__dirname}/../dist/gh-pages`; + +const license = `/* +* @license Copyright 2020 The Lighthouse Authors. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/`; + +/** + * @typedef BuildOptions + * @property {string} name + * @property {string} appDir + * @property {string[]} javascripts + * @property {string[]} stylesheets + * @property {string[]} assetPaths + * @property {Record=} htmlReplacements + */ + +/** + * Evaluates path glob and loads all identified files as an array of strings. + * @param {string} pattern + * @return {string[]} + */ +function loadFiles(pattern) { + const filePaths = glob.sync(pattern); + return filePaths.map(path => fs.readFileSync(path, {encoding: 'utf8'})); +} + +/** + * Write a file to filePath, creating parent directories if needed. + * @param {string} filePath + * @param {string} data + */ +function safeWriteFile(filePath, data) { + const fileDir = path.dirname(filePath); + fs.mkdirSync(fileDir, {recursive: true}); + fs.writeFileSync(filePath, data); +} + +class GhPagesApp { + /** + * @param {BuildOptions} opts + */ + constructor(opts) { + this.opts = opts; + this.distDir = `${ghPagesDistDir}/${opts.name}`; + } + + async build() { + rimraf.sync(this.distDir); + + const contents = [ + `"use strict";`, + ...this.opts.javascripts, + ]; + const options = { + output: {preamble: license}, // Insert license at top. + }; + const minified = terser.minify(contents, options); + if (minified.error || !minified.code) { + throw minified.error; + } + + const html = this._compileHtml(); + safeWriteFile(`${this.distDir}/index.html`, html); + + const css = this._compileCss(); + safeWriteFile(`${this.distDir}/styles/bundled.css`, css); + + const bundledJs = this._compileJs(); + safeWriteFile(`${this.distDir}/src/bundled.js`, bundledJs); + + await cpy(this.opts.assetPaths, this.distDir, { + cwd: this.opts.appDir, + parents: true, + }); + } + + deploy() { + return new Promise((resolve, reject) => { + ghPages.publish(this.distDir, { + add: true, // keep existing files + dest: this.opts.name, + message: `Update ${this.opts.name} to lighthouse@${lighthousePackage.version}`, + }, err => { + if (err) return reject(err); + resolve(); + }); + }); + } + + _compileHtml() { + let htmlSrc = fs.readFileSync(`${this.opts.appDir}/index.html`, {encoding: 'utf8'}); + + if (this.opts.htmlReplacements) { + for (const [key, value] of Object.entries(this.opts.htmlReplacements)) { + htmlSrc = htmlSrc.replace(key, value); + } + } + + return htmlSrc; + } + + _compileCss() { + return [ + ...this.opts.stylesheets, + ...loadFiles(`${this.opts.appDir}/styles/**/*.css`), + ].join('\n'); + } + + _compileJs() { + // Current Lighthouse version as a global variable. + const versionJs = `window.LH_CURRENT_VERSION = '${lighthousePackage.version}';`; + + // App-specific JS files. + const appJsFiles = loadFiles(`${this.opts.appDir}/src/*.js`); + + const contents = [ + `"use strict";`, + versionJs, + ...this.opts.javascripts, + ...appJsFiles, + ]; + const options = { + output: {preamble: license}, // Insert license at top. + }; + const uglified = terser.minify(contents, options); + if (uglified.error || !uglified.code) { + throw uglified.error; + } + + return uglified.code; + } +} + +module.exports = GhPagesApp; diff --git a/lighthouse-cli/test/fixtures/static-server.js b/lighthouse-cli/test/fixtures/static-server.js index 92c336c075f9..bf2beb6a30fc 100644 --- a/lighthouse-cli/test/fixtures/static-server.js +++ b/lighthouse-cli/test/fixtures/static-server.js @@ -158,7 +158,7 @@ class Server { return; } - if (filePath.startsWith('/dist/viewer')) { + if (filePath.startsWith('/dist/gh-pages/viewer')) { // Rewrite lighthouse-viewer paths to point to that location. absoluteFilePath = path.join(__dirname, '/../../../', filePath); } diff --git a/lighthouse-viewer/app/index.html b/lighthouse-viewer/app/index.html index 7e1025f0a026..00e927c84676 100644 --- a/lighthouse-viewer/app/index.html +++ b/lighthouse-viewer/app/index.html @@ -10,10 +10,9 @@ Lighthouse Report Viewer - - + @@ -45,13 +44,9 @@

Lighthouse Report Viewer

- +