Skip to content

Commit

Permalink
clients(viewer): convert to ES modules (GoogleChrome#12878)
Browse files Browse the repository at this point in the history
  • Loading branch information
connorjclark authored Aug 10, 2021
1 parent 36454ee commit 52beae3
Show file tree
Hide file tree
Showing 24 changed files with 167 additions and 148 deletions.
15 changes: 0 additions & 15 deletions build/build-report.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,6 @@ async function buildPsiReport() {
});
}

async function buildViewerReport() {
const bundle = await rollup.rollup({
input: 'report/clients/viewer.js',
plugins: [
commonjs(),
],
});

await bundle.write({
file: 'dist/report/viewer.js',
format: 'iife',
});
}

async function buildTreemapReport() {
const bundle = await rollup.rollup({
input: 'report/clients/treemap.js',
Expand Down Expand Up @@ -95,6 +81,5 @@ if (require.main === module) {
module.exports = {
buildStandaloneReport,
buildPsiReport,
buildViewerReport,
buildTreemapReport,
};
4 changes: 1 addition & 3 deletions build/build-treemap.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,8 @@ async function run() {
fs.readFileSync(require.resolve('pako/dist/pako_inflate.js'), 'utf-8'),
/* eslint-enable max-len */
buildStrings(),
{path: '../../lighthouse-viewer/app/src/deps-for-treemap.js', rollup: true},
{path: '../../dist/report/treemap.js'},
{path: '../../lighthouse-viewer/app/src/drag-and-drop.js'},
{path: '../../lighthouse-viewer/app/src/github-api.js'},
{path: '../../lighthouse-viewer/app/src/firebase-auth.js'},
{path: 'src/**/*'},
],
assets: [
Expand Down
7 changes: 1 addition & 6 deletions build/build-viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ const fs = require('fs');
const browserify = require('browserify');
const GhPagesApp = require('./gh-pages-app.js');
const {minifyFileTransform} = require('./build-utils.js');
const {buildViewerReport} = require('./build-report.js');
const htmlReportAssets = require('../report/report-assets.js');
const {LH_ROOT} = require('../root.js');

Expand All @@ -32,8 +31,6 @@ async function run() {
});
});

await buildViewerReport();

const app = new GhPagesApp({
name: 'viewer',
appDir: `${LH_ROOT}/lighthouse-viewer/app`,
Expand All @@ -44,10 +41,8 @@ async function run() {
],
javascripts: [
await generatorJsPromise,
fs.readFileSync(require.resolve('idb-keyval/dist/idb-keyval-min.js'), 'utf8'),
fs.readFileSync(require.resolve('pako/dist/pako_inflate.js'), 'utf-8'),
{path: '../../dist/report/viewer.js'},
{path: 'src/*'},
{path: 'src/main.js', rollup: true},
],
assets: [
{path: 'images/**/*'},
Expand Down
47 changes: 38 additions & 9 deletions build/gh-pages-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@

const fs = require('fs');
const path = require('path');
const rollup = require('rollup');
const commonjs =
// @ts-expect-error types are wrong.
/** @type {import('rollup-plugin-commonjs').default} */ (require('rollup-plugin-commonjs'));
const {terser: rollupTerser} = require('rollup-plugin-terser');
const {nodeResolve} = require('@rollup/plugin-node-resolve');
const cpy = require('cpy');
const ghPages = require('gh-pages');
const glob = require('glob');
Expand Down Expand Up @@ -35,7 +41,7 @@ const license = `/*
/**
* Literal string (representing JS, CSS, etc...), or an object with a path, which would
* be interpreted relative to opts.appDir and be glob-able.
* @typedef {{path: string} | string} Source
* @typedef {{path: string, rollup?: boolean} | string} Source
*/

/**
Expand Down Expand Up @@ -83,10 +89,10 @@ class GhPagesApp {
fs.mkdirSync(this.distDir, {recursive: true}); // Ensure dist is present, else rmdir will throw. COMPAT: when dropping Node 12, replace with fs.rm(p, {force: true})
fs.rmdirSync(this.distDir, {recursive: true});

const html = this._compileHtml();
const html = await this._compileHtml();
safeWriteFile(`${this.distDir}/index.html`, html);

const css = this._compileCss();
const css = await this._compileCss();
safeWriteFile(`${this.distDir}/styles/bundled.css`, css);

const bundledJs = await this._compileJs();
Expand Down Expand Up @@ -116,13 +122,16 @@ class GhPagesApp {

/**
* @param {Source[]} sources
* @return {Promise<string[]>}
*/
_resolveSourcesList(sources) {
async _resolveSourcesList(sources) {
const result = [];

for (const source of sources) {
if (typeof source === 'string') {
result.push(source);
} else if (source.rollup) {
result.push(await this._rollupSource(`${this.opts.appDir}/${source.path}`));
} else {
result.push(...loadFiles(`${this.opts.appDir}/${source.path}`));
}
Expand All @@ -131,8 +140,27 @@ class GhPagesApp {
return result;
}

_compileHtml() {
let htmlSrc = this._resolveSourcesList([this.opts.html])[0];
/**
* @param {string} input
* @return {Promise<string>}
*/
async _rollupSource(input) {
const plugins = [
nodeResolve(),
commonjs(),
];
if (!process.env.DEBUG) plugins.push(rollupTerser());
const bundle = await rollup.rollup({
input,
plugins,
});
const {output} = await bundle.generate({format: 'iife'});
return output[0].code;
}

async _compileHtml() {
const resolvedSources = await this._resolveSourcesList([this.opts.html]);
let htmlSrc = resolvedSources[0];

if (this.opts.htmlReplacements) {
for (const [key, value] of Object.entries(this.opts.htmlReplacements)) {
Expand All @@ -143,8 +171,9 @@ class GhPagesApp {
return htmlSrc;
}

_compileCss() {
return this._resolveSourcesList(this.opts.stylesheets).join('\n');
async _compileCss() {
const resolvedSources = await this._resolveSourcesList(this.opts.stylesheets);
return resolvedSources.join('\n');
}

async _compileJs() {
Expand All @@ -154,7 +183,7 @@ class GhPagesApp {
const contents = [
`"use strict";`,
versionJs,
...this._resolveSourcesList(this.opts.javascripts),
...await this._resolveSourcesList(this.opts.javascripts),
];
if (process.env.DEBUG) return contents.join('\n');

Expand Down
3 changes: 3 additions & 0 deletions lighthouse-treemap/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@
"types",
"../types",
],
"compilerOptions": {
"esModuleInterop": true,
},
}
6 changes: 3 additions & 3 deletions lighthouse-treemap/types/treemap.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import _TreemapUtil = require('../app/src/util.js');
import _DragAndDrop = require('../../lighthouse-viewer/app/src/drag-and-drop.js');
import _FirebaseAuth = require('../../lighthouse-viewer/app/src/firebase-auth.js');
import _GithubApi = require('../../lighthouse-viewer/app/src/github-api.js');
import {DragAndDrop as _DragAndDrop} from '../../lighthouse-viewer/app/src/drag-and-drop.js';
import {FirebaseAuth as _FirebaseAuth} from '../../lighthouse-viewer/app/src/firebase-auth.js';
import {GithubApi as _GithubApi} from '../../lighthouse-viewer/app/src/github-api.js';
import {TextEncoding as _TextEncoding} from '../../report/renderer/text-encoding.js';
import {Logger as _Logger} from '../../report/renderer/logger.js';
import {I18n as _I18n} from '../../report/renderer/i18n.js';
Expand Down
3 changes: 0 additions & 3 deletions lighthouse-viewer/app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ <h1 class="viewer-placeholder__heading">Lighthouse Report Viewer</h1>
<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase-auth.js"></script>
<script src="src/bundled.js"></script>
<script>
window.addEventListener('DOMContentLoaded', main);
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,15 @@
*/
'use strict';

/* global window */
// TODO(esmodules): remove when treemap is esm.

// TODO(esmodules): delete when viewer app is esm.
import {GithubApi} from './github-api.js';
import {FirebaseAuth} from './firebase-auth.js';
import {DragAndDrop} from './drag-and-drop.js';

import {DOM} from '../renderer/dom.js';
import {Logger} from '../renderer/logger.js';
import {ReportRenderer} from '../renderer/report-renderer.js';
import {ReportUIFeatures} from '../renderer/report-ui-features.js';
import {TextEncoding} from '../renderer/text-encoding.js';

// @ts-expect-error
window.DOM = DOM;
// @ts-expect-error
window.Logger = Logger;
// @ts-expect-error
window.ReportRenderer = ReportRenderer;
window.GithubApi = GithubApi;
// @ts-expect-error
window.ReportUIFeatures = ReportUIFeatures;
window.FirebaseAuth = FirebaseAuth;
// @ts-expect-error
window.TextEncoding = TextEncoding;
window.DragAndDrop = DragAndDrop;
6 changes: 1 addition & 5 deletions lighthouse-viewer/app/src/drag-and-drop.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
/**
* Manages drag and drop file input for the page.
*/
class DragAndDrop {
export class DragAndDrop {
/**
* @param {function(string): void} fileHandlerCallback Invoked when the user chooses a new file.
*/
Expand Down Expand Up @@ -91,7 +91,3 @@ class DragAndDrop {
this._dragging = false;
}
}

if (typeof module !== 'undefined' && module.exports) {
module.exports = DragAndDrop;
}
11 changes: 4 additions & 7 deletions lighthouse-viewer/app/src/firebase-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
*/
'use strict';

/* global firebase, idbKeyval */
/* global firebase */

import idbKeyval from 'idb-keyval';

/**
* Wrapper for Firebase authentication.
*/
class FirebaseAuth {
export class FirebaseAuth {
constructor() {
/** @type {?string} */
this._accessToken = null;
Expand Down Expand Up @@ -90,8 +92,3 @@ class FirebaseAuth {
});
}
}

// node export for testing.
if (typeof module !== 'undefined' && module.exports) {
module.exports = FirebaseAuth;
}
13 changes: 6 additions & 7 deletions lighthouse-viewer/app/src/github-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@
*/
'use strict';

/* global logger, FirebaseAuth, idbKeyval, getFilenamePrefix */
/* global logger */

/** @typedef {{etag: ?string, content: LH.Result}} CachableGist */

import idbKeyval from 'idb-keyval';
import {FirebaseAuth} from './firebase-auth.js';
import {getFilenamePrefix} from '../../../report/renderer/file-namer.js';

/**
* Wrapper around the GitHub API for reading/writing gists.
*/
class GithubApi {
export class GithubApi {
constructor() {
this._auth = new FirebaseAuth();
this._saving = false;
Expand Down Expand Up @@ -153,8 +157,3 @@ class GithubApi {
});
}
}

// node export for testing.
if (typeof module !== 'undefined' && module.exports) {
module.exports = GithubApi;
}
18 changes: 11 additions & 7 deletions lighthouse-viewer/app/src/lighthouse-report-viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,16 @@
*/
'use strict';

/* global DOM, ViewerUIFeatures, ReportRenderer, DragAndDrop, GithubApi, PSIApi, logger, idbKeyval, TextEncoding */
import idbKeyval from 'idb-keyval';
import {DragAndDrop} from './drag-and-drop.js';
import {GithubApi} from './github-api.js';
import {PSIApi} from './psi-api';
import {ViewerUIFeatures} from './viewer-ui-features.js';
import {DOM} from '../../../report/renderer/dom.js';
import {ReportRenderer} from '../../../report/renderer/report-renderer.js';
import {TextEncoding} from '../../../report/renderer/text-encoding.js';

/* global logger */

/** @typedef {import('./psi-api').PSIParams} PSIParams */

Expand All @@ -27,7 +36,7 @@ function find(query, context) {
/**
* Class that manages viewing Lighthouse reports.
*/
class LighthouseReportViewer {
export class LighthouseReportViewer {
constructor() {
this._onPaste = this._onPaste.bind(this);
this._onSaveJson = this._onSaveJson.bind(this);
Expand Down Expand Up @@ -445,8 +454,3 @@ class LighthouseReportViewer {
if (placeholder) placeholder.classList.toggle('lh-loading', force);
}
}

// node export for testing.
if (typeof module !== 'undefined' && module.exports) {
module.exports = LighthouseReportViewer;
}
7 changes: 5 additions & 2 deletions lighthouse-viewer/app/src/main.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/**
* Copyright 2016 The Lighthouse Authors. All Rights Reserved.
* @license Copyright 2016 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';

/* global LighthouseReportViewer, Logger */
import {Logger} from '../../../report/renderer/logger.js';
import {LighthouseReportViewer} from './lighthouse-report-viewer.js';

// eslint-disable-next-line no-unused-vars
function main() {
Expand Down Expand Up @@ -48,3 +49,5 @@ function main() {

window.viewer = new LighthouseReportViewer();
}

window.addEventListener('DOMContentLoaded', main);
4 changes: 4 additions & 0 deletions lighthouse-viewer/app/src/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"type": "module",
"//": "Any directory that uses `import ... from` or `export ...` must be type module. Temporary file until root package.json is type: module"
}
10 changes: 2 additions & 8 deletions lighthouse-viewer/app/src/psi-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

const PSI_URL = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed';
const PSI_KEY = 'AIzaSyAjcDRNN9CX9dCazhqI4lGR7yyQbkd_oYE';
const PSI_DEFAULT_CATEGORIES = [
export const PSI_DEFAULT_CATEGORIES = [
'performance',
'accessibility',
'seo',
Expand All @@ -29,7 +29,7 @@ const PSI_DEFAULT_CATEGORIES = [
/**
* Wrapper around the PSI API for fetching LHR.
*/
class PSIApi {
export class PSIApi {
/**
* @param {PSIParams} params
* @return {Promise<PSIResponse>}
Expand All @@ -49,9 +49,3 @@ class PSIApi {
return fetch(apiUrl.href).then(res => res.json());
}
}

// node export for testing.
if (typeof module !== 'undefined' && module.exports) {
module.exports = PSIApi;
module.exports.PSI_DEFAULT_CATEGORIES = PSI_DEFAULT_CATEGORIES;
}
Loading

0 comments on commit 52beae3

Please sign in to comment.