diff --git a/.eslintrc.cjs b/.eslintrc.cjs index c1b27434b08d..6f9fed97b4ab 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -36,7 +36,7 @@ module.exports = { }], 'no-floating-decimal': 2, 'max-len': [2, 100, { - ignorePattern: 'readJson\\(', + ignorePattern: 'readJson\\(|^import ', ignoreComments: true, ignoreUrls: true, tabWidth: 2, diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index 1299e407d86a..7c92a4228b49 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -11,6 +11,7 @@ jobs: strategy: matrix: node: ['14', '16', '17'] + fail-fast: false runs-on: ubuntu-latest name: node ${{ matrix.node }} env: diff --git a/build/build-bundle.js b/build/build-bundle.js index 58f4e1e21edb..e3e6fbe0f298 100644 --- a/build/build-bundle.js +++ b/build/build-bundle.js @@ -16,11 +16,12 @@ import {createRequire} from 'module'; import esMain from 'es-main'; import {rollup} from 'rollup'; -// @ts-expect-error: plugin has no types. -import PubAdsPlugin from 'lighthouse-plugin-publisher-ads/plugin.js'; +// TODO(esmodules): convert pubads to esm +// // @ts-expect-error: plugin has no types. +// import PubAdsPlugin from 'lighthouse-plugin-publisher-ads/plugin.js'; import * as rollupPlugins from './rollup-plugins.js'; -import Runner from '../lighthouse-core/runner.js'; +import {Runner} from '../lighthouse-core/runner.js'; import {LH_ROOT} from '../root.js'; import {readJson} from '../lighthouse-core/test/test-utils.js'; @@ -31,8 +32,8 @@ const COMMIT_HASH = execSync('git rev-parse HEAD').toString().trim(); // HACK: manually include the lighthouse-plugin-publisher-ads audits. /** @type {Array} */ -// @ts-expect-error -const pubAdsAudits = PubAdsPlugin.audits.map(a => a.path); +// // @ts-expect-error +// const pubAdsAudits = PubAdsPlugin.audits.map(a => a.path); /** @param {string} file */ const isDevtools = file => @@ -83,20 +84,24 @@ async function buildBundle(entryPath, distPath, opts = {minify: true}) { ]; // Include lighthouse-plugin-publisher-ads. - if (isDevtools(entryPath) || isLightrider(entryPath)) { - dynamicModulePaths.push('lighthouse-plugin-publisher-ads'); - pubAdsAudits.forEach(pubAdAudit => { - dynamicModulePaths.push(pubAdAudit); - }); - } + // if (isDevtools(entryPath) || isLightrider(entryPath)) { + // dynamicModulePaths.push('lighthouse-plugin-publisher-ads'); + // pubAdsAudits.forEach(pubAdAudit => { + // dynamicModulePaths.push(pubAdAudit); + // }); + // } const bundledMapEntriesCode = dynamicModulePaths.map(modulePath => { const pathNoExt = modulePath.replace('.js', ''); - return `['${pathNoExt}', require('${modulePath}')]`; + return `['${pathNoExt}', import('${modulePath}')]`; }).join(',\n'); /** @type {Record} */ - const shimsObj = {}; + const shimsObj = { + [require.resolve('../lighthouse-core/gather/connections/cri.js')]: + 'export const CriConnection = {}', + [require.resolve('../package.json')]: `export const version = '${pkg.version}';`, + }; const modulesToIgnore = [ 'puppeteer-core', @@ -106,7 +111,6 @@ async function buildBundle(entryPath, distPath, opts = {minify: true}) { '@sentry/node', 'source-map', 'ws', - require.resolve('../lighthouse-core/gather/connections/cri.js'), ]; // Don't include the stringified report in DevTools - see devtools-report-assets.js @@ -124,9 +128,6 @@ async function buildBundle(entryPath, distPath, opts = {minify: true}) { shimsObj[modulePath] = 'export default {}'; } - shimsObj[require.resolve('../package.json')] = - `export const version = '${pkg.version}';`; - const bundle = await rollup({ input: entryPath, context: 'globalThis', @@ -135,8 +136,6 @@ async function buildBundle(entryPath, distPath, opts = {minify: true}) { delimiters: ['', ''], values: { '/* BUILD_REPLACE_BUNDLED_MODULES */': `[\n${bundledMapEntriesCode},\n]`, - '__dirname': (id) => `'${path.relative(LH_ROOT, path.dirname(id))}'`, - '__filename': (id) => `'${path.relative(LH_ROOT, id)}'`, // This package exports to default in a way that causes Rollup to get confused, // resulting in MessageFormat being undefined. 'require(\'intl-messageformat\').default': 'require(\'intl-messageformat\')', @@ -148,6 +147,14 @@ async function buildBundle(entryPath, distPath, opts = {minify: true}) { // TODO: Use globalThis directly. 'global.isLightrider': 'globalThis.isLightrider', 'global.isDevtools': 'globalThis.isDevtools', + // For some reason, `shim` doesn't work to force this module to return false, so instead + // just replace usages of it with false. + 'esMain(import.meta)': 'false', + 'import esMain from \'es-main\'': '', + // By default Rollup converts `import.meta` to a big mess of `document.currentScript && ...`, + // and uses the output name as the url. Instead, do a simpler conversion and use the + // module path. + 'import.meta': (id) => `{url: '${path.relative(LH_ROOT, id)}'}`, }, }), rollupPlugins.alias({ @@ -160,14 +167,23 @@ async function buildBundle(entryPath, distPath, opts = {minify: true}) { ...shimsObj, // Allows for plugins to import lighthouse. 'lighthouse': ` - import Audit from '${require.resolve('../lighthouse-core/audits/audit.js')}'; + import {Audit} from '${require.resolve('../lighthouse-core/audits/audit.js')}'; export {Audit}; `, - // Most node 'url' polyfills don't include the WHATWG `URL` property, but - // that's all that's needed, so make a mini-polyfill. - // @see https://github.com/GoogleChrome/lighthouse/issues/5273 - // TODO: remove when not needed for pubads (https://github.com/googleads/publisher-ads-lighthouse-plugin/pull/325) - 'url': 'export const URL = globalThis.URL;', + 'url': ` + export const URL = globalThis.URL; + export const fileURLToPath = url => url; + export default {URL, fileURLToPath}; + `, + 'module': ` + export const createRequire = () => { + return { + resolve() { + throw new Error('createRequire.resolve is not supported in bundled Lighthouse'); + }, + }; + }; + `, }), rollupPlugins.json(), rollupPlugins.inlineFs({verbose: false}), @@ -211,6 +227,8 @@ async function buildBundle(entryPath, distPath, opts = {minify: true}) { banner, format: 'iife', sourcemap: DEBUG, + // Suppress code splitting. + inlineDynamicImports: true, }); await bundle.close(); } @@ -222,7 +240,7 @@ async function cli(argv) { // Take paths relative to cwd and build. const [entryPath, distPath] = argv.slice(2) .map(filePath => path.resolve(process.cwd(), filePath)); - await buildBundle(entryPath, distPath); + await buildBundle(entryPath, distPath, {minify: !process.env.DEBUG}); } // Test if called from the CLI or as a module. diff --git a/build/build-lightrider-bundles.js b/build/build-lightrider-bundles.js index 09757413b5bc..e4f346db5085 100644 --- a/build/build-lightrider-bundles.js +++ b/build/build-lightrider-bundles.js @@ -52,10 +52,6 @@ async function buildStaticServerBundle() { const bundle = await rollup({ input: 'lighthouse-cli/test/fixtures/static-server.js', plugins: [ - rollupPlugins.shim({ - 'es-main': 'export default function() { return false; }', - }), - rollupPlugins.commonjs(), rollupPlugins.nodeResolve(), ], external: ['mime-types', 'glob'], diff --git a/build/build-smokehouse-bundle.js b/build/build-smokehouse-bundle.js index 28cf6e30bc03..68fa8515a945 100644 --- a/build/build-smokehouse-bundle.js +++ b/build/build-smokehouse-bundle.js @@ -22,6 +22,15 @@ async function main() { rollupPlugins.shim({ [smokehouseCliFilename]: 'export function runLighthouse() { throw new Error("not supported"); }', + 'module': ` + export const createRequire = () => { + return { + resolve() { + throw new Error('createRequire.resolve is not supported in bundled Lighthouse'); + }, + }; + }; + `, }), rollupPlugins.inlineFs({verbose: Boolean(process.env.DEBUG)}), rollupPlugins.commonjs(), diff --git a/build/plugins/inline-fs.js b/build/plugins/inline-fs.js index d84f7f8d8b8c..f25f2c7ec33b 100644 --- a/build/plugins/inline-fs.js +++ b/build/plugins/inline-fs.js @@ -277,7 +277,7 @@ function collapseToStringLiteral(node, filepath) { } case 'Identifier': { - if (node.name === '__dirname') { + if (node.name === '__dirname' || node.name === 'moduleDir') { return path.dirname(filepath); } else if (node.name === '__filename') { return filepath; diff --git a/clients/devtools/devtools-entry.js b/clients/devtools/devtools-entry.js index 1dd9c370dda2..d95ca2b3a087 100644 --- a/clients/devtools/devtools-entry.js +++ b/clients/devtools/devtools-entry.js @@ -9,13 +9,13 @@ import {Buffer} from 'buffer'; -import lighthouse from '../../lighthouse-core/index.js'; +import lighthouse, {legacyNavigation} from '../../lighthouse-core/index.js'; import {navigation, startTimespan, snapshot} from '../../lighthouse-core/fraggle-rock/api.js'; -import RawProtocol from '../../lighthouse-core/gather/connections/raw.js'; +import {RawConnection} from '../../lighthouse-core/gather/connections/raw.js'; import log from 'lighthouse-logger'; import {lookupLocale} from '../../lighthouse-core/lib/i18n/i18n.js'; import {registerLocaleData, getCanonicalLocales} from '../../shared/localization/format.js'; -import constants from '../../lighthouse-core/config/constants.js'; +import * as constants from '../../lighthouse-core/config/constants.js'; /** @typedef {import('../../lighthouse-core/gather/connections/connection.js')} Connection */ @@ -52,17 +52,18 @@ function createConfig(categoryIDs, device) { return { extends: 'lighthouse:default', - plugins: ['lighthouse-plugin-publisher-ads'], + // TODO(esmodules): re-enable when pubads works again + // plugins: ['lighthouse-plugin-publisher-ads'], settings, }; } /** - * @param {RawProtocol.Port} port - * @return {RawProtocol} + * @param {import('../../lighthouse-core/gather/connections/raw.js').Port} port + * @return {RawConnection} */ function setUpWorkerConnection(port) { - return new RawProtocol(port); + return new RawConnection(port); } /** @param {(status: [string, string, string]) => void} listenCallback */ @@ -90,7 +91,7 @@ if (typeof self !== 'undefined') { // @ts-expect-error self.setUpWorkerConnection = setUpWorkerConnection; // @ts-expect-error - self.runLighthouse = lighthouse.legacyNavigation; + self.runLighthouse = legacyNavigation; // @ts-expect-error self.runLighthouseNavigation = navigation; // @ts-expect-error @@ -110,4 +111,6 @@ if (typeof self !== 'undefined') { // For the bundle smoke test. // @ts-expect-error global.runBundledLighthouse = lighthouse; + // @ts-expect-error + global.runBundledLighthouseLegacyNavigation = legacyNavigation; } diff --git a/clients/lightrider/lightrider-entry.js b/clients/lightrider/lightrider-entry.js index 09bd3cc52ccb..4aaf3ae408df 100644 --- a/clients/lightrider/lightrider-entry.js +++ b/clients/lightrider/lightrider-entry.js @@ -8,12 +8,12 @@ /* global globalThis */ import {Buffer} from 'buffer'; - import log from 'lighthouse-logger'; -import lighthouse from '../../lighthouse-core/index.js'; -import LighthouseError from '../../lighthouse-core/lib/lh-error.js'; -import preprocessor from '../../lighthouse-core/lib/proto-preprocessor.js'; -import assetSaver from '../../lighthouse-core/lib/asset-saver.js'; + +import {legacyNavigation} from '../../lighthouse-core/index.js'; +import {LighthouseError} from '../../lighthouse-core/lib/lh-error.js'; +import {processForProto} from '../../lighthouse-core/lib/proto-preprocessor.js'; +import * as assetSaver from '../../lighthouse-core/lib/asset-saver.js'; import mobileConfig from '../../lighthouse-core/config/lr-mobile-config.js'; import desktopConfig from '../../lighthouse-core/config/lr-desktop-config.js'; @@ -24,7 +24,7 @@ const LR_PRESETS = { desktop: desktopConfig, }; -/** @typedef {import('../../lighthouse-core/gather/connections/connection.js')} Connection */ +/** @typedef {import('../../lighthouse-core/gather/connections/connection.js').Connection} Connection */ // Rollup seems to overlook some references to `Buffer`, so it must be made explicit. // (`parseSourceMapFromDataUrl` breaks without this) @@ -64,11 +64,11 @@ export async function runLighthouseInLR(connection, url, flags, lrOpts) { } try { - const runnerResult = await lighthouse.legacyNavigation(url, flags, config, connection); + const runnerResult = await legacyNavigation(url, flags, config, connection); if (!runnerResult) throw new Error('Lighthouse finished without a runnerResult'); // pre process the LHR for proto - const preprocessedLhr = preprocessor.processForProto(runnerResult.lhr); + const preprocessedLhr = processForProto(runnerResult.lhr); // When LR is called with |internal: {keep_raw_response: true, save_lighthouse_assets: true}|, // we log artifacts to raw_response.artifacts. diff --git a/clients/test/lightrider/lightrider-entry-test.js b/clients/test/lightrider/lightrider-entry-test.js index c5c8f54bfd05..e138a678ce31 100644 --- a/clients/test/lightrider/lightrider-entry-test.js +++ b/clients/test/lightrider/lightrider-entry-test.js @@ -8,8 +8,8 @@ import jestMock from 'jest-mock'; import {strict as assert} from 'assert'; import {runLighthouseInLR} from '../../lightrider/lightrider-entry.js'; -import Runner from '../../../lighthouse-core/runner.js'; -import LighthouseError from '../../../lighthouse-core/lib/lh-error.js'; +import {Runner} from '../../../lighthouse-core/runner.js'; +import {LighthouseError} from '../../../lighthouse-core/lib/lh-error.js'; describe('lightrider-entry', () => { describe('#runLighthouseInLR', () => { diff --git a/docs/recipes/auth/example-lh-auth.js b/docs/recipes/auth/example-lh-auth.js index 7f892b70fde6..4b0c66ed69e1 100644 --- a/docs/recipes/auth/example-lh-auth.js +++ b/docs/recipes/auth/example-lh-auth.js @@ -10,8 +10,9 @@ * See docs/recipes/auth/README.md for more. */ -const puppeteer = require('puppeteer'); -const lighthouse = require('lighthouse'); +import puppeteer from 'puppeteer'; +import lighthouse from 'lighthouse'; +import esMain from 'es-main'; // This port will be used by Lighthouse later. The specific port is arbitrary. const PORT = 8041; @@ -71,11 +72,11 @@ async function main() { console.log(JSON.stringify(result.lhr, null, 2)); } -if (require.main === module) { +if (esMain(import.meta)) { main(); -} else { - module.exports = { - login, - logout, - }; } + +export { + login, + logout, +}; diff --git a/docs/recipes/auth/package.json b/docs/recipes/auth/package.json index 74fd7c3cf90e..f06949f688f0 100644 --- a/docs/recipes/auth/package.json +++ b/docs/recipes/auth/package.json @@ -1,9 +1,11 @@ { "private": true, + "type": "module", "scripts": { "start": "node server/server.js" }, "dependencies": { + "es-main": "^1.2.0", "express": "^4.17.1", "express-session": "^1.16.2", "lighthouse": "file:../../../dist/lighthouse.tgz", diff --git a/docs/recipes/auth/server/server.js b/docs/recipes/auth/server/server.js index 77553b47f81c..9d7cd516f3c9 100644 --- a/docs/recipes/auth/server/server.js +++ b/docs/recipes/auth/server/server.js @@ -10,13 +10,18 @@ * page. See docs/recipes/auth/README.md for more. */ -const createError = require('http-errors'); -const express = require('express'); -const morgan = require('morgan'); -const session = require('express-session'); -const http = require('http'); -const path = require('path'); -const PUBLIC_DIR = path.join(__dirname, 'public'); +import createError from 'http-errors'; + +import express from 'express'; +import morgan from 'morgan'; +import session from 'express-session'; +import http from 'http'; +import path from 'path'; +import url from 'url'; +import esMain from 'es-main'; + +const moduleDir = path.dirname(url.fileURLToPath(import.meta.url)); +const PUBLIC_DIR = path.join(moduleDir, 'public'); const app = express(); @@ -78,8 +83,9 @@ app.use(function(err, req, res, next) { }); const server = http.createServer(app); -if (require.main === module) { + +if (esMain(import.meta)) { server.listen(10632); -} else { - module.exports = server; } + +export default server; diff --git a/docs/recipes/custom-audit/custom-config.js b/docs/recipes/custom-audit/custom-config.js index 226ca7184480..f588f6c3085b 100644 --- a/docs/recipes/custom-audit/custom-config.js +++ b/docs/recipes/custom-audit/custom-config.js @@ -5,7 +5,7 @@ */ 'use strict'; -module.exports = { +export default { // 1. Run your custom tests along with all the default Lighthouse tests. extends: 'lighthouse:default', diff --git a/docs/recipes/custom-audit/package.json b/docs/recipes/custom-audit/package.json index 49de8347d904..0e8af2e02951 100644 --- a/docs/recipes/custom-audit/package.json +++ b/docs/recipes/custom-audit/package.json @@ -1,6 +1,7 @@ { "name": "custom-lighthouse-recipe", "private": true, + "type": "module", "scripts": {}, "devDependencies": { "lighthouse": "^9.5.0" diff --git a/docs/recipes/custom-audit/searchable-audit.js b/docs/recipes/custom-audit/searchable-audit.js index 31809b43da51..0636d67a853d 100644 --- a/docs/recipes/custom-audit/searchable-audit.js +++ b/docs/recipes/custom-audit/searchable-audit.js @@ -5,7 +5,7 @@ */ 'use strict'; -const Audit = require('lighthouse').Audit; +import {Audit} from 'lighthouse'; const MAX_SEARCHABLE_TIME = 4000; @@ -43,4 +43,4 @@ class LoadAudit extends Audit { } } -module.exports = LoadAudit; +export default LoadAudit; diff --git a/docs/recipes/custom-audit/searchable-gatherer.js b/docs/recipes/custom-audit/searchable-gatherer.js index ed6470c3f562..e20718d4c73d 100644 --- a/docs/recipes/custom-audit/searchable-gatherer.js +++ b/docs/recipes/custom-audit/searchable-gatherer.js @@ -5,7 +5,7 @@ */ 'use strict'; -const Gatherer = require('lighthouse').Gatherer; +import {Gatherer} from 'lighthouse'; /** * @fileoverview Extracts `window.myLoadMetrics` from the test page. @@ -29,4 +29,4 @@ class TimeToSearchable extends Gatherer { } } -module.exports = TimeToSearchable; +export default TimeToSearchable; diff --git a/docs/recipes/custom-gatherer-puppeteer/custom-audit.js b/docs/recipes/custom-gatherer-puppeteer/custom-audit.js index aacb7ba29eae..bbd3ab18aecc 100644 --- a/docs/recipes/custom-gatherer-puppeteer/custom-audit.js +++ b/docs/recipes/custom-gatherer-puppeteer/custom-audit.js @@ -5,7 +5,7 @@ */ 'use strict'; -const Audit = require('lighthouse').Audit; +import {Audit} from 'lighthouse'; class CustomAudit extends Audit { static get meta() { @@ -31,4 +31,4 @@ class CustomAudit extends Audit { } } -module.exports = CustomAudit; +export default CustomAudit; diff --git a/docs/recipes/custom-gatherer-puppeteer/custom-config.js b/docs/recipes/custom-gatherer-puppeteer/custom-config.js index 87ac5112967d..5258d7684fff 100644 --- a/docs/recipes/custom-gatherer-puppeteer/custom-config.js +++ b/docs/recipes/custom-gatherer-puppeteer/custom-config.js @@ -5,7 +5,7 @@ */ 'use strict'; -module.exports = { +export default { passes: [{ passName: 'defaultPass', gatherers: [ diff --git a/docs/recipes/custom-gatherer-puppeteer/custom-gatherer.js b/docs/recipes/custom-gatherer-puppeteer/custom-gatherer.js index 2d405b2813dc..672fbd7b44b7 100644 --- a/docs/recipes/custom-gatherer-puppeteer/custom-gatherer.js +++ b/docs/recipes/custom-gatherer-puppeteer/custom-gatherer.js @@ -7,11 +7,11 @@ /* global document */ -const Gatherer = require('lighthouse').Gatherer; -const Puppeteer = require('puppeteer'); +import {Gatherer} from 'lighthouse'; +import puppeteer from 'puppeteer'; async function connect(driver) { - const browser = await Puppeteer.connect({ + const browser = await puppeteer.connect({ browserWSEndpoint: await driver.wsEndpoint(), defaultViewport: null, }); @@ -48,4 +48,4 @@ class CustomGatherer extends Gatherer { } } -module.exports = CustomGatherer; +export default CustomGatherer; diff --git a/docs/recipes/custom-gatherer-puppeteer/package.json b/docs/recipes/custom-gatherer-puppeteer/package.json index 3975aaa3ee55..aed8e948a8b9 100644 --- a/docs/recipes/custom-gatherer-puppeteer/package.json +++ b/docs/recipes/custom-gatherer-puppeteer/package.json @@ -1,6 +1,7 @@ { "name": "custom-lighthouse-pptr-recipe", "private": true, + "type": "module", "scripts": { "test": "sh test.sh" }, diff --git a/docs/recipes/integration-test/example-lh-auth.test.js b/docs/recipes/integration-test/example-lh-auth.test.js index 029ba62607cd..44fddf939305 100644 --- a/docs/recipes/integration-test/example-lh-auth.test.js +++ b/docs/recipes/integration-test/example-lh-auth.test.js @@ -4,6 +4,7 @@ * 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'; + /* eslint-disable new-cap */ /** @@ -13,11 +14,12 @@ /** @typedef {import('lighthouse/types/lhr')} LH */ -const puppeteer = require('puppeteer'); -const lighthouse = require('lighthouse'); -const {expect} = require('expect'); -const server = require('../auth/server/server.js'); -const {login, logout} = require('../auth/example-lh-auth.js'); +import puppeteer from 'puppeteer'; + +import lighthouse from 'lighthouse'; +import {expect} from 'expect'; +import server from '../auth/server/server.js'; +import {login, logout} from '../auth/example-lh-auth.js'; const CHROME_DEBUG_PORT = 8042; const SERVER_PORT = 10632; diff --git a/docs/recipes/integration-test/package.json b/docs/recipes/integration-test/package.json index 2fe386a94acf..e91cef0837bc 100644 --- a/docs/recipes/integration-test/package.json +++ b/docs/recipes/integration-test/package.json @@ -1,5 +1,6 @@ { "private": true, + "type": "module", "scripts": { "test": "mocha --timeout 30000 example-lh-auth.test.js" }, diff --git a/docs/recipes/lighthouse-plugin-example/audits/preload-as.js b/docs/recipes/lighthouse-plugin-example/audits/preload-as.js index 83bdf59f88d4..9fad62553921 100644 --- a/docs/recipes/lighthouse-plugin-example/audits/preload-as.js +++ b/docs/recipes/lighthouse-plugin-example/audits/preload-as.js @@ -5,7 +5,7 @@ */ 'use strict'; -const Audit = require('lighthouse').Audit; +import {Audit} from 'lighthouse'; /** * @fileoverview A fake additional check of the robots.txt file. @@ -43,4 +43,4 @@ class PreloadAsAudit extends Audit { } } -module.exports = PreloadAsAudit; +export default PreloadAsAudit; diff --git a/docs/recipes/lighthouse-plugin-example/package.json b/docs/recipes/lighthouse-plugin-example/package.json index 68ee2cf7a274..3bc28f364858 100644 --- a/docs/recipes/lighthouse-plugin-example/package.json +++ b/docs/recipes/lighthouse-plugin-example/package.json @@ -1,6 +1,7 @@ { "name": "lighthouse-plugin-example", "private": true, + "type": "module", "main": "./plugin.js", "peerDependencies": { "lighthouse": "^9.5.0" diff --git a/docs/recipes/lighthouse-plugin-example/plugin.js b/docs/recipes/lighthouse-plugin-example/plugin.js index 8169004b6186..478f39b0d16e 100644 --- a/docs/recipes/lighthouse-plugin-example/plugin.js +++ b/docs/recipes/lighthouse-plugin-example/plugin.js @@ -6,7 +6,7 @@ 'use strict'; /** @type {LH.Config.Plugin} */ -module.exports = { +export default { // Additional audit to run on information Lighthouse gathered. audits: [{ path: 'lighthouse-plugin-example/audits/preload-as.js', diff --git a/esm-utils.mjs b/esm-utils.js similarity index 93% rename from esm-utils.mjs rename to esm-utils.js index 0b8ce070d341..71f7acad5ebb 100644 --- a/esm-utils.mjs +++ b/esm-utils.js @@ -6,7 +6,7 @@ 'use strict'; // TODO(esmodules): rename to .js when root is type: module -import module from 'module'; +import {createRequire} from 'module'; import url from 'url'; import path from 'path'; @@ -15,7 +15,7 @@ import path from 'path'; * @param {string} packageName */ function resolveModulePath(packageName) { - const require = module.createRequire(import.meta.url); + const require = createRequire(import.meta.url); return require.resolve(packageName); } diff --git a/flow-report/tsconfig.json b/flow-report/tsconfig.json index d91ed41a7119..2c313f236ad7 100644 --- a/flow-report/tsconfig.json +++ b/flow-report/tsconfig.json @@ -21,6 +21,7 @@ "./types", "../types/test.d.ts", "../root.js", + "../esm-utils.js", "../lighthouse-core/test/test-env/fake-timers.js", ], } diff --git a/lighthouse-cli/bin.js b/lighthouse-cli/bin.js index 696d5239a1fd..d030d57c10e3 100644 --- a/lighthouse-cli/bin.js +++ b/lighthouse-cli/bin.js @@ -20,7 +20,6 @@ import fs from 'fs'; import path from 'path'; import url from 'url'; -import module from 'module'; import log from 'lighthouse-logger'; @@ -28,17 +27,14 @@ import * as commands from './commands/commands.js'; import * as Printer from './printer.js'; import {getFlags} from './cli-flags.js'; import {runLighthouse} from './run.js'; -import lighthouse from '../lighthouse-core/index.js'; +import {generateConfig, generateLegacyConfig} from '../lighthouse-core/index.js'; import {askPermission} from './sentry-prompt.js'; import {LH_ROOT} from '../root.js'; +import {Sentry} from '../lighthouse-core/lib/sentry.js'; import {getConfigDisplayString} from '../lighthouse-core/fraggle-rock/config/config.js'; const pkg = JSON.parse(fs.readFileSync(LH_ROOT + '/package.json', 'utf-8')); -// TODO(esmodules): use regular import when this file is esm. -const require = module.createRequire(import.meta.url); -const Sentry = require('../lighthouse-core/lib/sentry.js'); - /** * @return {boolean} */ @@ -122,10 +118,10 @@ async function begin() { if (cliFlags.printConfig) { if (cliFlags.legacyNavigation) { - const config = await lighthouse.generateLegacyConfig(configJson, cliFlags); + const config = await generateLegacyConfig(configJson, cliFlags); process.stdout.write(config.getPrintString()); } else { - const config = await lighthouse.generateConfig(configJson, cliFlags); + const config = await generateConfig(configJson, cliFlags); process.stdout.write(getConfigDisplayString(config)); } return; @@ -138,7 +134,7 @@ async function begin() { cliFlags.enableErrorReporting = await askPermission(); } if (cliFlags.enableErrorReporting) { - Sentry.init({ + await Sentry.init({ url: urlUnderTest, flags: cliFlags, environmentData: { diff --git a/lighthouse-cli/commands/list-audits.js b/lighthouse-cli/commands/list-audits.js index a4ffc11fa4ff..0c96d50b2fde 100644 --- a/lighthouse-cli/commands/list-audits.js +++ b/lighthouse-cli/commands/list-audits.js @@ -4,10 +4,10 @@ * 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. */ -import lighthouse from '../../lighthouse-core/index.js'; +import {getAuditList} from '../../lighthouse-core/index.js'; function listAudits() { - const audits = lighthouse.getAuditList().map((i) => i.replace(/\.js$/, '')); + const audits = getAuditList().map((i) => i.replace(/\.js$/, '')); process.stdout.write(JSON.stringify({audits}, null, 2)); process.exit(0); } diff --git a/lighthouse-cli/commands/list-trace-categories.js b/lighthouse-cli/commands/list-trace-categories.js index a9fc969b9dd9..469f47a3abd8 100644 --- a/lighthouse-cli/commands/list-trace-categories.js +++ b/lighthouse-cli/commands/list-trace-categories.js @@ -4,10 +4,9 @@ * 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. */ -import lighthouse from '../../lighthouse-core/index.js'; +import {traceCategories} from '../../lighthouse-core/index.js'; function listTraceCategories() { - const traceCategories = lighthouse.traceCategories; process.stdout.write(JSON.stringify({traceCategories})); process.exit(0); } diff --git a/lighthouse-cli/run.js b/lighthouse-cli/run.js index aeedfab88280..f4b4177df018 100644 --- a/lighthouse-cli/run.js +++ b/lighthouse-cli/run.js @@ -15,7 +15,7 @@ import log from 'lighthouse-logger'; import open from 'open'; import * as Printer from './printer.js'; -import lighthouse from '../lighthouse-core/index.js'; +import lighthouse, {legacyNavigation} from '../lighthouse-core/index.js'; import {getLhrFilenamePrefix} from '../report/generator/file-namer.js'; import * as assetSaver from '../lighthouse-core/lib/asset-saver.js'; import URL from '../lighthouse-core/lib/url-shim.js'; @@ -233,7 +233,7 @@ async function runLighthouse(url, flags, config) { } const runnerResult = flags.legacyNavigation ? - await lighthouse.legacyNavigation(url, flags, config) : + await legacyNavigation(url, flags, config) : await lighthouse(url, flags, config); // If in gatherMode only, there will be no runnerResult. diff --git a/lighthouse-cli/test/cli/bin-test.js b/lighthouse-cli/test/cli/bin-test.js index 9bca2c44f0f9..2a872bac960c 100644 --- a/lighthouse-cli/test/cli/bin-test.js +++ b/lighthouse-cli/test/cli/bin-test.js @@ -21,19 +21,21 @@ const mockLoggerSetLevel = jestMock.fn(); /** @type {import('../../bin.js')} */ let bin; before(async () => { - td.replaceEsm('../../run.js', { + await td.replaceEsm('../../run.js', { runLighthouse: mockRunLighthouse, }); - td.replaceEsm('../../cli-flags.js', { + await td.replaceEsm('../../cli-flags.js', { getFlags: mockGetFlags, }); - td.replaceEsm('../../sentry-prompt.js', { + await td.replaceEsm('../../sentry-prompt.js', { askPermission: mockAskPermission, }); - td.replace('../../../lighthouse-core/lib/sentry.js', { - init: mockSentryInit, + await td.replaceEsm('../../../lighthouse-core/lib/sentry.js', { + Sentry: { + init: mockSentryInit, + }, }); - td.replaceEsm('lighthouse-logger', undefined, {setLevel: mockLoggerSetLevel}); + await td.replaceEsm('lighthouse-logger', undefined, {setLevel: mockLoggerSetLevel}); bin = await import('../../bin.js'); }); diff --git a/lighthouse-cli/test/smokehouse/core-tests.js b/lighthouse-cli/test/smokehouse/core-tests.js index da4efe426450..f8756b5b1d34 100644 --- a/lighthouse-cli/test/smokehouse/core-tests.js +++ b/lighthouse-cli/test/smokehouse/core-tests.js @@ -42,7 +42,7 @@ import perfFonts from './test-definitions/perf-fonts.js'; import perfFrameMetrics from './test-definitions/perf-frame-metrics.js'; import perfPreload from './test-definitions/perf-preload.js'; import perfTraceElements from './test-definitions/perf-trace-elements.js'; -import pubads from './test-definitions/pubads.js'; +// import pubads from './test-definitions/pubads.js'; import pwaAirhorner from './test-definitions/pwa-airhorner.js'; import pwaCaltrain from './test-definitions/pwa-caltrain.js'; import pwaChromestatus from './test-definitions/pwa-chromestatus.js'; @@ -103,7 +103,8 @@ const smokeTests = [ perfFrameMetrics, perfPreload, perfTraceElements, - pubads, + // TODO(esmodules): enable when pubads is bundled again + // pubads, pwaAirhorner, pwaChromestatus, pwaSvgomg, diff --git a/lighthouse-cli/test/smokehouse/lighthouse-runners/bundle.js b/lighthouse-cli/test/smokehouse/lighthouse-runners/bundle.js index 65f80ef022a7..e60bf147ca5f 100644 --- a/lighthouse-cli/test/smokehouse/lighthouse-runners/bundle.js +++ b/lighthouse-cli/test/smokehouse/lighthouse-runners/bundle.js @@ -19,7 +19,7 @@ import {once} from 'events'; import puppeteer from 'puppeteer-core'; import ChromeLauncher from 'chrome-launcher'; -import ChromeProtocol from '../../../../lighthouse-core/gather/connections/cri.js'; +import {CriConnection} from '../../../../lighthouse-core/gather/connections/cri.js'; import {LH_ROOT} from '../../../../root.js'; import {loadArtifacts, saveArtifacts} from '../../../../lighthouse-core/lib/asset-saver.js'; @@ -68,10 +68,14 @@ async function runBundledLighthouse(url, configJson, testRunnerOptions) { global.require = originalRequire; global.Buffer = originalBuffer; - /** @type {import('../../../../lighthouse-core/index.js')} */ + /** @type {import('../../../../lighthouse-core/index.js')['default']} */ // @ts-expect-error - not worth giving test global an actual type. const lighthouse = global.runBundledLighthouse; + /** @type {import('../../../../lighthouse-core/index.js')['legacyNavigation']} */ + // @ts-expect-error - not worth giving test global an actual type. + const legacyNavigation = global.runBundledLighthouseLegacyNavigation; + // Launch and connect to Chrome. const launchedChrome = await ChromeLauncher.launch(); const port = launchedChrome.port; @@ -81,9 +85,9 @@ async function runBundledLighthouse(url, configJson, testRunnerOptions) { const logLevel = testRunnerOptions.isDebug ? 'info' : undefined; let runnerResult; if (testRunnerOptions.useLegacyNavigation) { - const connection = new ChromeProtocol(port); + const connection = new CriConnection(port); runnerResult = - await lighthouse.legacyNavigation(url, {port, logLevel}, configJson, connection); + await legacyNavigation(url, {port, logLevel}, configJson, connection); } else { // Puppeteer is not included in the bundle, we must create the page here. const browser = await puppeteer.connect({browserURL: `http://localhost:${port}`}); diff --git a/lighthouse-cli/test/smokehouse/lighthouse-runners/cli.js b/lighthouse-cli/test/smokehouse/lighthouse-runners/cli.js index 88645d40ce68..eb457649eafb 100644 --- a/lighthouse-cli/test/smokehouse/lighthouse-runners/cli.js +++ b/lighthouse-cli/test/smokehouse/lighthouse-runners/cli.js @@ -17,7 +17,7 @@ import {execFile} from 'child_process'; import log from 'lighthouse-logger'; -import assetSaver from '../../../../lighthouse-core/lib/asset-saver.js'; +import * as assetSaver from '../../../../lighthouse-core/lib/asset-saver.js'; import {LocalConsole} from '../lib/local-console.js'; import {ChildProcessError} from '../lib/child-process-error.js'; import {LH_ROOT} from '../../../../root.js'; diff --git a/lighthouse-core/audits/accessibility/accesskeys.js b/lighthouse-core/audits/accessibility/accesskeys.js index 0d35ab0ff2e2..b919bf948ba6 100644 --- a/lighthouse-core/audits/accessibility/accesskeys.js +++ b/lighthouse-core/audits/accessibility/accesskeys.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the accesskey HTML attribute values are unique across all elements. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/accesskeys).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class Accesskeys extends AxeAudit { /** @@ -41,5 +42,5 @@ class Accesskeys extends AxeAudit { } } -module.exports = Accesskeys; -module.exports.UIStrings = UIStrings; +export default Accesskeys; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-allowed-attr.js b/lighthouse-core/audits/accessibility/aria-allowed-attr.js index 741e4f65df15..fa4f5d93ab49 100644 --- a/lighthouse-core/audits/accessibility/aria-allowed-attr.js +++ b/lighthouse-core/audits/accessibility/aria-allowed-attr.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the ARIA HTML attributes are misaligned with the aria-role HTML attribute specificed on the element, such mismatches are invalid. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { 'more](https://dequeuniversity.com/rules/axe/4.4/aria-allowed-attr).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ARIAAllowedAttr extends AxeAudit { /** @@ -41,5 +42,5 @@ class ARIAAllowedAttr extends AxeAudit { } } -module.exports = ARIAAllowedAttr; -module.exports.UIStrings = UIStrings; +export default ARIAAllowedAttr; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-command-name.js b/lighthouse-core/audits/accessibility/aria-command-name.js index 49ed26963283..7a57a1d9c70a 100644 --- a/lighthouse-core/audits/accessibility/aria-command-name.js +++ b/lighthouse-core/audits/accessibility/aria-command-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accessibility audit that evaluates if important HTML elements have an accessible name. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'When an element doesn\'t have an accessible name, screen readers announce it with a generic name, making it unusable for users who rely on screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-command-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaCommandName extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaCommandName extends AxeAudit { } } -module.exports = AriaCommandName; -module.exports.UIStrings = UIStrings; +export default AriaCommandName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-hidden-body.js b/lighthouse-core/audits/accessibility/aria-hidden-body.js index cc74c7f504f0..c5083d69e876 100644 --- a/lighthouse-core/audits/accessibility/aria-hidden-body.js +++ b/lighthouse-core/audits/accessibility/aria-hidden-body.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that checks if the html element does not have an aria-hidden attribute set on it. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'Assistive technologies, like screen readers, work inconsistently when `aria-hidden="true"` is set on the document ``. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-hidden-body).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaHiddenBody extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaHiddenBody extends AxeAudit { } } -module.exports = AriaHiddenBody; -module.exports.UIStrings = UIStrings; +export default AriaHiddenBody; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-hidden-focus.js b/lighthouse-core/audits/accessibility/aria-hidden-focus.js index 8ec7b7729ca7..2bae32f3475b 100644 --- a/lighthouse-core/audits/accessibility/aria-hidden-focus.js +++ b/lighthouse-core/audits/accessibility/aria-hidden-focus.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that checks if all elements that have an aria-hidden attribute do not contain focusable descendent elements. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'Focusable descendents within an `[aria-hidden="true"]` element prevent those interactive elements from being available to users of assistive technologies like screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-hidden-focus).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaHiddenFocus extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaHiddenFocus extends AxeAudit { } } -module.exports = AriaHiddenFocus; -module.exports.UIStrings = UIStrings; +export default AriaHiddenFocus; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-input-field-name.js b/lighthouse-core/audits/accessibility/aria-input-field-name.js index 98414877dea2..bfe0b153ca60 100644 --- a/lighthouse-core/audits/accessibility/aria-input-field-name.js +++ b/lighthouse-core/audits/accessibility/aria-input-field-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that checks that all ARIA input fields have an accessible name. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'When an input field doesn\'t have an accessible name, screen readers announce it with a generic name, making it unusable for users who rely on screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-input-field-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaInputFieldName extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaInputFieldName extends AxeAudit { } } -module.exports = AriaInputFieldName; -module.exports.UIStrings = UIStrings; +export default AriaInputFieldName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-meter-name.js b/lighthouse-core/audits/accessibility/aria-meter-name.js index 328317056784..4534b4100f0f 100644 --- a/lighthouse-core/audits/accessibility/aria-meter-name.js +++ b/lighthouse-core/audits/accessibility/aria-meter-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accessibility audit that evaluates if meter HTML elements have an accessible name. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'When an element doesn\'t have an accessible name, screen readers announce it with a generic name, making it unusable for users who rely on screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-meter-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaMeterName extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaMeterName extends AxeAudit { } } -module.exports = AriaMeterName; -module.exports.UIStrings = UIStrings; +export default AriaMeterName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-progressbar-name.js b/lighthouse-core/audits/accessibility/aria-progressbar-name.js index 587cceff6dfa..508d1ccea0b9 100644 --- a/lighthouse-core/audits/accessibility/aria-progressbar-name.js +++ b/lighthouse-core/audits/accessibility/aria-progressbar-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accessibility audit that evaluates if progressbar HTML elements have an accessible name. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'When a `progressbar` element doesn\'t have an accessible name, screen readers announce it with a generic name, making it unusable for users who rely on screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-progressbar-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaProgressbarName extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaProgressbarName extends AxeAudit { } } -module.exports = AriaProgressbarName; -module.exports.UIStrings = UIStrings; +export default AriaProgressbarName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-required-attr.js b/lighthouse-core/audits/accessibility/aria-required-attr.js index 1e0d71ec7894..5d949bbe7771 100644 --- a/lighthouse-core/audits/accessibility/aria-required-attr.js +++ b/lighthouse-core/audits/accessibility/aria-required-attr.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all elements with the aria-role attribute have the other corresponding ARIA attributes set as well. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -23,7 +24,7 @@ const UIStrings = { 'of the element to screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-required-attr).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ARIARequiredAttr extends AxeAudit { /** @@ -40,5 +41,5 @@ class ARIARequiredAttr extends AxeAudit { } } -module.exports = ARIARequiredAttr; -module.exports.UIStrings = UIStrings; +export default ARIARequiredAttr; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-required-children.js b/lighthouse-core/audits/accessibility/aria-required-children.js index dfd5a6d77293..1175c33e5d57 100644 --- a/lighthouse-core/audits/accessibility/aria-required-children.js +++ b/lighthouse-core/audits/accessibility/aria-required-children.js @@ -11,8 +11,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the elements with an aria-role that require child elements have the required children. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -27,7 +28,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-required-children).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaRequiredChildren extends AxeAudit { /** @@ -44,5 +45,5 @@ class AriaRequiredChildren extends AxeAudit { } } -module.exports = AriaRequiredChildren; -module.exports.UIStrings = UIStrings; +export default AriaRequiredChildren; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-required-parent.js b/lighthouse-core/audits/accessibility/aria-required-parent.js index 14c0438ebfbb..50584cfe9437 100644 --- a/lighthouse-core/audits/accessibility/aria-required-parent.js +++ b/lighthouse-core/audits/accessibility/aria-required-parent.js @@ -11,8 +11,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates valid aria-role usage. Some ARIA roles require that elements must be a child of specific parent element. This audit checks that when those roles are used, the element with the role is in fact a child of the required parent. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -25,7 +26,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-required-parent).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaRequiredParent extends AxeAudit { /** @@ -42,5 +43,5 @@ class AriaRequiredParent extends AxeAudit { } } -module.exports = AriaRequiredParent; -module.exports.UIStrings = UIStrings; +export default AriaRequiredParent; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-roles.js b/lighthouse-core/audits/accessibility/aria-roles.js index 9d85068032f4..1e69c5e2b053 100644 --- a/lighthouse-core/audits/accessibility/aria-roles.js +++ b/lighthouse-core/audits/accessibility/aria-roles.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all elements have valid aria-role HTML attributes. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-roles).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaRoles extends AxeAudit { /** @@ -41,5 +42,5 @@ class AriaRoles extends AxeAudit { } } -module.exports = AriaRoles; -module.exports.UIStrings = UIStrings; +export default AriaRoles; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-toggle-field-name.js b/lighthouse-core/audits/accessibility/aria-toggle-field-name.js index 0152f07bf92a..e99803284f2a 100644 --- a/lighthouse-core/audits/accessibility/aria-toggle-field-name.js +++ b/lighthouse-core/audits/accessibility/aria-toggle-field-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that checks that all ARIA toggle fields have an accessible name. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'When a toggle field doesn\'t have an accessible name, screen readers announce it with a generic name, making it unusable for users who rely on screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-toggle-field-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaToggleFieldName extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaToggleFieldName extends AxeAudit { } } -module.exports = AriaToggleFieldName; -module.exports.UIStrings = UIStrings; +export default AriaToggleFieldName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-tooltip-name.js b/lighthouse-core/audits/accessibility/aria-tooltip-name.js index 5ba24c7b48ea..8851ebf6edb7 100644 --- a/lighthouse-core/audits/accessibility/aria-tooltip-name.js +++ b/lighthouse-core/audits/accessibility/aria-tooltip-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accessibility audit that evaluates if tooltip HTML elements have an accessible name. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'When an element doesn\'t have an accessible name, screen readers announce it with a generic name, making it unusable for users who rely on screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-tooltip-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaTooltipName extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaTooltipName extends AxeAudit { } } -module.exports = AriaTooltipName; -module.exports.UIStrings = UIStrings; +export default AriaTooltipName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-treeitem-name.js b/lighthouse-core/audits/accessibility/aria-treeitem-name.js index 9b4863c1ac70..515876681283 100644 --- a/lighthouse-core/audits/accessibility/aria-treeitem-name.js +++ b/lighthouse-core/audits/accessibility/aria-treeitem-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accessibility audit that evaluates if treeitem HTML elements have an accessible name. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'When an element doesn\'t have an accessible name, screen readers announce it with a generic name, making it unusable for users who rely on screen readers. [Learn more](https://dequeuniversity.com/rules/axe/4.4/aria-treeitem-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AriaTreeitemName extends AxeAudit { /** @@ -39,5 +40,5 @@ class AriaTreeitemName extends AxeAudit { } } -module.exports = AriaTreeitemName; -module.exports.UIStrings = UIStrings; +export default AriaTreeitemName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-valid-attr-value.js b/lighthouse-core/audits/accessibility/aria-valid-attr-value.js index 2d8f2bf76a03..70a8454d1c11 100644 --- a/lighthouse-core/audits/accessibility/aria-valid-attr-value.js +++ b/lighthouse-core/audits/accessibility/aria-valid-attr-value.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all elements that have an ARIA HTML attribute have a valid value for that attribute. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { 'more](https://dequeuniversity.com/rules/axe/4.4/aria-valid-attr-value).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ARIAValidAttr extends AxeAudit { /** @@ -41,5 +42,5 @@ class ARIAValidAttr extends AxeAudit { } } -module.exports = ARIAValidAttr; -module.exports.UIStrings = UIStrings; +export default ARIAValidAttr; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/aria-valid-attr.js b/lighthouse-core/audits/accessibility/aria-valid-attr.js index f0ef26b0c00c..67098b7aed6e 100644 --- a/lighthouse-core/audits/accessibility/aria-valid-attr.js +++ b/lighthouse-core/audits/accessibility/aria-valid-attr.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all elements with ARIA HTML attributes have spelled the name of attribute correctly. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { 'more](https://dequeuniversity.com/rules/axe/4.4/aria-valid-attr).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ARIAValidAttr extends AxeAudit { /** @@ -41,5 +42,5 @@ class ARIAValidAttr extends AxeAudit { } } -module.exports = ARIAValidAttr; -module.exports.UIStrings = UIStrings; +export default ARIAValidAttr; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/axe-audit.js b/lighthouse-core/audits/accessibility/axe-audit.js index 0c701e16afee..aee620ed35c7 100644 --- a/lighthouse-core/audits/accessibility/axe-audit.js +++ b/lighthouse-core/audits/accessibility/axe-audit.js @@ -10,15 +10,16 @@ * generate audit results using aXe rule names. */ -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Label of a table column that identifies HTML elements that have failed an audit. */ failingElementsHeader: 'Failing Elements', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AxeAudit extends Audit { /** @@ -110,5 +111,5 @@ class AxeAudit extends Audit { } } -module.exports = AxeAudit; -module.exports.UIStrings = UIStrings; +export default AxeAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/button-name.js b/lighthouse-core/audits/accessibility/button-name.js index ad325476ac55..fe7a6ef5bec2 100644 --- a/lighthouse-core/audits/accessibility/button-name.js +++ b/lighthouse-core/audits/accessibility/button-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all button elements have names accessible to screen readers. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/button-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ButtonName extends AxeAudit { /** @@ -41,5 +42,5 @@ class ButtonName extends AxeAudit { } } -module.exports = ButtonName; -module.exports.UIStrings = UIStrings; +export default ButtonName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/bypass.js b/lighthouse-core/audits/accessibility/bypass.js index 98f7bb3afab8..3c7be66521ef 100644 --- a/lighthouse-core/audits/accessibility/bypass.js +++ b/lighthouse-core/audits/accessibility/bypass.js @@ -11,8 +11,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the page has elements that let screen reader users skip over repetitive content. `heading`, `skip link`, and `landmark region` are technical terms for the elements that enable quick page navigation. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -25,7 +26,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/bypass).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class Bypass extends AxeAudit { /** @@ -42,5 +43,5 @@ class Bypass extends AxeAudit { } } -module.exports = Bypass; -module.exports.UIStrings = UIStrings; +export default Bypass; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/color-contrast.js b/lighthouse-core/audits/accessibility/color-contrast.js index 10688a45176a..29cb07c8f9c5 100644 --- a/lighthouse-core/audits/accessibility/color-contrast.js +++ b/lighthouse-core/audits/accessibility/color-contrast.js @@ -11,8 +11,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all foreground colors are distinct enough from their background colors to be legible for users. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -25,7 +26,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/color-contrast).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ColorContrast extends AxeAudit { /** @@ -42,5 +43,5 @@ class ColorContrast extends AxeAudit { } } -module.exports = ColorContrast; -module.exports.UIStrings = UIStrings; +export default ColorContrast; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/definition-list.js b/lighthouse-core/audits/accessibility/definition-list.js index dfbe0546bc95..c3397ac77b05 100644 --- a/lighthouse-core/audits/accessibility/definition-list.js +++ b/lighthouse-core/audits/accessibility/definition-list.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all the definition list elements have valid markup for screen readers. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -26,7 +27,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/definition-list).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class DefinitionList extends AxeAudit { /** @@ -43,5 +44,5 @@ class DefinitionList extends AxeAudit { } } -module.exports = DefinitionList; -module.exports.UIStrings = UIStrings; +export default DefinitionList; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/dlitem.js b/lighthouse-core/audits/accessibility/dlitem.js index 212af86fd2d8..abb1306a553e 100644 --- a/lighthouse-core/audits/accessibility/dlitem.js +++ b/lighthouse-core/audits/accessibility/dlitem.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all definition list item elements (`
`/`
`) have a definition list parent element (`
`). This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/dlitem).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class DLItem extends AxeAudit { /** @@ -41,5 +42,5 @@ class DLItem extends AxeAudit { } } -module.exports = DLItem; -module.exports.UIStrings = UIStrings; +export default DLItem; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/document-title.js b/lighthouse-core/audits/accessibility/document-title.js index 5e9378109027..66b85e8a0b56 100644 --- a/lighthouse-core/audits/accessibility/document-title.js +++ b/lighthouse-core/audits/accessibility/document-title.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the page has a element that describes the page. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/document-title).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class DocumentTitle extends AxeAudit { /** @@ -41,5 +42,5 @@ class DocumentTitle extends AxeAudit { } } -module.exports = DocumentTitle; -module.exports.UIStrings = UIStrings; +export default DocumentTitle; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/duplicate-id-active.js b/lighthouse-core/audits/accessibility/duplicate-id-active.js index c1b7acca77d3..e4fee63abf62 100644 --- a/lighthouse-core/audits/accessibility/duplicate-id-active.js +++ b/lighthouse-core/audits/accessibility/duplicate-id-active.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that checks if there are any duplicate id HTML attributes on active, focusable elements. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'All focusable elements must have a unique `id` to ensure that they\'re visible to assistive technologies. [Learn more](https://dequeuniversity.com/rules/axe/4.4/duplicate-id-active).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class DuplicateIdActive extends AxeAudit { /** @@ -39,5 +40,5 @@ class DuplicateIdActive extends AxeAudit { } } -module.exports = DuplicateIdActive; -module.exports.UIStrings = UIStrings; +export default DuplicateIdActive; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/duplicate-id-aria.js b/lighthouse-core/audits/accessibility/duplicate-id-aria.js index c7e266517a42..dd85e3a91cc9 100644 --- a/lighthouse-core/audits/accessibility/duplicate-id-aria.js +++ b/lighthouse-core/audits/accessibility/duplicate-id-aria.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that checks if there are any duplicate ARIA IDs on the page. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'The value of an ARIA ID must be unique to prevent other instances from being overlooked by assistive technologies. [Learn more](https://dequeuniversity.com/rules/axe/4.4/duplicate-id-aria).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class DuplicateIdAria extends AxeAudit { /** @@ -39,5 +40,5 @@ class DuplicateIdAria extends AxeAudit { } } -module.exports = DuplicateIdAria; -module.exports.UIStrings = UIStrings; +export default DuplicateIdAria; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/form-field-multiple-labels.js b/lighthouse-core/audits/accessibility/form-field-multiple-labels.js index bec83b6a2b67..729a5af221dd 100644 --- a/lighthouse-core/audits/accessibility/form-field-multiple-labels.js +++ b/lighthouse-core/audits/accessibility/form-field-multiple-labels.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that checks if any form fields have multiple label elements. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'Form fields with multiple labels can be confusingly announced by assistive technologies like screen readers which use either the first, the last, or all of the labels. [Learn more](https://dequeuniversity.com/rules/axe/4.4/form-field-multiple-labels).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class FormFieldMultipleLabels extends AxeAudit { /** @@ -40,5 +41,5 @@ class FormFieldMultipleLabels extends AxeAudit { } } -module.exports = FormFieldMultipleLabels; -module.exports.UIStrings = UIStrings; +export default FormFieldMultipleLabels; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/frame-title.js b/lighthouse-core/audits/accessibility/frame-title.js index c09fd851a6db..5cfa90544049 100644 --- a/lighthouse-core/audits/accessibility/frame-title.js +++ b/lighthouse-core/audits/accessibility/frame-title.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all `<frame>` and `<iframe>` elements on the page have a title HTML attribute to describe their contents. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -23,7 +24,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/frame-title).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class FrameTitle extends AxeAudit { /** @@ -40,5 +41,5 @@ class FrameTitle extends AxeAudit { } } -module.exports = FrameTitle; -module.exports.UIStrings = UIStrings; +export default FrameTitle; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/heading-order.js b/lighthouse-core/audits/accessibility/heading-order.js index 89a44ca6c5e9..c83e1ef50d13 100644 --- a/lighthouse-core/audits/accessibility/heading-order.js +++ b/lighthouse-core/audits/accessibility/heading-order.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that checks if heading elements (<h1>, <h2>, etc) appear in numeric order and only ever increase in steps of 1. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -22,7 +23,7 @@ const UIStrings = { description: 'Properly ordered headings that do not skip levels convey the semantic structure of the page, making it easier to navigate and understand when using assistive technologies. [Learn more](https://dequeuniversity.com/rules/axe/4.4/heading-order).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class HeadingOrder extends AxeAudit { /** @@ -39,5 +40,5 @@ class HeadingOrder extends AxeAudit { } } -module.exports = HeadingOrder; -module.exports.UIStrings = UIStrings; +export default HeadingOrder; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/html-has-lang.js b/lighthouse-core/audits/accessibility/html-has-lang.js index 0a7db03b4aa2..a93d3c3dd6a2 100644 --- a/lighthouse-core/audits/accessibility/html-has-lang.js +++ b/lighthouse-core/audits/accessibility/html-has-lang.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the root HTML tag has a lang attribute identifying the page's language. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -26,7 +27,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/html-has-lang).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class HTMLHasLang extends AxeAudit { /** @@ -43,5 +44,5 @@ class HTMLHasLang extends AxeAudit { } } -module.exports = HTMLHasLang; -module.exports.UIStrings = UIStrings; +export default HTMLHasLang; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/html-lang-valid.js b/lighthouse-core/audits/accessibility/html-lang-valid.js index 664dd9a8ee98..9de516f3eba6 100644 --- a/lighthouse-core/audits/accessibility/html-lang-valid.js +++ b/lighthouse-core/audits/accessibility/html-lang-valid.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the value for root HTML tag's lang attribute is a valid BCP 47 language. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -25,7 +26,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/html-lang-valid).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class HTMLLangValid extends AxeAudit { /** @@ -42,5 +43,5 @@ class HTMLLangValid extends AxeAudit { } } -module.exports = HTMLLangValid; -module.exports.UIStrings = UIStrings; +export default HTMLLangValid; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/image-alt.js b/lighthouse-core/audits/accessibility/image-alt.js index 40d8968d2431..ea595602a270 100644 --- a/lighthouse-core/audits/accessibility/image-alt.js +++ b/lighthouse-core/audits/accessibility/image-alt.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all image elements have the alt HTML attribute to describe their contents. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/image-alt).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ImageAlt extends AxeAudit { /** @@ -41,5 +42,5 @@ class ImageAlt extends AxeAudit { } } -module.exports = ImageAlt; -module.exports.UIStrings = UIStrings; +export default ImageAlt; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/input-image-alt.js b/lighthouse-core/audits/accessibility/input-image-alt.js index e08a67a3f336..5fdd819d12e6 100644 --- a/lighthouse-core/audits/accessibility/input-image-alt.js +++ b/lighthouse-core/audits/accessibility/input-image-alt.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all input elements of type image have an alt HTML attribute to describe their contents. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/input-image-alt).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class InputImageAlt extends AxeAudit { /** @@ -41,5 +42,5 @@ class InputImageAlt extends AxeAudit { } } -module.exports = InputImageAlt; -module.exports.UIStrings = UIStrings; +export default InputImageAlt; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/label.js b/lighthouse-core/audits/accessibility/label.js index d5df13e36dba..50cccd4793b9 100644 --- a/lighthouse-core/audits/accessibility/label.js +++ b/lighthouse-core/audits/accessibility/label.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all form elements have corresponding label elements. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { 'more](https://dequeuniversity.com/rules/axe/4.4/label).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class Label extends AxeAudit { /** @@ -41,5 +42,5 @@ class Label extends AxeAudit { } } -module.exports = Label; -module.exports.UIStrings = UIStrings; +export default Label; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/link-name.js b/lighthouse-core/audits/accessibility/link-name.js index 3ec77a66a8c9..f91320ccd7e9 100644 --- a/lighthouse-core/audits/accessibility/link-name.js +++ b/lighthouse-core/audits/accessibility/link-name.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all link elements have a non-generic name to screen readers. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -25,7 +26,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/link-name).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class LinkName extends AxeAudit { /** @@ -42,5 +43,5 @@ class LinkName extends AxeAudit { } } -module.exports = LinkName; -module.exports.UIStrings = UIStrings; +export default LinkName; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/list.js b/lighthouse-core/audits/accessibility/list.js index ae3d7f702f08..b0d2612a3da1 100644 --- a/lighthouse-core/audits/accessibility/list.js +++ b/lighthouse-core/audits/accessibility/list.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all list elements have a valid structure containing only list items. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -26,7 +27,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/list).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class List extends AxeAudit { /** @@ -43,5 +44,5 @@ class List extends AxeAudit { } } -module.exports = List; -module.exports.UIStrings = UIStrings; +export default List; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/listitem.js b/lighthouse-core/audits/accessibility/listitem.js index 5c5f3687db33..df26e5bc8f96 100644 --- a/lighthouse-core/audits/accessibility/listitem.js +++ b/lighthouse-core/audits/accessibility/listitem.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if any list item elements do not have list parent elements. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -25,7 +26,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/listitem).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ListItem extends AxeAudit { /** @@ -42,5 +43,5 @@ class ListItem extends AxeAudit { } } -module.exports = ListItem; -module.exports.UIStrings = UIStrings; +export default ListItem; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/manual/custom-controls-labels.js b/lighthouse-core/audits/accessibility/manual/custom-controls-labels.js index a6119ed95e60..ccf350181e1c 100644 --- a/lighthouse-core/audits/accessibility/manual/custom-controls-labels.js +++ b/lighthouse-core/audits/accessibility/manual/custom-controls-labels.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit to assert custom controls have associated labels. @@ -25,4 +25,4 @@ class CustomControlsLabels extends ManualAudit { } } -module.exports = CustomControlsLabels; +export default CustomControlsLabels; diff --git a/lighthouse-core/audits/accessibility/manual/custom-controls-roles.js b/lighthouse-core/audits/accessibility/manual/custom-controls-roles.js index d3b239c55004..b3196c6e2d9b 100644 --- a/lighthouse-core/audits/accessibility/manual/custom-controls-roles.js +++ b/lighthouse-core/audits/accessibility/manual/custom-controls-roles.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit to assert custom controls have associated roles. @@ -25,4 +25,4 @@ class CustomControlsRoles extends ManualAudit { } } -module.exports = CustomControlsRoles; +export default CustomControlsRoles; diff --git a/lighthouse-core/audits/accessibility/manual/focus-traps.js b/lighthouse-core/audits/accessibility/manual/focus-traps.js index da68ffc77df2..78a4f2319542 100644 --- a/lighthouse-core/audits/accessibility/manual/focus-traps.js +++ b/lighthouse-core/audits/accessibility/manual/focus-traps.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit to avoid trapping keyboard focus in a region. @@ -25,4 +25,4 @@ class FocusTraps extends ManualAudit { } } -module.exports = FocusTraps; +export default FocusTraps; diff --git a/lighthouse-core/audits/accessibility/manual/focusable-controls.js b/lighthouse-core/audits/accessibility/manual/focusable-controls.js index bf8a57364e5f..5dd73829b2b4 100644 --- a/lighthouse-core/audits/accessibility/manual/focusable-controls.js +++ b/lighthouse-core/audits/accessibility/manual/focusable-controls.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit for focusable controls. @@ -25,4 +25,4 @@ class FocusableControls extends ManualAudit { } } -module.exports = FocusableControls; +export default FocusableControls; diff --git a/lighthouse-core/audits/accessibility/manual/interactive-element-affordance.js b/lighthouse-core/audits/accessibility/manual/interactive-element-affordance.js index 83b519472671..9cabd5b60456 100644 --- a/lighthouse-core/audits/accessibility/manual/interactive-element-affordance.js +++ b/lighthouse-core/audits/accessibility/manual/interactive-element-affordance.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit for interactive element affordance. @@ -25,4 +25,4 @@ class InteractiveElementAffordance extends ManualAudit { } } -module.exports = InteractiveElementAffordance; +export default InteractiveElementAffordance; diff --git a/lighthouse-core/audits/accessibility/manual/logical-tab-order.js b/lighthouse-core/audits/accessibility/manual/logical-tab-order.js index e02894b5d15c..1eee117341fd 100644 --- a/lighthouse-core/audits/accessibility/manual/logical-tab-order.js +++ b/lighthouse-core/audits/accessibility/manual/logical-tab-order.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit for tab order that follows DOM order. @@ -25,4 +25,4 @@ class LogicalTabOrder extends ManualAudit { } } -module.exports = LogicalTabOrder; +export default LogicalTabOrder; diff --git a/lighthouse-core/audits/accessibility/manual/managed-focus.js b/lighthouse-core/audits/accessibility/manual/managed-focus.js index 23717d767bbb..9c762ad71a8c 100644 --- a/lighthouse-core/audits/accessibility/manual/managed-focus.js +++ b/lighthouse-core/audits/accessibility/manual/managed-focus.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit for focusing new content that's added to the page. @@ -25,4 +25,4 @@ class ManagedFocus extends ManualAudit { } } -module.exports = ManagedFocus; +export default ManagedFocus; diff --git a/lighthouse-core/audits/accessibility/manual/offscreen-content-hidden.js b/lighthouse-core/audits/accessibility/manual/offscreen-content-hidden.js index ff3b10defbcc..4c58c65dbef5 100644 --- a/lighthouse-core/audits/accessibility/manual/offscreen-content-hidden.js +++ b/lighthouse-core/audits/accessibility/manual/offscreen-content-hidden.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit to check that offscreen content is hidden from @@ -26,4 +26,4 @@ class OffscreenContentHidden extends ManualAudit { } } -module.exports = OffscreenContentHidden; +export default OffscreenContentHidden; diff --git a/lighthouse-core/audits/accessibility/manual/use-landmarks.js b/lighthouse-core/audits/accessibility/manual/use-landmarks.js index 8355d2cf2d57..603a28a8d18f 100644 --- a/lighthouse-core/audits/accessibility/manual/use-landmarks.js +++ b/lighthouse-core/audits/accessibility/manual/use-landmarks.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit to check that landmark elements are used whenever possible. @@ -25,4 +25,4 @@ class UseLandmarks extends ManualAudit { } } -module.exports = UseLandmarks; +export default UseLandmarks; diff --git a/lighthouse-core/audits/accessibility/manual/visual-order-follows-dom.js b/lighthouse-core/audits/accessibility/manual/visual-order-follows-dom.js index 342a92660dc7..c40009d2c599 100644 --- a/lighthouse-core/audits/accessibility/manual/visual-order-follows-dom.js +++ b/lighthouse-core/audits/accessibility/manual/visual-order-follows-dom.js @@ -6,7 +6,7 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); +import ManualAudit from '../../manual/manual-audit.js'; /** * @fileoverview Manual A11y audit to check that the visual layout of the page matches the DOM. @@ -25,4 +25,4 @@ class VisualOrderFollowsDOM extends ManualAudit { } } -module.exports = VisualOrderFollowsDOM; +export default VisualOrderFollowsDOM; diff --git a/lighthouse-core/audits/accessibility/meta-refresh.js b/lighthouse-core/audits/accessibility/meta-refresh.js index fc51553225aa..7c10e1ea5535 100644 --- a/lighthouse-core/audits/accessibility/meta-refresh.js +++ b/lighthouse-core/audits/accessibility/meta-refresh.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the page uses a meta tag that refreshes the page automatically. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -25,7 +26,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/meta-refresh).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class MetaRefresh extends AxeAudit { /** @@ -42,5 +43,5 @@ class MetaRefresh extends AxeAudit { } } -module.exports = MetaRefresh; -module.exports.UIStrings = UIStrings; +export default MetaRefresh; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/meta-viewport.js b/lighthouse-core/audits/accessibility/meta-viewport.js index 060a77c869e8..045a9c4b5e1d 100644 --- a/lighthouse-core/audits/accessibility/meta-viewport.js +++ b/lighthouse-core/audits/accessibility/meta-viewport.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if the page has limited the scaling properties of the page in a way that harms users with low vision. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -26,7 +27,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/meta-viewport).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class MetaViewport extends AxeAudit { /** @@ -43,5 +44,5 @@ class MetaViewport extends AxeAudit { } } -module.exports = MetaViewport; -module.exports.UIStrings = UIStrings; +export default MetaViewport; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/object-alt.js b/lighthouse-core/audits/accessibility/object-alt.js index 5d7a257ae9ee..f12f10d28a38 100644 --- a/lighthouse-core/audits/accessibility/object-alt.js +++ b/lighthouse-core/audits/accessibility/object-alt.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all object elements have an alt HTML attribute that describes their contents. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/object-alt).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ObjectAlt extends AxeAudit { /** @@ -41,5 +42,5 @@ class ObjectAlt extends AxeAudit { } } -module.exports = ObjectAlt; -module.exports.UIStrings = UIStrings; +export default ObjectAlt; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/tabindex.js b/lighthouse-core/audits/accessibility/tabindex.js index ed07004afab7..3d9f71a032de 100644 --- a/lighthouse-core/audits/accessibility/tabindex.js +++ b/lighthouse-core/audits/accessibility/tabindex.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if any elements have custom tabindex HTML attributes that might frustrate users of assitive technology. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { 'for users who rely on assistive technologies. [Learn more](https://dequeuniversity.com/rules/axe/4.4/tabindex).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class TabIndex extends AxeAudit { /** @@ -41,5 +42,5 @@ class TabIndex extends AxeAudit { } } -module.exports = TabIndex; -module.exports.UIStrings = UIStrings; +export default TabIndex; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/td-headers-attr.js b/lighthouse-core/audits/accessibility/td-headers-attr.js index 3969285ecb0b..503b40d31f0e 100644 --- a/lighthouse-core/audits/accessibility/td-headers-attr.js +++ b/lighthouse-core/audits/accessibility/td-headers-attr.js @@ -11,8 +11,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all table cell elements in a table that use the headers HTML attribute use it correctly to refer to header cells within the same table. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -28,7 +29,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/td-headers-attr).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class TDHeadersAttr extends AxeAudit { /** @@ -45,5 +46,5 @@ class TDHeadersAttr extends AxeAudit { } } -module.exports = TDHeadersAttr; -module.exports.UIStrings = UIStrings; +export default TDHeadersAttr; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/th-has-data-cells.js b/lighthouse-core/audits/accessibility/th-has-data-cells.js index 15331ee04fec..6f75b5d52932 100644 --- a/lighthouse-core/audits/accessibility/th-has-data-cells.js +++ b/lighthouse-core/audits/accessibility/th-has-data-cells.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all table header elements have children. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -27,7 +28,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/th-has-data-cells).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class THHasDataCells extends AxeAudit { /** @@ -44,5 +45,5 @@ class THHasDataCells extends AxeAudit { } } -module.exports = THHasDataCells; -module.exports.UIStrings = UIStrings; +export default THHasDataCells; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/valid-lang.js b/lighthouse-core/audits/accessibility/valid-lang.js index f968d5a4efee..138863393d44 100644 --- a/lighthouse-core/audits/accessibility/valid-lang.js +++ b/lighthouse-core/audits/accessibility/valid-lang.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all lang HTML attributes are valid BCP 47 languages. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -24,7 +25,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/valid-lang).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ValidLang extends AxeAudit { /** @@ -41,5 +42,5 @@ class ValidLang extends AxeAudit { } } -module.exports = ValidLang; -module.exports.UIStrings = UIStrings; +export default ValidLang; +export {UIStrings}; diff --git a/lighthouse-core/audits/accessibility/video-caption.js b/lighthouse-core/audits/accessibility/video-caption.js index 3be2b8563727..b3474f334437 100644 --- a/lighthouse-core/audits/accessibility/video-caption.js +++ b/lighthouse-core/audits/accessibility/video-caption.js @@ -10,8 +10,9 @@ * See base class in axe-audit.js for audit() implementation. */ -const AxeAudit = require('./axe-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import AxeAudit from './axe-audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of an accesibility audit that evaluates if all video elements contain a child track element that has captions describing their audio. This title is descriptive of the successful state and is shown to users when no user action is required. */ @@ -25,7 +26,7 @@ const UIStrings = { '[Learn more](https://dequeuniversity.com/rules/axe/4.4/video-caption).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class VideoCaption extends AxeAudit { /** @@ -42,5 +43,5 @@ class VideoCaption extends AxeAudit { } } -module.exports = VideoCaption; -module.exports.UIStrings = UIStrings; +export default VideoCaption; +export {UIStrings}; diff --git a/lighthouse-core/audits/apple-touch-icon.js b/lighthouse-core/audits/apple-touch-icon.js index 06ac21ff047d..63bd75f1f1d8 100644 --- a/lighthouse-core/audits/apple-touch-icon.js +++ b/lighthouse-core/audits/apple-touch-icon.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; /** * @fileoverview Audits if a page has an `apple-touch-icon` link element with a valid href. @@ -26,7 +26,7 @@ const UIStrings = { '`apple-touch-icon` is preferred.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class AppleTouchIcon extends Audit { /** @@ -68,5 +68,5 @@ class AppleTouchIcon extends Audit { } } -module.exports = AppleTouchIcon; -module.exports.UIStrings = UIStrings; +export default AppleTouchIcon; +export {UIStrings}; diff --git a/lighthouse-core/audits/audit.js b/lighthouse-core/audits/audit.js index 8dbb57aa64c7..9fe32cf46230 100644 --- a/lighthouse-core/audits/audit.js +++ b/lighthouse-core/audits/audit.js @@ -5,9 +5,9 @@ */ 'use strict'; -const {isUnderTest} = require('../lib/lh-env.js'); -const statistics = require('../lib/statistics.js'); -const {Util} = require('../util-commonjs.js'); +import {isUnderTest} from '../lib/lh-env.js'; +import * as statistics from '../lib/statistics.js'; +import {Util} from '../util.cjs'; const DEFAULT_PASS = 'defaultPass'; @@ -388,4 +388,4 @@ class Audit { } } -module.exports = Audit; +export {Audit}; diff --git a/lighthouse-core/audits/autocomplete.js b/lighthouse-core/audits/autocomplete.js index f0cb14b20f98..03fd010f1bf8 100644 --- a/lighthouse-core/audits/autocomplete.js +++ b/lighthouse-core/audits/autocomplete.js @@ -12,9 +12,9 @@ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const log = require('lighthouse-logger'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import log from 'lighthouse-logger'; const UIStrings = { /** Title of a Lighthouse audit that lets the user know if there are any missing or invalid autocomplete attributes on page inputs. This descriptive title is shown to users when all input attributes have a valid autocomplete attribute. */ @@ -48,7 +48,7 @@ const UIStrings = { manualReview: 'Requires manual review', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @type {string[]} This array contains all acceptable autocomplete attributes from the WHATWG standard. More found at https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill */ const validAutocompleteTokens = ['name', 'honorific-prefix', 'given-name', @@ -286,5 +286,5 @@ class AutocompleteAudit extends Audit { } } -module.exports = AutocompleteAudit; -module.exports.UIStrings = UIStrings; +export default AutocompleteAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/bootup-time.js b/lighthouse-core/audits/bootup-time.js index e08c17e8f1bc..0ad91c10e897 100644 --- a/lighthouse-core/audits/bootup-time.js +++ b/lighthouse-core/audits/bootup-time.js @@ -5,12 +5,12 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const {taskGroups} = require('../lib/tracehouse/task-groups.js'); -const i18n = require('../lib/i18n/i18n.js'); -const NetworkRecords = require('../computed/network-records.js'); -const MainThreadTasks = require('../computed/main-thread-tasks.js'); -const {getExecutionTimingsByURL} = require('../lib/tracehouse/task-summary.js'); +import {Audit} from './audit.js'; +import {taskGroups} from '../lib/tracehouse/task-groups.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import NetworkRecords from '../computed/network-records.js'; +import MainThreadTasks from '../computed/main-thread-tasks.js'; +import {getExecutionTimingsByURL} from '../lib/tracehouse/task-summary.js'; const UIStrings = { /** Title of a diagnostic audit that provides detail on the time spent executing javascript files during the load. This descriptive title is shown to users when the amount is acceptable and no user action is required. */ @@ -32,7 +32,7 @@ const UIStrings = { 'Try auditing the page in incognito mode or from a Chrome profile without extensions.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class BootupTime extends Audit { /** @@ -148,5 +148,5 @@ class BootupTime extends Audit { } } -module.exports = BootupTime; -module.exports.UIStrings = UIStrings; +export default BootupTime; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/byte-efficiency-audit.js b/lighthouse-core/audits/byte-efficiency/byte-efficiency-audit.js index 3456bc771f85..6520eb6ea11c 100644 --- a/lighthouse-core/audits/byte-efficiency/byte-efficiency-audit.js +++ b/lighthouse-core/audits/byte-efficiency/byte-efficiency-audit.js @@ -5,17 +5,17 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const linearInterpolation = require('../../lib/statistics.js').linearInterpolation; -const Interactive = require('../../computed/metrics/lantern-interactive.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const NetworkRecords = require('../../computed/network-records.js'); -const LoadSimulator = require('../../computed/load-simulator.js'); -const PageDependencyGraph = require('../../computed/page-dependency-graph.js'); +import {Audit} from '../audit.js'; +import {linearInterpolation} from '../../lib/statistics.js'; +import Interactive from '../../computed/metrics/lantern-interactive.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import NetworkRecords from '../../computed/network-records.js'; +import LoadSimulator from '../../computed/load-simulator.js'; +import PageDependencyGraph from '../../computed/page-dependency-graph.js'; -const str_ = i18n.createMessageInstanceIdFn(__filename, {}); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, {}); -/** @typedef {import('../../lib/dependency-graph/simulator/simulator')} Simulator */ +/** @typedef {import('../../lib/dependency-graph/simulator/simulator').Simulator} Simulator */ /** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ const WASTED_MS_FOR_AVERAGE = 300; @@ -36,7 +36,7 @@ const WASTED_MS_FOR_SCORE_OF_ZERO = 5000; * @overview Used as the base for all byte efficiency audits. Computes total bytes * and estimated time saved. Subclass and override `audit_` to return results. */ -class UnusedBytes extends Audit { +class ByteEfficiencyAudit extends Audit { /** * Creates a score based on the wastedMs value using linear interpolation between control points. * @@ -236,7 +236,7 @@ class UnusedBytes extends Audit { displayValue, numericValue: wastedMs, numericUnit: 'millisecond', - score: UnusedBytes.scoreForWastedMs(wastedMs), + score: ByteEfficiencyAudit.scoreForWastedMs(wastedMs), details, }; } @@ -256,4 +256,4 @@ class UnusedBytes extends Audit { /* eslint-enable no-unused-vars */ } -module.exports = UnusedBytes; +export {ByteEfficiencyAudit}; diff --git a/lighthouse-core/audits/byte-efficiency/duplicated-javascript.js b/lighthouse-core/audits/byte-efficiency/duplicated-javascript.js index 1cb02931e468..cd84a3d1b925 100644 --- a/lighthouse-core/audits/byte-efficiency/duplicated-javascript.js +++ b/lighthouse-core/audits/byte-efficiency/duplicated-javascript.js @@ -9,10 +9,11 @@ /** @typedef {LH.Audit.ByteEfficiencyItem & {source: string, subItems: {type: 'subitems', items: SubItem[]}}} Item */ /** @typedef {{url: string, sourceTransferBytes?: number}} SubItem */ -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const ModuleDuplication = require('../../computed/module-duplication.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const {getRequestForScript} = require('../../lib/script-helpers.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; + +import ModuleDuplication from '../../computed/module-duplication.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import {getRequestForScript} from '../../lib/script-helpers.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to remove duplicate JavaScript from their code. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -24,7 +25,7 @@ const UIStrings = { // '[Learn more](https://web.dev/duplicated-javascript/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const IGNORE_THRESHOLD_IN_BYTES = 1024; @@ -123,7 +124,7 @@ class DuplicatedJavascript extends ByteEfficiencyAudit { * @param {LH.Artifacts} artifacts * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords * @param {LH.Audit.Context} context - * @return {Promise<ByteEfficiencyAudit.ByteEfficiencyProduct>} + * @return {Promise<ByteEfficiencyProduct>} */ static async audit_(artifacts, networkRecords, context) { const ignoreThresholdInBytes = @@ -244,5 +245,5 @@ class DuplicatedJavascript extends ByteEfficiencyAudit { } } -module.exports = DuplicatedJavascript; -module.exports.UIStrings = UIStrings; +export default DuplicatedJavascript; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/efficient-animated-content.js b/lighthouse-core/audits/byte-efficiency/efficient-animated-content.js index d78bd83235ae..0605b9a226f5 100644 --- a/lighthouse-core/audits/byte-efficiency/efficient-animated-content.js +++ b/lighthouse-core/audits/byte-efficiency/efficient-animated-content.js @@ -8,9 +8,9 @@ */ 'use strict'; -const NetworkRequest = require('../../lib/network-request.js'); -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {NetworkRequest} from '../../lib/network-request.js'; +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to use video formats rather than animated GIFs, which are wasteful. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -21,7 +21,7 @@ const UIStrings = { 'network bytes. [Learn more](https://web.dev/efficient-animated-content/)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // If GIFs are above this size, we'll flag them // See https://github.com/GoogleChrome/lighthouse/pull/4885#discussion_r178406623 and https://github.com/GoogleChrome/lighthouse/issues/4696#issuecomment-370979920 @@ -54,7 +54,7 @@ class EfficientAnimatedContent extends ByteEfficiencyAudit { /** * @param {LH.Artifacts} artifacts * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords - * @return {ByteEfficiencyAudit.ByteEfficiencyProduct} + * @return {import('./byte-efficiency-audit.js').ByteEfficiencyProduct} */ static audit_(artifacts, networkRecords) { const unoptimizedContent = networkRecords.filter( @@ -88,5 +88,5 @@ class EfficientAnimatedContent extends ByteEfficiencyAudit { } } -module.exports = EfficientAnimatedContent; -module.exports.UIStrings = UIStrings; +export default EfficientAnimatedContent; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/legacy-javascript.js b/lighthouse-core/audits/byte-efficiency/legacy-javascript.js index 913321685f2e..dccf5d4b220e 100644 --- a/lighthouse-core/audits/byte-efficiency/legacy-javascript.js +++ b/lighthouse-core/audits/byte-efficiency/legacy-javascript.js @@ -18,11 +18,21 @@ /** @typedef {LH.Audit.ByteEfficiencyItem & {subItems: {type: 'subitems', items: SubItem[]}}} Item */ /** @typedef {{signal: string, location: LH.Audit.Details.SourceLocationValue}} SubItem */ -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const JsBundles = require('../../computed/js-bundles.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const thirdPartyWeb = require('../../lib/third-party-web.js'); -const {getRequestForScript} = require('../../lib/script-helpers.js'); +import fs from 'fs'; + +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; + +import JsBundles from '../../computed/js-bundles.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import thirdPartyWeb from '../../lib/third-party-web.js'; +import {getRequestForScript} from '../../lib/script-helpers.js'; +import {LH_ROOT} from '../../../root.js'; + +const graphJson = fs.readFileSync( + `${LH_ROOT}/lighthouse-core/audits/byte-efficiency/polyfill-graph-data.json`, 'utf-8'); + +/** @type {import('../../scripts/legacy-javascript/create-polyfill-size-estimation.js').PolyfillSizeEstimator} */ +const graph = JSON.parse(graphJson); const UIStrings = { /** Title of a Lighthouse audit that tells the user about legacy polyfills and transforms used on the page. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -33,7 +43,7 @@ const UIStrings = { description: 'Polyfills and transforms enable legacy browsers to use new JavaScript features. However, many aren\'t necessary for modern browsers. For your bundled JavaScript, adopt a modern script deployment strategy using module/nomodule feature detection to reduce the amount of code shipped to modern browsers, while retaining support for legacy browsers. [Learn More](https://web.dev/publish-modern-javascript/)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * Takes a list of patterns (consisting of a name identifier and a RegExp expression string) @@ -327,8 +337,6 @@ class LegacyJavascript extends ByteEfficiencyAudit { const transformResults = matches.filter(m => m.name.startsWith('@')); let estimatedWastedBytesFromPolyfills = 0; - /** @type {import('../../scripts/legacy-javascript/create-polyfill-size-estimation.js').PolyfillSizeEstimator} */ - const graph = require('./polyfill-graph-data.json'); const modulesSeen = new Set(); for (const result of polyfillResults) { const modules = graph.dependencies[result.name]; @@ -466,5 +474,5 @@ class LegacyJavascript extends ByteEfficiencyAudit { } } -module.exports = LegacyJavascript; -module.exports.UIStrings = UIStrings; +export default LegacyJavascript; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/modern-image-formats.js b/lighthouse-core/audits/byte-efficiency/modern-image-formats.js index ff31372e605c..e912efc47cd5 100644 --- a/lighthouse-core/audits/byte-efficiency/modern-image-formats.js +++ b/lighthouse-core/audits/byte-efficiency/modern-image-formats.js @@ -8,9 +8,9 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const URL = require('../../lib/url-shim.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import URL from '../../lib/url-shim.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to serve images in newer and more efficient image formats in order to enhance the performance of a page. A non-modern image format was designed 20+ years ago. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -21,7 +21,7 @@ const UIStrings = { '[Learn more](https://web.dev/uses-webp-images/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const IGNORE_THRESHOLD_IN_BYTES = 8192; @@ -89,7 +89,7 @@ class ModernImageFormats extends ByteEfficiencyAudit { /** * @param {LH.Artifacts} artifacts - * @return {ByteEfficiencyAudit.ByteEfficiencyProduct} + * @return {import('./byte-efficiency-audit.js').ByteEfficiencyProduct} */ static audit_(artifacts) { const pageURL = artifacts.URL.finalUrl; @@ -182,5 +182,5 @@ class ModernImageFormats extends ByteEfficiencyAudit { } } -module.exports = ModernImageFormats; -module.exports.UIStrings = UIStrings; +export default ModernImageFormats; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/offscreen-images.js b/lighthouse-core/audits/byte-efficiency/offscreen-images.js index c49e9313932a..449bf4510ae9 100644 --- a/lighthouse-core/audits/byte-efficiency/offscreen-images.js +++ b/lighthouse-core/audits/byte-efficiency/offscreen-images.js @@ -9,13 +9,13 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const Sentry = require('../../lib/sentry.js'); -const URL = require('../../lib/url-shim.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const Interactive = require('../../computed/metrics/interactive.js'); -const ProcessedTrace = require('../../computed/processed-trace.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import {Sentry} from '../../lib/sentry.js'; +import URL from '../../lib/url-shim.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import Interactive from '../../computed/metrics/interactive.js'; +import ProcessedTrace from '../../computed/processed-trace.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to defer loading offscreen images. Offscreen images are images located outside of the visible browser viewport. As they are unseen by the user and slow down page load, they should be loaded later, closer to when the user is going to see them. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -27,7 +27,7 @@ const UIStrings = { '[Learn more](https://web.dev/offscreen-images/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // See https://github.com/GoogleChrome/lighthouse/issues/10471 for discussion about the thresholds here. const ALLOWABLE_OFFSCREEN_IN_PX = 100; @@ -174,7 +174,7 @@ class OffscreenImages extends ByteEfficiencyAudit { * @param {LH.Artifacts} artifacts * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords * @param {LH.Audit.Context} context - * @return {Promise<ByteEfficiencyAudit.ByteEfficiencyProduct>} + * @return {Promise<import('./byte-efficiency-audit.js').ByteEfficiencyProduct>} */ static async audit_(artifacts, networkRecords, context) { const images = artifacts.ImageElements; @@ -249,5 +249,5 @@ class OffscreenImages extends ByteEfficiencyAudit { } } -module.exports = OffscreenImages; -module.exports.UIStrings = UIStrings; +export default OffscreenImages; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/render-blocking-resources.js b/lighthouse-core/audits/byte-efficiency/render-blocking-resources.js index 97270c2b7e58..001a33d09e7f 100644 --- a/lighthouse-core/audits/byte-efficiency/render-blocking-resources.js +++ b/lighthouse-core/audits/byte-efficiency/render-blocking-resources.js @@ -9,18 +9,18 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const BaseNode = require('../../lib/dependency-graph/base-node.js'); -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const UnusedCSS = require('../../computed/unused-css.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const ProcessedTrace = require('../../computed/processed-trace.js'); -const ProcessedNavigation = require('../../computed/processed-navigation.js'); -const LoadSimulator = require('../../computed/load-simulator.js'); -const FirstContentfulPaint = require('../../computed/metrics/first-contentful-paint.js'); - -/** @typedef {import('../../lib/dependency-graph/simulator/simulator')} Simulator */ +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import {BaseNode} from '../../lib/dependency-graph/base-node.js'; +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import UnusedCSS from '../../computed/unused-css.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import ProcessedTrace from '../../computed/processed-trace.js'; +import ProcessedNavigation from '../../computed/processed-navigation.js'; +import LoadSimulator from '../../computed/load-simulator.js'; +import FirstContentfulPaint from '../../computed/metrics/first-contentful-paint.js'; + +/** @typedef {import('../../lib/dependency-graph/simulator/simulator').Simulator} Simulator */ /** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ /** @typedef {import('../../lib/dependency-graph/network-node.js')} NetworkNode */ @@ -39,7 +39,7 @@ const UIStrings = { 'JS/styles. [Learn more](https://web.dev/render-blocking-resources/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * Given a simulation's nodeTimings, return an object with the nodes/timing keyed by network URL @@ -304,5 +304,5 @@ class RenderBlockingResources extends Audit { } } -module.exports = RenderBlockingResources; -module.exports.UIStrings = UIStrings; +export default RenderBlockingResources; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/total-byte-weight.js b/lighthouse-core/audits/byte-efficiency/total-byte-weight.js index 5c576e5d78da..628fb17f2a8d 100644 --- a/lighthouse-core/audits/byte-efficiency/total-byte-weight.js +++ b/lighthouse-core/audits/byte-efficiency/total-byte-weight.js @@ -5,10 +5,10 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const NetworkRecords = require('../../computed/network-records.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import NetworkRecords from '../../computed/network-records.js'; const UIStrings = { /** Title of a diagnostic audit that provides detail on large network resources required during page load. 'Payloads' is roughly equivalent to 'resources'. This descriptive title is shown to users when the amount is acceptable and no user action is required. */ @@ -24,7 +24,7 @@ const UIStrings = { displayValue: 'Total size was {totalBytes, number, bytes}\xa0KiB', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class TotalByteWeight extends Audit { /** @@ -107,5 +107,5 @@ class TotalByteWeight extends Audit { } } -module.exports = TotalByteWeight; -module.exports.UIStrings = UIStrings; +export default TotalByteWeight; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/unminified-css.js b/lighthouse-core/audits/byte-efficiency/unminified-css.js index a283ff44a576..e4093a8147cc 100644 --- a/lighthouse-core/audits/byte-efficiency/unminified-css.js +++ b/lighthouse-core/audits/byte-efficiency/unminified-css.js @@ -5,10 +5,10 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const UnusedCSS = require('../../computed/unused-css.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const computeTokenLength = require('../../lib/minification-estimator.js').computeCSSTokenLength; +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import UnusedCSS from '../../computed/unused-css.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import {computeCSSTokenLength as computeTokenLength} from '../../lib/minification-estimator.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to minify (remove whitespace) the page's CSS code. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -18,7 +18,7 @@ const UIStrings = { '[Learn more](https://web.dev/unminified-css/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const IGNORE_THRESHOLD_IN_PERCENT = 5; const IGNORE_THRESHOLD_IN_BYTES = 2048; @@ -81,7 +81,7 @@ class UnminifiedCSS extends ByteEfficiencyAudit { /** * @param {LH.Artifacts} artifacts * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords - * @return {ByteEfficiencyAudit.ByteEfficiencyProduct} + * @return {import('./byte-efficiency-audit.js').ByteEfficiencyProduct} */ static audit_(artifacts, networkRecords) { const items = []; @@ -111,5 +111,5 @@ class UnminifiedCSS extends ByteEfficiencyAudit { } } -module.exports = UnminifiedCSS; -module.exports.UIStrings = UIStrings; +export default UnminifiedCSS; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/unminified-javascript.js b/lighthouse-core/audits/byte-efficiency/unminified-javascript.js index b512edef9a85..4f5cacb5473c 100644 --- a/lighthouse-core/audits/byte-efficiency/unminified-javascript.js +++ b/lighthouse-core/audits/byte-efficiency/unminified-javascript.js @@ -5,10 +5,10 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const computeTokenLength = require('../../lib/minification-estimator.js').computeJSTokenLength; -const {getRequestForScript, isInline} = require('../../lib/script-helpers.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import {computeJSTokenLength as computeTokenLength} from '../../lib/minification-estimator.js'; +import {getRequestForScript, isInline} from '../../lib/script-helpers.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to minify the page’s JS code to reduce file size. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -18,7 +18,7 @@ const UIStrings = { '[Learn more](https://web.dev/unminified-javascript/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const IGNORE_THRESHOLD_IN_PERCENT = 10; const IGNORE_THRESHOLD_IN_BYTES = 2048; @@ -73,7 +73,7 @@ class UnminifiedJavaScript extends ByteEfficiencyAudit { /** * @param {LH.Artifacts} artifacts * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords - * @return {ByteEfficiencyAudit.ByteEfficiencyProduct} + * @return {import('./byte-efficiency-audit.js').ByteEfficiencyProduct} */ static audit_(artifacts, networkRecords) { /** @type {Array<LH.Audit.ByteEfficiencyItem>} */ @@ -115,5 +115,5 @@ class UnminifiedJavaScript extends ByteEfficiencyAudit { } } -module.exports = UnminifiedJavaScript; -module.exports.UIStrings = UIStrings; +export default UnminifiedJavaScript; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/unused-css-rules.js b/lighthouse-core/audits/byte-efficiency/unused-css-rules.js index e83cc8085cc8..ad5532125650 100644 --- a/lighthouse-core/audits/byte-efficiency/unused-css-rules.js +++ b/lighthouse-core/audits/byte-efficiency/unused-css-rules.js @@ -5,9 +5,9 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const UnusedCSS = require('../../computed/unused-css.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import UnusedCSS from '../../computed/unused-css.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to reduce content from their CSS that isn’t needed immediately and instead load that content at a later time. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -18,7 +18,7 @@ const UIStrings = { '[Learn more](https://web.dev/unused-css-rules/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // Allow 10KiB of unused CSS to permit `:hover` and other styles not used on a non-interactive load. // @see https://github.com/GoogleChrome/lighthouse/issues/9353 for more discussion. @@ -42,7 +42,7 @@ class UnusedCSSRules extends ByteEfficiencyAudit { * @param {LH.Artifacts} artifacts * @param {LH.Artifacts.NetworkRequest[]} _ * @param {LH.Audit.Context} context - * @return {Promise<ByteEfficiencyAudit.ByteEfficiencyProduct>} + * @return {Promise<import('./byte-efficiency-audit.js').ByteEfficiencyProduct>} */ static async audit_(artifacts, _, context) { const unusedCssItems = await UnusedCSS.request({ @@ -66,5 +66,5 @@ class UnusedCSSRules extends ByteEfficiencyAudit { } } -module.exports = UnusedCSSRules; -module.exports.UIStrings = UIStrings; +export default UnusedCSSRules; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/unused-javascript.js b/lighthouse-core/audits/byte-efficiency/unused-javascript.js index 669f70792ba5..c710e8eb8ae6 100644 --- a/lighthouse-core/audits/byte-efficiency/unused-javascript.js +++ b/lighthouse-core/audits/byte-efficiency/unused-javascript.js @@ -5,11 +5,11 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const UnusedJavaScriptSummary = require('../../computed/unused-javascript-summary.js'); -const JsBundles = require('../../computed/js-bundles.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const {getRequestForScript} = require('../../lib/script-helpers.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import UnusedJavaScriptSummary from '../../computed/unused-javascript-summary.js'; +import JsBundles from '../../computed/js-bundles.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import {getRequestForScript} from '../../lib/script-helpers.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to reduce JavaScript that is never evaluated during page load. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -19,7 +19,7 @@ const UIStrings = { 'decrease bytes consumed by network activity. [Learn more](https://web.dev/unused-javascript/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const UNUSED_BYTES_IGNORE_THRESHOLD = 20 * 1024; const UNUSED_BYTES_IGNORE_BUNDLE_SOURCE_THRESHOLD = 512; @@ -77,7 +77,7 @@ class UnusedJavaScript extends ByteEfficiencyAudit { * @param {LH.Artifacts} artifacts * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords * @param {LH.Audit.Context} context - * @return {Promise<ByteEfficiencyAudit.ByteEfficiencyProduct>} + * @return {Promise<import('./byte-efficiency-audit.js').ByteEfficiencyProduct>} */ static async audit_(artifacts, networkRecords, context) { const bundles = await JsBundles.request(artifacts, context); @@ -160,5 +160,5 @@ class UnusedJavaScript extends ByteEfficiencyAudit { } } -module.exports = UnusedJavaScript; -module.exports.UIStrings = UIStrings; +export default UnusedJavaScript; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/uses-long-cache-ttl.js b/lighthouse-core/audits/byte-efficiency/uses-long-cache-ttl.js index 90726899c3c5..f927592444a4 100644 --- a/lighthouse-core/audits/byte-efficiency/uses-long-cache-ttl.js +++ b/lighthouse-core/audits/byte-efficiency/uses-long-cache-ttl.js @@ -5,13 +5,13 @@ */ 'use strict'; -const parseCacheControl = require('parse-cache-control'); -const Audit = require('../audit.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const URL = require('../../lib/url-shim.js'); -const linearInterpolation = require('../../lib/statistics.js').linearInterpolation; -const i18n = require('../../lib/i18n/i18n.js'); -const NetworkRecords = require('../../computed/network-records.js'); +import parseCacheControl from 'parse-cache-control'; +import {Audit} from '../audit.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import URL from '../../lib/url-shim.js'; +import {linearInterpolation} from '../../lib/statistics.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import NetworkRecords from '../../computed/network-records.js'; const UIStrings = { /** Title of a diagnostic audit that provides detail on the cache policy applies to the page's static assets. Cache refers to browser disk cache, which keeps old versions of network resources around for future use. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -29,7 +29,7 @@ const UIStrings = { }`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // Ignore assets that have very high likelihood of cache hit const IGNORE_THRESHOLD_IN_PERCENT = 0.925; @@ -294,5 +294,5 @@ class CacheHeaders extends Audit { } } -module.exports = CacheHeaders; -module.exports.UIStrings = UIStrings; +export default CacheHeaders; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/uses-optimized-images.js b/lighthouse-core/audits/byte-efficiency/uses-optimized-images.js index 9b432f3358a6..b9e34db087b5 100644 --- a/lighthouse-core/audits/byte-efficiency/uses-optimized-images.js +++ b/lighthouse-core/audits/byte-efficiency/uses-optimized-images.js @@ -9,9 +9,9 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const URL = require('../../lib/url-shim.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import URL from '../../lib/url-shim.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to encode images with optimization (better compression). This is displayed in a list of audit titles that Lighthouse generates. */ @@ -21,7 +21,7 @@ const UIStrings = { '[Learn more](https://web.dev/uses-optimized-images/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const IGNORE_THRESHOLD_IN_BYTES = 4096; @@ -66,7 +66,7 @@ class UsesOptimizedImages extends ByteEfficiencyAudit { /** * @param {LH.Artifacts} artifacts - * @return {ByteEfficiencyAudit.ByteEfficiencyProduct} + * @return {import('./byte-efficiency-audit.js').ByteEfficiencyProduct} */ static audit_(artifacts) { const pageURL = artifacts.URL.finalUrl; @@ -141,5 +141,5 @@ class UsesOptimizedImages extends ByteEfficiencyAudit { } } -module.exports = UsesOptimizedImages; -module.exports.UIStrings = UIStrings; +export default UsesOptimizedImages; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/uses-responsive-images-snapshot.js b/lighthouse-core/audits/byte-efficiency/uses-responsive-images-snapshot.js index 3e1fd1ae1d3e..2a2b928511fe 100644 --- a/lighthouse-core/audits/byte-efficiency/uses-responsive-images-snapshot.js +++ b/lighthouse-core/audits/byte-efficiency/uses-responsive-images-snapshot.js @@ -11,10 +11,10 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const UsesResponsiveImages = require('./uses-responsive-images.js'); -const URL = require('../../lib/url-shim.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import * as UsesResponsiveImages from './uses-responsive-images.js'; +import URL from '../../lib/url-shim.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Descriptive title of a Lighthouse audit that checks if images match their displayed dimensions. This is displayed when the audit is passing. */ @@ -27,7 +27,7 @@ const UIStrings = { columnActualDimensions: 'Actual dimensions', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // Based on byte threshold of 4096, with 3 bytes per pixel. const IGNORE_THRESHOLD_IN_PIXELS = 1365; @@ -58,7 +58,7 @@ class UsesResponsiveImagesSnapshot extends Audit { for (const image of artifacts.ImageElements) { if (!image.naturalDimensions) continue; const actual = image.naturalDimensions; - const displayed = UsesResponsiveImages.getDisplayedDimensions( + const displayed = UsesResponsiveImages.default.getDisplayedDimensions( {...image, naturalWidth: actual.width, naturalHeight: actual.height}, artifacts.ViewportDimensions ); @@ -96,5 +96,5 @@ class UsesResponsiveImagesSnapshot extends Audit { } } -module.exports = UsesResponsiveImagesSnapshot; -module.exports.UIStrings = UIStrings; +export default UsesResponsiveImagesSnapshot; +export {UIStrings}; diff --git a/lighthouse-core/audits/byte-efficiency/uses-responsive-images.js b/lighthouse-core/audits/byte-efficiency/uses-responsive-images.js index 891c590c6442..f6d7cadf07bb 100644 --- a/lighthouse-core/audits/byte-efficiency/uses-responsive-images.js +++ b/lighthouse-core/audits/byte-efficiency/uses-responsive-images.js @@ -13,11 +13,11 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const ImageRecords = require('../../computed/image-records.js'); -const URL = require('../../lib/url-shim.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import ImageRecords from '../../computed/image-records.js'; +import URL from '../../lib/url-shim.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to resize images to match the display dimensions. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -29,7 +29,7 @@ const UIStrings = { '[Learn more](https://web.dev/uses-responsive-images/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const IGNORE_THRESHOLD_IN_BYTES = 4096; @@ -131,7 +131,7 @@ class UsesResponsiveImages extends ByteEfficiencyAudit { * @param {LH.Artifacts} artifacts * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords * @param {LH.Audit.Context} context - * @return {Promise<ByteEfficiencyAudit.ByteEfficiencyProduct>} + * @return {Promise<import('./byte-efficiency-audit.js').ByteEfficiencyProduct>} */ static async audit_(artifacts, networkRecords, context) { const images = await ImageRecords.request({ @@ -197,6 +197,5 @@ class UsesResponsiveImages extends ByteEfficiencyAudit { } } -module.exports = UsesResponsiveImages; -module.exports.UIStrings = UIStrings; -module.exports.str_ = str_; +export default UsesResponsiveImages; +export {UIStrings, str_}; diff --git a/lighthouse-core/audits/byte-efficiency/uses-text-compression.js b/lighthouse-core/audits/byte-efficiency/uses-text-compression.js index 008067a40376..ecfc116f5154 100644 --- a/lighthouse-core/audits/byte-efficiency/uses-text-compression.js +++ b/lighthouse-core/audits/byte-efficiency/uses-text-compression.js @@ -9,9 +9,9 @@ */ 'use strict'; -const ByteEfficiencyAudit = require('./byte-efficiency-audit.js'); -const URL = require('../../lib/url-shim.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {ByteEfficiencyAudit} from './byte-efficiency-audit.js'; +import URL from '../../lib/url-shim.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to enable text compression (like gzip) in order to enhance the performance of a page. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -22,7 +22,7 @@ const UIStrings = { ' [Learn more](https://web.dev/uses-text-compression/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const IGNORE_THRESHOLD_IN_BYTES = 1400; const IGNORE_THRESHOLD_IN_PERCENT = 0.1; @@ -43,7 +43,7 @@ class ResponsesAreCompressed extends ByteEfficiencyAudit { /** * @param {LH.Artifacts} artifacts - * @return {ByteEfficiencyAudit.ByteEfficiencyProduct} + * @return {import('./byte-efficiency-audit.js').ByteEfficiencyProduct} */ static audit_(artifacts) { const uncompressedResponses = artifacts.ResponseCompression; @@ -96,5 +96,5 @@ class ResponsesAreCompressed extends ByteEfficiencyAudit { } } -module.exports = ResponsesAreCompressed; -module.exports.UIStrings = UIStrings; +export default ResponsesAreCompressed; +export {UIStrings}; diff --git a/lighthouse-core/audits/content-width.js b/lighthouse-core/audits/content-width.js index 718ae991abf2..1478b47576fb 100644 --- a/lighthouse-core/audits/content-width.js +++ b/lighthouse-core/audits/content-width.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the content size of a web site compared to the viewport, which is the size of the screen the site is displayed on. This descriptive title is shown to users when the site's content is sized appropriately. */ @@ -26,7 +26,7 @@ const UIStrings = { 'size of {outerWidth}px.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ContentWidth extends Audit { /** @@ -73,5 +73,5 @@ class ContentWidth extends Audit { } } -module.exports = ContentWidth; -module.exports.UIStrings = UIStrings; +export default ContentWidth; +export {UIStrings}; diff --git a/lighthouse-core/audits/critical-request-chains.js b/lighthouse-core/audits/critical-request-chains.js index e822d078b587..d35de749cb9f 100644 --- a/lighthouse-core/audits/critical-request-chains.js +++ b/lighthouse-core/audits/critical-request-chains.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const ComputedChains = require('../computed/critical-request-chains.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import ComputedChains from '../computed/critical-request-chains.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to reduce the depth of critical network requests to enhance initial load of a page. Critical request chains are series of dependent network requests that are important for page rendering. For example, here's a 4-request-deep chain: The biglogo.jpg image is required, but is requested via the styles.css style code, which is requested by the initialize.js javascript, which is requested by the page's HTML. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -25,7 +25,7 @@ const UIStrings = { }`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class CriticalRequestChains extends Audit { /** @@ -216,5 +216,5 @@ class CriticalRequestChains extends Audit { } } -module.exports = CriticalRequestChains; -module.exports.UIStrings = UIStrings; +export default CriticalRequestChains; +export {UIStrings}; diff --git a/lighthouse-core/audits/csp-xss.js b/lighthouse-core/audits/csp-xss.js index e45fb0d8f2a9..7e64eb9e7327 100644 --- a/lighthouse-core/audits/csp-xss.js +++ b/lighthouse-core/audits/csp-xss.js @@ -5,13 +5,10 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const MainResource = require('../computed/main-resource.js'); -const i18n = require('../lib/i18n/i18n.js'); -const { - evaluateRawCspsForXss, - getTranslatedDescription, -} = require('../lib/csp-evaluator.js'); +import {Audit} from './audit.js'; +import MainResource from '../computed/main-resource.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import {evaluateRawCspsForXss, getTranslatedDescription} from '../lib/csp-evaluator.js'; /** @typedef {import('../lib/csp-evaluator.js').Finding} Finding */ @@ -35,7 +32,7 @@ const UIStrings = { itemSeveritySyntax: 'Syntax', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class CspXss extends Audit { /** @@ -182,5 +179,5 @@ class CspXss extends Audit { } } -module.exports = CspXss; -module.exports.UIStrings = UIStrings; +export default CspXss; +export {UIStrings}; diff --git a/lighthouse-core/audits/deprecations.js b/lighthouse-core/audits/deprecations.js index 671668d4a1bb..483ac431e293 100644 --- a/lighthouse-core/audits/deprecations.js +++ b/lighthouse-core/audits/deprecations.js @@ -9,9 +9,10 @@ * @fileoverview Audits a page to determine if it is calling deprecated APIs. */ -const Audit = require('./audit.js'); -const JsBundles = require('../computed/js-bundles.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; + +import JsBundles from '../computed/js-bundles.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the use of deprecated APIs. This descriptive title is shown to users when the page does not use deprecated APIs. */ @@ -32,7 +33,7 @@ const UIStrings = { columnLine: 'Line', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class Deprecations extends Audit { /** @@ -90,5 +91,5 @@ class Deprecations extends Audit { } } -module.exports = Deprecations; -module.exports.UIStrings = UIStrings; +export default Deprecations; +export {UIStrings}; diff --git a/lighthouse-core/audits/diagnostics.js b/lighthouse-core/audits/diagnostics.js index 5928e57b9898..6b10235791c9 100644 --- a/lighthouse-core/audits/diagnostics.js +++ b/lighthouse-core/audits/diagnostics.js @@ -5,11 +5,11 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const MainThreadTasksComputed = require('../computed/main-thread-tasks.js'); -const NetworkRecordsComputed = require('../computed/network-records.js'); -const NetworkAnalysisComputed = require('../computed/network-analysis.js'); -const MainResource = require('../computed/main-resource.js'); +import {Audit} from './audit.js'; +import MainThreadTasksComputed from '../computed/main-thread-tasks.js'; +import NetworkRecordsComputed from '../computed/network-records.js'; +import NetworkAnalysisComputed from '../computed/network-analysis.js'; +import MainResource from '../computed/main-resource.js'; class Diagnostics extends Audit { /** @@ -77,4 +77,4 @@ class Diagnostics extends Audit { } } -module.exports = Diagnostics; +export default Diagnostics; diff --git a/lighthouse-core/audits/dobetterweb/charset.js b/lighthouse-core/audits/dobetterweb/charset.js index 110d60eac109..d6f1869cdae6 100644 --- a/lighthouse-core/audits/dobetterweb/charset.js +++ b/lighthouse-core/audits/dobetterweb/charset.js @@ -12,9 +12,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const MainResource = require('../../computed/main-resource.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import MainResource from '../../computed/main-resource.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on if the charset is set properly for a page. This title is shown when the charset is defined correctly. Charset defines the character encoding (eg UTF-8) of the page content. */ @@ -27,7 +27,7 @@ const UIStrings = { '[Learn more](https://web.dev/charset/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const CONTENT_TYPE_HEADER = 'content-type'; // /^[a-zA-Z0-9-_:.()]{2,}$/ matches all known IANA charset names (https://www.iana.org/assignments/character-sets/character-sets.xhtml) @@ -89,8 +89,5 @@ class CharsetDefined extends Audit { } } -module.exports = CharsetDefined; -module.exports.UIStrings = UIStrings; -module.exports.CHARSET_HTML_REGEX = CHARSET_HTML_REGEX; -module.exports.CHARSET_HTTP_REGEX = CHARSET_HTTP_REGEX; -module.exports.IANA_REGEX = IANA_REGEX; +export default CharsetDefined; +export {UIStrings, CHARSET_HTML_REGEX, CHARSET_HTTP_REGEX, IANA_REGEX}; diff --git a/lighthouse-core/audits/dobetterweb/doctype.js b/lighthouse-core/audits/dobetterweb/doctype.js index 51a992d0dc7c..cabde5694156 100644 --- a/lighthouse-core/audits/dobetterweb/doctype.js +++ b/lighthouse-core/audits/dobetterweb/doctype.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the doctype of a page. This descriptive title is shown to users when the pages's doctype is set to HTML. */ @@ -29,7 +29,7 @@ const UIStrings = { explanationBadDoctype: 'Doctype name must be the string `html`', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class Doctype extends Audit { /** @@ -101,5 +101,5 @@ class Doctype extends Audit { } } -module.exports = Doctype; -module.exports.UIStrings = UIStrings; +export default Doctype; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/dom-size.js b/lighthouse-core/audits/dobetterweb/dom-size.js index 7ff253eae131..bc5543f47f7e 100644 --- a/lighthouse-core/audits/dobetterweb/dom-size.js +++ b/lighthouse-core/audits/dobetterweb/dom-size.js @@ -12,8 +12,8 @@ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a diagnostic audit that provides detail on the size of the web page's DOM. The size of a DOM is characterized by the total number of DOM elements and greatest DOM depth. This descriptive title is shown to users when the amount is acceptable and no user action is required. */ @@ -41,7 +41,7 @@ const UIStrings = { statisticDOMWidth: 'Maximum Child Elements', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class DOMSize extends Audit { /** @@ -119,5 +119,5 @@ class DOMSize extends Audit { } } -module.exports = DOMSize; -module.exports.UIStrings = UIStrings; +export default DOMSize; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/geolocation-on-start.js b/lighthouse-core/audits/dobetterweb/geolocation-on-start.js index 33b0df066597..e04b229d7168 100644 --- a/lighthouse-core/audits/dobetterweb/geolocation-on-start.js +++ b/lighthouse-core/audits/dobetterweb/geolocation-on-start.js @@ -11,8 +11,8 @@ 'use strict'; -const ViolationAudit = require('../violation-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import ViolationAudit from '../violation-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on geolocation permission requests while the page is loading. This descriptive title is shown to users when the page does not ask for geolocation permissions on load. */ @@ -25,7 +25,7 @@ const UIStrings = { '[Learn more](https://web.dev/geolocation-on-start/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class GeolocationOnStart extends ViolationAudit { /** @@ -66,5 +66,5 @@ class GeolocationOnStart extends ViolationAudit { } } -module.exports = GeolocationOnStart; -module.exports.UIStrings = UIStrings; +export default GeolocationOnStart; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/inspector-issues.js b/lighthouse-core/audits/dobetterweb/inspector-issues.js index 781b8f48b70a..8d942bb49c75 100644 --- a/lighthouse-core/audits/dobetterweb/inspector-issues.js +++ b/lighthouse-core/audits/dobetterweb/inspector-issues.js @@ -15,8 +15,9 @@ /** @typedef {{url: string}} IssueSubItem */ /** @typedef {{issueType: string|LH.IcuMessage, subItems: Array<IssueSubItem>}} IssueItem */ -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on various types of problems with a website, like security or network errors. This descriptive title is shown to users when no issues were logged into the Chrome DevTools Issues panel. */ @@ -35,7 +36,7 @@ const UIStrings = { issueTypeHeavyAds: 'Heavy resource usage by ads', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class IssuesPanelEntries extends Audit { /** @@ -188,5 +189,5 @@ class IssuesPanelEntries extends Audit { } } -module.exports = IssuesPanelEntries; -module.exports.UIStrings = UIStrings; +export default IssuesPanelEntries; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/js-libraries.js b/lighthouse-core/audits/dobetterweb/js-libraries.js index 84c3a16c0571..64470870a7a5 100644 --- a/lighthouse-core/audits/dobetterweb/js-libraries.js +++ b/lighthouse-core/audits/dobetterweb/js-libraries.js @@ -10,8 +10,8 @@ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the Javascript libraries that are used on the page. */ @@ -22,7 +22,7 @@ const UIStrings = { columnVersion: 'Version', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class JsLibrariesAudit extends Audit { /** @@ -84,5 +84,5 @@ class JsLibrariesAudit extends Audit { } } -module.exports = JsLibrariesAudit; -module.exports.UIStrings = UIStrings; +export default JsLibrariesAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/no-document-write.js b/lighthouse-core/audits/dobetterweb/no-document-write.js index fc29e657d8cf..a78940279f88 100644 --- a/lighthouse-core/audits/dobetterweb/no-document-write.js +++ b/lighthouse-core/audits/dobetterweb/no-document-write.js @@ -28,8 +28,8 @@ 'use strict'; -const ViolationAudit = require('../violation-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import ViolationAudit from '../violation-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the page's use of the `document.write` API. This descriptive title is shown to users when the page does not use `document.write`. */ @@ -42,7 +42,7 @@ const UIStrings = { '[Learn more](https://web.dev/no-document-write/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class NoDocWriteAudit extends ViolationAudit { /** @@ -81,5 +81,5 @@ class NoDocWriteAudit extends ViolationAudit { } } -module.exports = NoDocWriteAudit; -module.exports.UIStrings = UIStrings; +export default NoDocWriteAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/no-vulnerable-libraries.js b/lighthouse-core/audits/dobetterweb/no-vulnerable-libraries.js index 2743b5d730b6..8fd5df0cda30 100644 --- a/lighthouse-core/audits/dobetterweb/no-vulnerable-libraries.js +++ b/lighthouse-core/audits/dobetterweb/no-vulnerable-libraries.js @@ -12,11 +12,15 @@ 'use strict'; -const Audit = require('../audit.js'); -const Sentry = require('../../lib/sentry.js'); -const semver = require('semver'); -const snykDatabase = require('../../../third-party/snyk/snapshot.json'); -const i18n = require('../../lib/i18n/i18n.js'); +import fs from 'fs'; +import {Audit} from '../audit.js'; +import {Sentry} from '../../lib/sentry.js'; +import semver from 'semver'; +import * as i18n from '../../lib/i18n/i18n.js'; +import {LH_ROOT} from '../../../root.js'; + +const snykDatabase = JSON.parse( + fs.readFileSync(`${LH_ROOT}/third-party/snyk/snapshot.json`, 'utf-8')); const UIStrings = { /** Title of a Lighthouse audit that provides detail on Javascript libraries the page uses. This descriptive title is shown to users when all Javascript libraries are free of known security vulnerabilities. */ @@ -42,7 +46,7 @@ const UIStrings = { columnSeverity: 'Highest Severity', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const SEMVER_REGEX = /^(\d+\.\d+\.\d+)[^-0-9]+/; @@ -221,5 +225,5 @@ class NoVulnerableLibrariesAudit extends Audit { } } -module.exports = NoVulnerableLibrariesAudit; -module.exports.UIStrings = UIStrings; +export default NoVulnerableLibrariesAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/notification-on-start.js b/lighthouse-core/audits/dobetterweb/notification-on-start.js index 7df8a4b445a0..3ad4d4ea3a7f 100644 --- a/lighthouse-core/audits/dobetterweb/notification-on-start.js +++ b/lighthouse-core/audits/dobetterweb/notification-on-start.js @@ -11,8 +11,8 @@ 'use strict'; -const ViolationAudit = require('../violation-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import ViolationAudit from '../violation-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the page's notification permission requests. This descriptive title is shown to users when the page does not ask for notification permission on load. */ @@ -25,7 +25,7 @@ const UIStrings = { 'instead. [Learn more](https://web.dev/notification-on-start/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class NotificationOnStart extends ViolationAudit { /** @@ -65,5 +65,5 @@ class NotificationOnStart extends ViolationAudit { } } -module.exports = NotificationOnStart; -module.exports.UIStrings = UIStrings; +export default NotificationOnStart; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/password-inputs-can-be-pasted-into.js b/lighthouse-core/audits/dobetterweb/password-inputs-can-be-pasted-into.js index fb08ef99071a..8832fb37c62f 100644 --- a/lighthouse-core/audits/dobetterweb/password-inputs-can-be-pasted-into.js +++ b/lighthouse-core/audits/dobetterweb/password-inputs-can-be-pasted-into.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the ability to paste into password fields. This descriptive title is shown to users when the page allows pasting of content into password fields. */ @@ -18,7 +18,7 @@ const UIStrings = { '[Learn more](https://web.dev/password-inputs-can-be-pasted-into/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class PasswordInputsCanBePastedIntoAudit extends Audit { /** @@ -62,5 +62,5 @@ class PasswordInputsCanBePastedIntoAudit extends Audit { } } -module.exports = PasswordInputsCanBePastedIntoAudit; -module.exports.UIStrings = UIStrings; +export default PasswordInputsCanBePastedIntoAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/uses-http2.js b/lighthouse-core/audits/dobetterweb/uses-http2.js index c2e5146e58b2..a5acbe52d21e 100644 --- a/lighthouse-core/audits/dobetterweb/uses-http2.js +++ b/lighthouse-core/audits/dobetterweb/uses-http2.js @@ -10,19 +10,20 @@ * origin are over the http/2 protocol. */ -/** @typedef {import('../../lib/dependency-graph/simulator/simulator')} Simulator */ +/** @typedef {import('../../lib/dependency-graph/simulator/simulator').Simulator} Simulator */ /** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ -const Audit = require('../audit.js'); -const ThirdParty = require('../../lib/third-party-web.js'); -const URL = require('../../lib/url-shim.js'); -const ByteEfficiencyAudit = require('../byte-efficiency/byte-efficiency-audit.js'); -const Interactive = require('../../computed/metrics/lantern-interactive.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const NetworkRecords = require('../../computed/network-records.js'); -const LoadSimulator = require('../../computed/load-simulator.js'); -const PageDependencyGraph = require('../../computed/page-dependency-graph.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; + +import ThirdParty from '../../lib/third-party-web.js'; +import URL from '../../lib/url-shim.js'; +import {ByteEfficiencyAudit} from '../byte-efficiency/byte-efficiency-audit.js'; +import Interactive from '../../computed/metrics/lantern-interactive.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import NetworkRecords from '../../computed/network-records.js'; +import LoadSimulator from '../../computed/load-simulator.js'; +import PageDependencyGraph from '../../computed/page-dependency-graph.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to enable HTTP/2. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -39,7 +40,7 @@ const UIStrings = { columnProtocol: 'Protocol', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @type {Set<LH.Artifacts.NetworkRequest['resourceType']>} */ const STATIC_RESOURCE_TYPES = new Set([ @@ -255,5 +256,5 @@ class UsesHTTP2Audit extends Audit { } } -module.exports = UsesHTTP2Audit; -module.exports.UIStrings = UIStrings; +export default UsesHTTP2Audit; +export {UIStrings}; diff --git a/lighthouse-core/audits/dobetterweb/uses-passive-event-listeners.js b/lighthouse-core/audits/dobetterweb/uses-passive-event-listeners.js index db33a7a90c3e..75c58eec5bb1 100644 --- a/lighthouse-core/audits/dobetterweb/uses-passive-event-listeners.js +++ b/lighthouse-core/audits/dobetterweb/uses-passive-event-listeners.js @@ -11,8 +11,8 @@ 'use strict'; -const ViolationAudit = require('../violation-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import ViolationAudit from '../violation-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the page's use of passive event listeners used to improve the scrolling performance of the page. This descriptive title is shown to users when the page does use passive listeners. */ @@ -25,7 +25,7 @@ const UIStrings = { '[Learn more](https://web.dev/uses-passive-event-listeners/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class PassiveEventsAudit extends ViolationAudit { /** @@ -64,5 +64,5 @@ class PassiveEventsAudit extends ViolationAudit { } } -module.exports = PassiveEventsAudit; -module.exports.UIStrings = UIStrings; +export default PassiveEventsAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/errors-in-console.js b/lighthouse-core/audits/errors-in-console.js index a1ed54d507ea..f1a9930de966 100644 --- a/lighthouse-core/audits/errors-in-console.js +++ b/lighthouse-core/audits/errors-in-console.js @@ -10,10 +10,11 @@ * This is done by collecting Chrome console log messages and filtering out the non-error ones. */ -const log = require('lighthouse-logger'); -const Audit = require('./audit.js'); -const JsBundles = require('../computed/js-bundles.js'); -const i18n = require('../lib/i18n/i18n.js'); +import log from 'lighthouse-logger'; + +import {Audit} from './audit.js'; +import JsBundles from '../computed/js-bundles.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on browser errors. This descriptive title is shown to users when no browser errors were logged into the devtools console. */ @@ -26,7 +27,7 @@ const UIStrings = { '[Learn more](https://web.dev/errors-in-console/)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @typedef {{ignoredPatterns?: Array<RegExp|string>}} AuditOptions */ @@ -114,5 +115,5 @@ class ErrorLogs extends Audit { } } -module.exports = ErrorLogs; -module.exports.UIStrings = UIStrings; +export default ErrorLogs; +export {UIStrings}; diff --git a/lighthouse-core/audits/final-screenshot.js b/lighthouse-core/audits/final-screenshot.js index c67db3052580..16c2928c616b 100644 --- a/lighthouse-core/audits/final-screenshot.js +++ b/lighthouse-core/audits/final-screenshot.js @@ -5,10 +5,10 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const LighthouseError = require('../lib/lh-error.js'); -const ProcessedTrace = require('../computed/processed-trace.js'); -const Screenshots = require('../computed/screenshots.js'); +import {Audit} from './audit.js'; +import {LighthouseError} from '../lib/lh-error.js'; +import ProcessedTrace from '../computed/processed-trace.js'; +import Screenshots from '../computed/screenshots.js'; class FinalScreenshot extends Audit { /** @@ -56,4 +56,4 @@ class FinalScreenshot extends Audit { } } -module.exports = FinalScreenshot; +export default FinalScreenshot; diff --git a/lighthouse-core/audits/font-display.js b/lighthouse-core/audits/font-display.js index 769f94e8b5d3..441bb2e21368 100644 --- a/lighthouse-core/audits/font-display.js +++ b/lighthouse-core/audits/font-display.js @@ -5,14 +5,14 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const URL = require('../lib/url-shim.js'); +import {Audit} from './audit.js'; +import URL from '../lib/url-shim.js'; const PASSING_FONT_DISPLAY_REGEX = /^(block|fallback|optional|swap)$/; const CSS_URL_REGEX = /url\((.*?)\)/; const CSS_URL_GLOBAL_REGEX = new RegExp(CSS_URL_REGEX, 'g'); -const i18n = require('../lib/i18n/i18n.js'); -const Sentry = require('../lib/sentry.js'); -const NetworkRecords = require('../computed/network-records.js'); +import * as i18n from '../lib/i18n/i18n.js'; +import {Sentry} from '../lib/sentry.js'; +import NetworkRecords from '../computed/network-records.js'; const UIStrings = { /** Title of a diagnostic audit that provides detail on if all the text on a webpage was visible while the page was loading its webfonts. This descriptive title is shown to users when the amount is acceptable and no user action is required. */ @@ -36,7 +36,7 @@ const UIStrings = { 'other {Lighthouse was unable to automatically check the `font-display` values for the origin {fontOrigin}.}}', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class FontDisplay extends Audit { /** @@ -189,5 +189,5 @@ class FontDisplay extends Audit { } } -module.exports = FontDisplay; -module.exports.UIStrings = UIStrings; +export default FontDisplay; +export {UIStrings}; diff --git a/lighthouse-core/audits/full-page-screenshot.js b/lighthouse-core/audits/full-page-screenshot.js index 29e3252e246a..ba748ac55f8c 100644 --- a/lighthouse-core/audits/full-page-screenshot.js +++ b/lighthouse-core/audits/full-page-screenshot.js @@ -5,7 +5,7 @@ */ 'use strict'; -const Audit = require('./audit.js'); +import {Audit} from './audit.js'; class FullPageScreenshot extends Audit { /** @@ -40,4 +40,4 @@ class FullPageScreenshot extends Audit { } } -module.exports = FullPageScreenshot; +export default FullPageScreenshot; diff --git a/lighthouse-core/audits/image-aspect-ratio.js b/lighthouse-core/audits/image-aspect-ratio.js index b81c95cceb9f..1a0e849a84e1 100644 --- a/lighthouse-core/audits/image-aspect-ratio.js +++ b/lighthouse-core/audits/image-aspect-ratio.js @@ -11,9 +11,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const URL = require('../lib/url-shim.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import URL from '../lib/url-shim.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the aspect ratios of all images on the page. This descriptive title is shown to users when all images use correct aspect ratios. */ @@ -29,7 +29,7 @@ const UIStrings = { columnActual: 'Aspect Ratio (Actual)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const THRESHOLD_PX = 2; @@ -118,5 +118,5 @@ class ImageAspectRatio extends Audit { } } -module.exports = ImageAspectRatio; -module.exports.UIStrings = UIStrings; +export default ImageAspectRatio; +export {UIStrings}; diff --git a/lighthouse-core/audits/image-size-responsive.js b/lighthouse-core/audits/image-size-responsive.js index ec4ff234f523..d0ea4d920e08 100644 --- a/lighthouse-core/audits/image-size-responsive.js +++ b/lighthouse-core/audits/image-size-responsive.js @@ -10,9 +10,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const URL = require('../lib/url-shim.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import URL from '../lib/url-shim.js'; +import * as i18n from '../lib/i18n/i18n.js'; /** @typedef {LH.Artifacts.ImageElement & Required<Pick<LH.Artifacts.ImageElement, 'naturalDimensions'>>} ImageWithNaturalDimensions */ @@ -32,7 +32,7 @@ const UIStrings = { columnExpected: 'Expected size', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // Factors used to allow for smaller effective density. // A factor of 1 means the actual device pixel density will be used. @@ -327,5 +327,5 @@ function quantizeDpr(dpr) { return 1.0; } -module.exports = ImageSizeResponsive; -module.exports.UIStrings = UIStrings; +export default ImageSizeResponsive; +export {UIStrings}; diff --git a/lighthouse-core/audits/installable-manifest.js b/lighthouse-core/audits/installable-manifest.js index 271785454d19..b17a041d33a3 100644 --- a/lighthouse-core/audits/installable-manifest.js +++ b/lighthouse-core/audits/installable-manifest.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const ManifestValues = require('../computed/manifest-values.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import ManifestValues from '../computed/manifest-values.js'; /* eslint-disable max-len */ const UIStrings = { @@ -105,7 +105,7 @@ const UIStrings = { }; /* eslint-enable max-len */ -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview @@ -262,5 +262,5 @@ class InstallableManifest extends Audit { } } -module.exports = InstallableManifest; -module.exports.UIStrings = UIStrings; +export default InstallableManifest; +export {UIStrings}; diff --git a/lighthouse-core/audits/is-on-https.js b/lighthouse-core/audits/is-on-https.js index 9cddce28d3ca..5c33a121844a 100644 --- a/lighthouse-core/audits/is-on-https.js +++ b/lighthouse-core/audits/is-on-https.js @@ -5,11 +5,11 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const URL = require('../lib/url-shim.js'); -const NetworkRequest = require('../lib/network-request.js'); -const NetworkRecords = require('../computed/network-records.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import URL from '../lib/url-shim.js'; +import {NetworkRequest} from '../lib/network-request.js'; +import NetworkRecords from '../computed/network-records.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the useage of HTTPS on a page. This descriptive title is shown to users when all requests on a page are fufilled using HTTPS. */ @@ -49,7 +49,7 @@ const resolutionToString = { MixedContentWarning: UIStrings.warning, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class HTTPS extends Audit { @@ -121,5 +121,5 @@ class HTTPS extends Audit { } } -module.exports = HTTPS; -module.exports.UIStrings = UIStrings; +export default HTTPS; +export {UIStrings}; diff --git a/lighthouse-core/audits/largest-contentful-paint-element.js b/lighthouse-core/audits/largest-contentful-paint-element.js index 159c2853d820..070985a77449 100644 --- a/lighthouse-core/audits/largest-contentful-paint-element.js +++ b/lighthouse-core/audits/largest-contentful-paint-element.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Descriptive title of a diagnostic audit that provides the element that was determined to be the Largest Contentful Paint. */ @@ -16,7 +16,7 @@ const UIStrings = { '[Learn More](https://web.dev/lighthouse-largest-contentful-paint/)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class LargestContentfulPaintElement extends Audit { /** @@ -66,5 +66,5 @@ class LargestContentfulPaintElement extends Audit { } } -module.exports = LargestContentfulPaintElement; -module.exports.UIStrings = UIStrings; +export default LargestContentfulPaintElement; +export {UIStrings}; diff --git a/lighthouse-core/audits/layout-shift-elements.js b/lighthouse-core/audits/layout-shift-elements.js index 6d3f4f9bde5b..094223b24c05 100644 --- a/lighthouse-core/audits/layout-shift-elements.js +++ b/lighthouse-core/audits/layout-shift-elements.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Descriptive title of a diagnostic audit that provides up to the top five elements contributing to Cumulative Layout Shift. */ @@ -17,7 +17,7 @@ const UIStrings = { columnContribution: 'CLS Contribution', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class LayoutShiftElements extends Audit { /** @@ -71,5 +71,5 @@ class LayoutShiftElements extends Audit { } } -module.exports = LayoutShiftElements; -module.exports.UIStrings = UIStrings; +export default LayoutShiftElements; +export {UIStrings}; diff --git a/lighthouse-core/audits/lcp-lazy-loaded.js b/lighthouse-core/audits/lcp-lazy-loaded.js index f9d75c889b30..deb162ee550e 100644 --- a/lighthouse-core/audits/lcp-lazy-loaded.js +++ b/lighthouse-core/audits/lcp-lazy-loaded.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on whether the largest above-the-fold image was loaded with sufficient priority. This descriptive title is shown to users when the image was loaded properly. */ @@ -17,7 +17,7 @@ const UIStrings = { description: 'Above-the-fold images that are lazily loaded render later in the page lifecycle, which can delay the largest contentful paint. [Learn more](https://web.dev/lcp-lazy-loading/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class LargestContentfulPaintLazyLoaded extends Audit { /** @@ -80,5 +80,5 @@ class LargestContentfulPaintLazyLoaded extends Audit { } } -module.exports = LargestContentfulPaintLazyLoaded; -module.exports.UIStrings = UIStrings; +export default LargestContentfulPaintLazyLoaded; +export {UIStrings}; diff --git a/lighthouse-core/audits/long-tasks.js b/lighthouse-core/audits/long-tasks.js index 0f46ac87487a..cdd013cf5b11 100644 --- a/lighthouse-core/audits/long-tasks.js +++ b/lighthouse-core/audits/long-tasks.js @@ -5,13 +5,13 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const NetworkRecords = require('../computed/network-records.js'); -const i18n = require('../lib/i18n/i18n.js'); -const MainThreadTasks = require('../computed/main-thread-tasks.js'); -const PageDependencyGraph = require('../computed/page-dependency-graph.js'); -const LoadSimulator = require('../computed/load-simulator.js'); -const {getJavaScriptURLs, getAttributableURLForTask} = require('../lib/tracehouse/task-summary.js'); +import {Audit} from './audit.js'; +import NetworkRecords from '../computed/network-records.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import MainThreadTasks from '../computed/main-thread-tasks.js'; +import PageDependencyGraph from '../computed/page-dependency-graph.js'; +import LoadSimulator from '../computed/load-simulator.js'; +import {getJavaScriptURLs, getAttributableURLForTask} from '../lib/tracehouse/task-summary.js'; /** We don't always have timing data for short tasks, if we're missing timing data. Treat it as though it were 0ms. */ const DEFAULT_TIMING = {startTime: 0, endTime: 0, duration: 0}; @@ -30,7 +30,7 @@ const UIStrings = { }`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class LongTasks extends Audit { /** @@ -121,5 +121,5 @@ class LongTasks extends Audit { } } -module.exports = LongTasks; -module.exports.UIStrings = UIStrings; +export default LongTasks; +export {UIStrings}; diff --git a/lighthouse-core/audits/main-thread-tasks.js b/lighthouse-core/audits/main-thread-tasks.js index 5d90dd333206..001f5dfe78b8 100644 --- a/lighthouse-core/audits/main-thread-tasks.js +++ b/lighthouse-core/audits/main-thread-tasks.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const MainThreadTasksComputed = require('../computed/main-thread-tasks.js'); +import {Audit} from './audit.js'; +import MainThreadTasksComputed from '../computed/main-thread-tasks.js'; class MainThreadTasks extends Audit { /** @@ -56,4 +56,4 @@ class MainThreadTasks extends Audit { } } -module.exports = MainThreadTasks; +export default MainThreadTasks; diff --git a/lighthouse-core/audits/mainthread-work-breakdown.js b/lighthouse-core/audits/mainthread-work-breakdown.js index 159cd7151c7f..eb91caa18e9d 100644 --- a/lighthouse-core/audits/mainthread-work-breakdown.js +++ b/lighthouse-core/audits/mainthread-work-breakdown.js @@ -10,10 +10,10 @@ 'use strict'; -const Audit = require('./audit.js'); -const {taskGroups} = require('../lib/tracehouse/task-groups.js'); -const i18n = require('../lib/i18n/i18n.js'); -const MainThreadTasks = require('../computed/main-thread-tasks.js'); +import {Audit} from './audit.js'; +import {taskGroups} from '../lib/tracehouse/task-groups.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import MainThreadTasks from '../computed/main-thread-tasks.js'; const UIStrings = { /** Title of a diagnostic audit that provides detail on the main thread work the browser did to load the page. This descriptive title is shown to users when the amount is acceptable and no user action is required. */ @@ -28,7 +28,7 @@ const UIStrings = { columnCategory: 'Category', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @typedef {import('../lib/tracehouse/task-groups.js').TaskGroupIds} TaskGroupIds */ @@ -130,5 +130,5 @@ class MainThreadWorkBreakdown extends Audit { } } -module.exports = MainThreadWorkBreakdown; -module.exports.UIStrings = UIStrings; +export default MainThreadWorkBreakdown; +export {UIStrings}; diff --git a/lighthouse-core/audits/manual/manual-audit.js b/lighthouse-core/audits/manual/manual-audit.js index 6eaf37b5e62f..a52f8fe94ba7 100644 --- a/lighthouse-core/audits/manual/manual-audit.js +++ b/lighthouse-core/audits/manual/manual-audit.js @@ -10,7 +10,7 @@ * their site. */ -const Audit = require('../audit.js'); +import {Audit} from '../audit.js'; class ManualAudit extends Audit { /** @@ -34,4 +34,4 @@ class ManualAudit extends Audit { } } -module.exports = ManualAudit; +export default ManualAudit; diff --git a/lighthouse-core/audits/manual/pwa-cross-browser.js b/lighthouse-core/audits/manual/pwa-cross-browser.js index 82f79379a4cd..67e23a367c31 100644 --- a/lighthouse-core/audits/manual/pwa-cross-browser.js +++ b/lighthouse-core/audits/manual/pwa-cross-browser.js @@ -6,8 +6,8 @@ */ 'use strict'; -const ManualAudit = require('./manual-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import ManualAudit from './manual-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that prompts the user to manually check that their site works across different web browsers. */ @@ -17,7 +17,7 @@ const UIStrings = { 'every major browser. [Learn more](https://web.dev/pwa-cross-browser/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview Manual PWA audit for cross browser support. @@ -36,6 +36,6 @@ class PWACrossBrowser extends ManualAudit { } } -module.exports = PWACrossBrowser; -module.exports.UIStrings = UIStrings; +export default PWACrossBrowser; +export {UIStrings}; diff --git a/lighthouse-core/audits/manual/pwa-each-page-has-url.js b/lighthouse-core/audits/manual/pwa-each-page-has-url.js index 29ac16a0bafc..543e72aa014b 100644 --- a/lighthouse-core/audits/manual/pwa-each-page-has-url.js +++ b/lighthouse-core/audits/manual/pwa-each-page-has-url.js @@ -5,8 +5,8 @@ */ 'use strict'; -const ManualAudit = require('./manual-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import ManualAudit from './manual-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that prompts the user to manually check that each page on their website uses a unique URL. */ @@ -16,7 +16,7 @@ const UIStrings = { 'unique for the purpose of shareability on social media. [Learn more](https://web.dev/pwa-each-page-has-url/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview Manual PWA audit to ensure every page has a deep link. @@ -35,5 +35,5 @@ class PWAEachPageHasURL extends ManualAudit { } } -module.exports = PWAEachPageHasURL; -module.exports.UIStrings = UIStrings; +export default PWAEachPageHasURL; +export {UIStrings}; diff --git a/lighthouse-core/audits/manual/pwa-page-transitions.js b/lighthouse-core/audits/manual/pwa-page-transitions.js index 6906d0e73075..90c78b823543 100644 --- a/lighthouse-core/audits/manual/pwa-page-transitions.js +++ b/lighthouse-core/audits/manual/pwa-page-transitions.js @@ -5,8 +5,8 @@ */ 'use strict'; -const ManualAudit = require('./manual-audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import ManualAudit from './manual-audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that prompts the user to manually check that page transitions (navigating to other pages on a website) shouldn't feel like they are waiting for the network to load. */ @@ -16,7 +16,7 @@ const UIStrings = { 'This experience is key to a user\'s perception of performance. [Learn more](https://web.dev/pwa-page-transitions/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview Manual PWA audit for janky-free page transitions. @@ -35,5 +35,5 @@ class PWAPageTransitions extends ManualAudit { } } -module.exports = PWAPageTransitions; -module.exports.UIStrings = UIStrings; +export default PWAPageTransitions; +export {UIStrings}; diff --git a/lighthouse-core/audits/maskable-icon.js b/lighthouse-core/audits/maskable-icon.js index 2657d9981001..e50ae5f0b0d2 100644 --- a/lighthouse-core/audits/maskable-icon.js +++ b/lighthouse-core/audits/maskable-icon.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const ManifestValues = require('../computed/manifest-values.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import ManifestValues from '../computed/manifest-values.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on if the manifest contains a maskable icon. This descriptive title is shown to users when the manifest contains at least one maskable icon. */ @@ -20,7 +20,7 @@ const UIStrings = { 'the app on a device. [Learn more](https://web.dev/maskable-icon-audit/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview @@ -67,5 +67,5 @@ class MaskableIcon extends Audit { } } -module.exports = MaskableIcon; -module.exports.UIStrings = UIStrings; +export default MaskableIcon; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics.js b/lighthouse-core/audits/metrics.js index 79c444f3ca24..7d8e8ee4a152 100644 --- a/lighthouse-core/audits/metrics.js +++ b/lighthouse-core/audits/metrics.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const ComputedTimingSummary = require('../computed/metrics/timing-summary.js'); +import {Audit} from './audit.js'; +import ComputedTimingSummary from '../computed/metrics/timing-summary.js'; /** @type {Set<keyof LH.Artifacts.TimingSummary>} */ const DECIMAL_METRIC_KEYS = new Set([ @@ -71,4 +71,4 @@ class Metrics extends Audit { } } -module.exports = Metrics; +export default Metrics; diff --git a/lighthouse-core/audits/metrics/cumulative-layout-shift.js b/lighthouse-core/audits/metrics/cumulative-layout-shift.js index eb97cc531066..1bdb58029687 100644 --- a/lighthouse-core/audits/metrics/cumulative-layout-shift.js +++ b/lighthouse-core/audits/metrics/cumulative-layout-shift.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const ComputedCLS = require('../../computed/metrics/cumulative-layout-shift.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import ComputedCLS from '../../computed/metrics/cumulative-layout-shift.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Description of the Cumulative Layout Shift metric that indicates how much the page changes its layout while it loads. If big segments of the page shift their location during load, the Cumulative Layout Shift will be higher. This description is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { 'elements within the viewport. [Learn more](https://web.dev/cls/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview This metric represents the amount of visual shifting of DOM elements during page load. @@ -75,5 +75,5 @@ class CumulativeLayoutShift extends Audit { } } -module.exports = CumulativeLayoutShift; -module.exports.UIStrings = UIStrings; +export default CumulativeLayoutShift; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics/experimental-interaction-to-next-paint.js b/lighthouse-core/audits/metrics/experimental-interaction-to-next-paint.js index 7ff420ce45d1..374e279528cd 100644 --- a/lighthouse-core/audits/metrics/experimental-interaction-to-next-paint.js +++ b/lighthouse-core/audits/metrics/experimental-interaction-to-next-paint.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const ComputedResponsivenes = require('../../computed/metrics/responsiveness.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import ComputedResponsivenes from '../../computed/metrics/responsiveness.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Description of the Interaction to Next Paint metric. This description is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { 'takes the page to visibly respond to user input. [Learn more](https://web.dev/inp/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview This metric gives a high-percentile measure of responsiveness to input. @@ -84,5 +84,5 @@ class ExperimentalInteractionToNextPaint extends Audit { } } -module.exports = ExperimentalInteractionToNextPaint; -module.exports.UIStrings = UIStrings; +export default ExperimentalInteractionToNextPaint; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics/first-contentful-paint-3g.js b/lighthouse-core/audits/metrics/first-contentful-paint-3g.js index 3df6362a12e1..4ca7f3447cf9 100644 --- a/lighthouse-core/audits/metrics/first-contentful-paint-3g.js +++ b/lighthouse-core/audits/metrics/first-contentful-paint-3g.js @@ -5,9 +5,11 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const regular3G = require('../../config/constants.js').throttling.mobileRegular3G; -const ComputedFcp = require('../../computed/metrics/first-contentful-paint.js'); +import {Audit} from '../audit.js'; +import ComputedFcp from '../../computed/metrics/first-contentful-paint.js'; +import * as constants from '../../config/constants.js'; + +const regular3G = constants.throttling.mobileRegular3G; class FirstContentfulPaint3G extends Audit { /** @@ -64,4 +66,4 @@ class FirstContentfulPaint3G extends Audit { } } -module.exports = FirstContentfulPaint3G; +export default FirstContentfulPaint3G; diff --git a/lighthouse-core/audits/metrics/first-contentful-paint.js b/lighthouse-core/audits/metrics/first-contentful-paint.js index fb5823fad971..15485637154b 100644 --- a/lighthouse-core/audits/metrics/first-contentful-paint.js +++ b/lighthouse-core/audits/metrics/first-contentful-paint.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const ComputedFcp = require('../../computed/metrics/first-contentful-paint.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import ComputedFcp from '../../computed/metrics/first-contentful-paint.js'; const UIStrings = { /** Description of the First Contentful Paint (FCP) metric, which marks the time at which the first text or image is painted by the browser. This is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { `painted. [Learn more](https://web.dev/first-contentful-paint/).`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class FirstContentfulPaint extends Audit { /** @@ -82,5 +82,5 @@ class FirstContentfulPaint extends Audit { } } -module.exports = FirstContentfulPaint; -module.exports.UIStrings = UIStrings; +export default FirstContentfulPaint; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics/first-meaningful-paint.js b/lighthouse-core/audits/metrics/first-meaningful-paint.js index 80789c9cbdc0..dfd496ea3ffb 100644 --- a/lighthouse-core/audits/metrics/first-meaningful-paint.js +++ b/lighthouse-core/audits/metrics/first-meaningful-paint.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const ComputedFmp = require('../../computed/metrics/first-meaningful-paint.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import ComputedFmp from '../../computed/metrics/first-meaningful-paint.js'; const UIStrings = { /** Description of the First Meaningful Paint (FMP) metric, which marks the time at which a majority of the content has been painted by the browser. This is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { 'visible. [Learn more](https://web.dev/first-meaningful-paint/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class FirstMeaningfulPaint extends Audit { /** @@ -86,5 +86,5 @@ class FirstMeaningfulPaint extends Audit { } } -module.exports = FirstMeaningfulPaint; -module.exports.UIStrings = UIStrings; +export default FirstMeaningfulPaint; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics/interactive.js b/lighthouse-core/audits/metrics/interactive.js index 989f8c2e44c2..2852ddf6e5a1 100644 --- a/lighthouse-core/audits/metrics/interactive.js +++ b/lighthouse-core/audits/metrics/interactive.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const Interactive = require('../../computed/metrics/interactive.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import Interactive from '../../computed/metrics/interactive.js'; const UIStrings = { /** Description of the Time to Interactive (TTI) metric, which evaluates when a page has completed its primary network activity and main thread work. This is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { 'interactive. [Learn more](https://web.dev/interactive/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview This audit identifies the time the page is "consistently interactive". @@ -90,5 +90,5 @@ class InteractiveMetric extends Audit { } } -module.exports = InteractiveMetric; -module.exports.UIStrings = UIStrings; +export default InteractiveMetric; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics/largest-contentful-paint.js b/lighthouse-core/audits/metrics/largest-contentful-paint.js index 3dff8f71a999..6e9bec2458da 100644 --- a/lighthouse-core/audits/metrics/largest-contentful-paint.js +++ b/lighthouse-core/audits/metrics/largest-contentful-paint.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const ComputedLcp = require('../../computed/metrics/largest-contentful-paint.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import ComputedLcp from '../../computed/metrics/largest-contentful-paint.js'; const UIStrings = { /** Description of the Largest Contentful Paint (LCP) metric, which marks the time at which the largest text or image is painted by the browser. This is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { `painted. [Learn more](https://web.dev/lighthouse-largest-contentful-paint/)`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class LargestContentfulPaint extends Audit { /** @@ -91,5 +91,5 @@ class LargestContentfulPaint extends Audit { } } -module.exports = LargestContentfulPaint; -module.exports.UIStrings = UIStrings; +export default LargestContentfulPaint; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics/max-potential-fid.js b/lighthouse-core/audits/metrics/max-potential-fid.js index 464a073e5060..85fc268a8d65 100644 --- a/lighthouse-core/audits/metrics/max-potential-fid.js +++ b/lighthouse-core/audits/metrics/max-potential-fid.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const ComputedFid = require('../../computed/metrics/max-potential-fid.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import ComputedFid from '../../computed/metrics/max-potential-fid.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Description of the Maximum Potential First Input Delay metric that marks the maximum estimated time between the page receiving input (a user clicking, tapping, or typing) and the page responding. This description is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { 'duration of the longest task. [Learn more](https://web.dev/lighthouse-max-potential-fid/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview This metric is the duration of the longest task after FCP. It is meant to capture @@ -73,5 +73,5 @@ class MaxPotentialFID extends Audit { } } -module.exports = MaxPotentialFID; -module.exports.UIStrings = UIStrings; +export default MaxPotentialFID; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics/speed-index.js b/lighthouse-core/audits/metrics/speed-index.js index 884bd53e7dce..5b95618be2e1 100644 --- a/lighthouse-core/audits/metrics/speed-index.js +++ b/lighthouse-core/audits/metrics/speed-index.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const ComputedSi = require('../../computed/metrics/speed-index.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import ComputedSi from '../../computed/metrics/speed-index.js'; const UIStrings = { /** Description of the Speed Index metric, which summarizes how quickly the page looked visually complete. This is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { '[Learn more](https://web.dev/speed-index/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class SpeedIndex extends Audit { /** @@ -85,5 +85,5 @@ class SpeedIndex extends Audit { } } -module.exports = SpeedIndex; -module.exports.UIStrings = UIStrings; +export default SpeedIndex; +export {UIStrings}; diff --git a/lighthouse-core/audits/metrics/total-blocking-time.js b/lighthouse-core/audits/metrics/total-blocking-time.js index 77843ac00454..8c004638c0fd 100644 --- a/lighthouse-core/audits/metrics/total-blocking-time.js +++ b/lighthouse-core/audits/metrics/total-blocking-time.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const ComputedTBT = require('../../computed/metrics/total-blocking-time.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import ComputedTBT from '../../computed/metrics/total-blocking-time.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Description of the Total Blocking Time (TBT) metric, which calculates the total duration of blocking time for a web page. Blocking times are time periods when the page would be blocked (prevented) from responding to user input (clicks, taps, and keypresses will feel slow to respond). This is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits.*/ @@ -15,7 +15,7 @@ const UIStrings = { 'when task length exceeded 50ms, expressed in milliseconds. [Learn more](https://web.dev/lighthouse-total-blocking-time/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class TotalBlockingTime extends Audit { /** @@ -114,5 +114,5 @@ class TotalBlockingTime extends Audit { } } -module.exports = TotalBlockingTime; -module.exports.UIStrings = UIStrings; +export default TotalBlockingTime; +export {UIStrings}; diff --git a/lighthouse-core/audits/multi-check-audit.js b/lighthouse-core/audits/multi-check-audit.js index d6eea7f97b87..6b2203ed7564 100644 --- a/lighthouse-core/audits/multi-check-audit.js +++ b/lighthouse-core/audits/multi-check-audit.js @@ -9,7 +9,7 @@ * @fileoverview Base class for boolean audits that can have multiple reasons for failure */ -const Audit = require('./audit.js'); +import {Audit} from './audit.js'; class MultiCheckAudit extends Audit { /** @@ -80,4 +80,4 @@ class MultiCheckAudit extends Audit { /* eslint-enable no-unused-vars */ } -module.exports = MultiCheckAudit; +export default MultiCheckAudit; diff --git a/lighthouse-core/audits/network-requests.js b/lighthouse-core/audits/network-requests.js index 95a94a6ce51f..7074e4cc87e6 100644 --- a/lighthouse-core/audits/network-requests.js +++ b/lighthouse-core/audits/network-requests.js @@ -5,10 +5,10 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const URL = require('../lib/url-shim.js'); -const NetworkRecords = require('../computed/network-records.js'); -const MainResource = require('../computed/main-resource.js'); +import {Audit} from './audit.js'; +import URL from '../lib/url-shim.js'; +import NetworkRecords from '../computed/network-records.js'; +import MainResource from '../computed/main-resource.js'; class NetworkRequests extends Audit { /** @@ -117,4 +117,4 @@ class NetworkRequests extends Audit { } } -module.exports = NetworkRequests; +export default NetworkRequests; diff --git a/lighthouse-core/audits/network-rtt.js b/lighthouse-core/audits/network-rtt.js index 3b35357b1908..aa799b08716b 100644 --- a/lighthouse-core/audits/network-rtt.js +++ b/lighthouse-core/audits/network-rtt.js @@ -5,10 +5,10 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const NetworkRecords = require('../computed/network-records.js'); -const NetworkAnalysisComputed = require('../computed/network-analysis.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import NetworkRecords from '../computed/network-records.js'; +import NetworkAnalysisComputed from '../computed/network-analysis.js'; const UIStrings = { /** Descriptive title of a Lighthouse audit that tells the user the round trip times to each origin the page connected to. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -19,7 +19,7 @@ const UIStrings = { 'improve performance. [Learn more](https://hpbn.co/primer-on-latency-and-bandwidth/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class NetworkRTT extends Audit { /** @@ -86,5 +86,5 @@ class NetworkRTT extends Audit { } } -module.exports = NetworkRTT; -module.exports.UIStrings = UIStrings; +export default NetworkRTT; +export {UIStrings}; diff --git a/lighthouse-core/audits/network-server-latency.js b/lighthouse-core/audits/network-server-latency.js index f7a849778a3a..25456c2feba8 100644 --- a/lighthouse-core/audits/network-server-latency.js +++ b/lighthouse-core/audits/network-server-latency.js @@ -5,10 +5,10 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const NetworkRecords = require('../computed/network-records.js'); -const NetworkAnalysisComputed = require('../computed/network-analysis.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import NetworkRecords from '../computed/network-records.js'; +import NetworkAnalysisComputed from '../computed/network-analysis.js'; const UIStrings = { /** Descriptive title of a Lighthouse audit that tells the user the server latencies observed from each origin the page connected to. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -19,7 +19,7 @@ const UIStrings = { 'or has poor backend performance. [Learn more](https://hpbn.co/primer-on-web-performance/#analyzing-the-resource-waterfall).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class NetworkServerLatency extends Audit { /** @@ -85,5 +85,5 @@ class NetworkServerLatency extends Audit { } } -module.exports = NetworkServerLatency; -module.exports.UIStrings = UIStrings; +export default NetworkServerLatency; +export {UIStrings}; diff --git a/lighthouse-core/audits/no-unload-listeners.js b/lighthouse-core/audits/no-unload-listeners.js index a93c885801d6..65001aa91697 100644 --- a/lighthouse-core/audits/no-unload-listeners.js +++ b/lighthouse-core/audits/no-unload-listeners.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const JsBundles = require('../computed/js-bundles.js'); -const i18n = require('./../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import JsBundles from '../computed/js-bundles.js'; +import * as i18n from './../lib/i18n/i18n.js'; const UIStrings = { /** Descriptive title of a Lighthouse audit that checks if a web page has 'unload' event listeners and finds none. */ @@ -18,7 +18,7 @@ const UIStrings = { description: 'The `unload` event does not fire reliably and listening for it can prevent browser optimizations like the Back-Forward Cache. Use `pagehide` or `visibilitychange` events instead. [Learn more](https://web.dev/bfcache/#never-use-the-unload-event)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class NoUnloadListeners extends Audit { /** @@ -83,5 +83,5 @@ class NoUnloadListeners extends Audit { } } -module.exports = NoUnloadListeners; -module.exports.UIStrings = UIStrings; +export default NoUnloadListeners; +export {UIStrings}; diff --git a/lighthouse-core/audits/non-composited-animations.js b/lighthouse-core/audits/non-composited-animations.js index b0691e4ed273..4da91d054130 100644 --- a/lighthouse-core/audits/non-composited-animations.js +++ b/lighthouse-core/audits/non-composited-animations.js @@ -11,8 +11,9 @@ * https://docs.google.com/document/d/1XKcJP2CKmNKfOcDsVvliAQ-e1H9C1nf2H-pzTdyafAA/edit?usp=sharing */ -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; + +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a diagnostic LH audit that provides details on animations that are not composited. */ @@ -45,7 +46,7 @@ const UIStrings = { unsupportedTimingParameters: 'Effect has unsupported timing parameters', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * Each failure reason is represented by a bit flag. The bit shift operator '<<' is used to define which bit corresponds to each failure reason. @@ -202,5 +203,5 @@ class NonCompositedAnimations extends Audit { } } -module.exports = NonCompositedAnimations; -module.exports.UIStrings = UIStrings; +export default NonCompositedAnimations; +export {UIStrings}; diff --git a/lighthouse-core/audits/oopif-iframe-test-audit.js b/lighthouse-core/audits/oopif-iframe-test-audit.js index 08071aa29078..ed7263cb1ff2 100644 --- a/lighthouse-core/audits/oopif-iframe-test-audit.js +++ b/lighthouse-core/audits/oopif-iframe-test-audit.js @@ -18,7 +18,7 @@ * test-only audit in our core list instead. */ -module.exports = { +export default { meta: { id: 'oopif-iframe-test-audit', title: 'IFrame Elements', diff --git a/lighthouse-core/audits/performance-budget.js b/lighthouse-core/audits/performance-budget.js index e737e78ea887..9038de3a93be 100644 --- a/lighthouse-core/audits/performance-budget.js +++ b/lighthouse-core/audits/performance-budget.js @@ -5,11 +5,11 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const ResourceSummary = require('../computed/resource-summary.js'); -const MainResource = require('../computed/main-resource.js'); -const Budget = require('../config/budget.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import ResourceSummary from '../computed/resource-summary.js'; +import MainResource from '../computed/main-resource.js'; +import {Budget} from '../config/budget.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that compares the size and quantity of page resources against targets set by the user. These targets are thought of as "performance budgets" because these metrics impact page performance (i.e. how quickly a page loads). */ @@ -24,7 +24,7 @@ const UIStrings = { }`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @typedef {import('../computed/resource-summary.js').ResourceEntry} ResourceEntry */ /** @typedef {{resourceType: LH.Budget.ResourceType, label: LH.IcuMessage, requestCount: number, transferSize: number, sizeOverBudget: number | undefined, countOverBudget: LH.IcuMessage | undefined}} BudgetItem */ @@ -150,5 +150,5 @@ class ResourceBudget extends Audit { } } -module.exports = ResourceBudget; -module.exports.UIStrings = UIStrings; +export default ResourceBudget; +export {UIStrings}; diff --git a/lighthouse-core/audits/predictive-perf.js b/lighthouse-core/audits/predictive-perf.js index 1eaa6d562075..3ace4de30df3 100644 --- a/lighthouse-core/audits/predictive-perf.js +++ b/lighthouse-core/audits/predictive-perf.js @@ -5,21 +5,20 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); - -const LanternFcp = require('../computed/metrics/lantern-first-contentful-paint.js'); -const LanternFmp = require('../computed/metrics/lantern-first-meaningful-paint.js'); -const LanternInteractive = require('../computed/metrics/lantern-interactive.js'); -const LanternSpeedIndex = require('../computed/metrics/lantern-speed-index.js'); -const LanternLcp = require('../computed/metrics/lantern-largest-contentful-paint.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import LanternFcp from '../computed/metrics/lantern-first-contentful-paint.js'; +import LanternFmp from '../computed/metrics/lantern-first-meaningful-paint.js'; +import LanternInteractive from '../computed/metrics/lantern-interactive.js'; +import LanternSpeedIndex from '../computed/metrics/lantern-speed-index.js'; +import LanternLcp from '../computed/metrics/lantern-largest-contentful-paint.js'; // Parameters (in ms) for log-normal CDF scoring. To see the curve: // https://www.desmos.com/calculator/bksgkihhj8 const SCORING_P10 = 3651; const SCORING_MEDIAN = 10000; -const str_ = i18n.createMessageInstanceIdFn(__filename, {}); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, {}); class PredictivePerf extends Audit { /** @@ -99,4 +98,4 @@ class PredictivePerf extends Audit { } } -module.exports = PredictivePerf; +export default PredictivePerf; diff --git a/lighthouse-core/audits/preload-fonts.js b/lighthouse-core/audits/preload-fonts.js index 80cad4a712be..8999f52b124d 100644 --- a/lighthouse-core/audits/preload-fonts.js +++ b/lighthouse-core/audits/preload-fonts.js @@ -10,11 +10,12 @@ * Audit that checks whether fonts that use `font-display: optional` were preloaded. */ -const Audit = require('./audit.js'); -const i18n = require('./../lib/i18n/i18n.js'); -const FontDisplay = require('./../audits/font-display.js'); +import {Audit} from './audit.js'; + +import * as i18n from './../lib/i18n/i18n.js'; +import FontDisplay from './../audits/font-display.js'; const PASSING_FONT_DISPLAY_REGEX = /^(optional)$/; -const NetworkRecords = require('../computed/network-records.js'); +import NetworkRecords from '../computed/network-records.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on whether fonts that used `font-display: optional` were preloaded. This descriptive title is shown to users when all fonts that used `font-display: optional` were preloaded. */ @@ -25,7 +26,7 @@ const UIStrings = { description: 'Preload `optional` fonts so first-time visitors may use them. [Learn more](https://web.dev/preload-optional-fonts/)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class PreloadFontsAudit extends Audit { /** @@ -103,5 +104,5 @@ class PreloadFontsAudit extends Audit { } } -module.exports = PreloadFontsAudit; -module.exports.UIStrings = UIStrings; +export default PreloadFontsAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/preload-lcp-image.js b/lighthouse-core/audits/preload-lcp-image.js index 9d7c8631f2ad..236883a55010 100644 --- a/lighthouse-core/audits/preload-lcp-image.js +++ b/lighthouse-core/audits/preload-lcp-image.js @@ -5,13 +5,13 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const NetworkRequest = require('../lib/network-request.js'); -const MainResource = require('../computed/main-resource.js'); -const LanternLCP = require('../computed/metrics/lantern-largest-contentful-paint.js'); -const LoadSimulator = require('../computed/load-simulator.js'); -const UnusedBytes = require('./byte-efficiency/byte-efficiency-audit.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import {NetworkRequest} from '../lib/network-request.js'; +import MainResource from '../computed/main-resource.js'; +import LanternLCP from '../computed/metrics/lantern-largest-contentful-paint.js'; +import LoadSimulator from '../computed/load-simulator.js'; +import {ByteEfficiencyAudit} from './byte-efficiency/byte-efficiency-audit.js'; const UIStrings = { /** Title of a lighthouse audit that tells a user to preload an image in order to improve their LCP time. */ @@ -21,7 +21,7 @@ const UIStrings = { 'image in order to improve LCP. [Learn more](https://web.dev/optimize-lcp/#preload-important-resources).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @typedef {Array<{url: string, initiatorType: string}>} InitiatorPath @@ -255,7 +255,7 @@ class PreloadLCPImageAudit extends Audit { } return { - score: UnusedBytes.scoreForWastedMs(wastedMs), + score: ByteEfficiencyAudit.scoreForWastedMs(wastedMs), numericValue: wastedMs, numericUnit: 'millisecond', displayValue: wastedMs ? str_(i18n.UIStrings.displayValueMsSavings, {wastedMs}) : '', @@ -264,5 +264,5 @@ class PreloadLCPImageAudit extends Audit { } } -module.exports = PreloadLCPImageAudit; -module.exports.UIStrings = UIStrings; +export default PreloadLCPImageAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/redirects.js b/lighthouse-core/audits/redirects.js index a1a75222a485..70fc31bcb52b 100644 --- a/lighthouse-core/audits/redirects.js +++ b/lighthouse-core/audits/redirects.js @@ -5,13 +5,13 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const UnusedBytes = require('./byte-efficiency/byte-efficiency-audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const ProcessedTrace = require('../computed/processed-trace.js'); -const NetworkRecords = require('../computed/network-records.js'); -const MainResource = require('../computed/main-resource.js'); -const LanternInteractive = require('../computed/metrics/lantern-interactive.js'); +import {Audit} from './audit.js'; +import {ByteEfficiencyAudit} from './byte-efficiency/byte-efficiency-audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import ProcessedTrace from '../computed/processed-trace.js'; +import NetworkRecords from '../computed/network-records.js'; +import MainResource from '../computed/main-resource.js'; +import LanternInteractive from '../computed/metrics/lantern-interactive.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to eliminate the redirects taken through multiple URLs to load the page. This is shown in a list of audits that Lighthouse generates. */ @@ -20,7 +20,7 @@ const UIStrings = { description: 'Redirects introduce additional delays before the page can be loaded. [Learn more](https://web.dev/redirects/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class Redirects extends Audit { /** @@ -148,7 +148,7 @@ class Redirects extends Audit { // We award a passing grade if you only have 1 redirect // TODO(phulce): reconsider if cases like the example in https://github.com/GoogleChrome/lighthouse/issues/8984 // should fail this audit. - score: documentRequests.length <= 2 ? 1 : UnusedBytes.scoreForWastedMs(totalWastedMs), + score: documentRequests.length <= 2 ? 1 : ByteEfficiencyAudit.scoreForWastedMs(totalWastedMs), numericValue: totalWastedMs, numericUnit: 'millisecond', displayValue: totalWastedMs ? @@ -159,5 +159,5 @@ class Redirects extends Audit { } } -module.exports = Redirects; -module.exports.UIStrings = UIStrings; +export default Redirects; +export {UIStrings}; diff --git a/lighthouse-core/audits/resource-summary.js b/lighthouse-core/audits/resource-summary.js index 5646b9fe1c63..bf8d48abcd61 100644 --- a/lighthouse-core/audits/resource-summary.js +++ b/lighthouse-core/audits/resource-summary.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const ComputedResourceSummary = require('../computed/resource-summary.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import ComputedResourceSummary from '../computed/resource-summary.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to minimize the size and quantity of resources used to load the page. */ @@ -21,7 +21,7 @@ const UIStrings = { `other {# requests • {byteCount, number, bytes} KiB}}`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ResourceSummary extends Audit { /** @@ -100,5 +100,5 @@ class ResourceSummary extends Audit { } } -module.exports = ResourceSummary; -module.exports.UIStrings = UIStrings; +export default ResourceSummary; +export {UIStrings}; diff --git a/lighthouse-core/audits/screenshot-thumbnails.js b/lighthouse-core/audits/screenshot-thumbnails.js index d3da43d0f72d..d3dc54e99dbf 100644 --- a/lighthouse-core/audits/screenshot-thumbnails.js +++ b/lighthouse-core/audits/screenshot-thumbnails.js @@ -5,10 +5,10 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const LighthouseError = require('../lib/lh-error.js'); -const jpeg = require('jpeg-js'); -const Speedline = require('../computed/speedline.js'); +import {Audit} from './audit.js'; +import {LighthouseError} from '../lib/lh-error.js'; +import jpeg from 'jpeg-js'; +import Speedline from '../computed/speedline.js'; const NUMBER_OF_THUMBNAILS = 10; const THUMBNAIL_WIDTH = 120; @@ -160,4 +160,4 @@ class ScreenshotThumbnails extends Audit { } } -module.exports = ScreenshotThumbnails; +export default ScreenshotThumbnails; diff --git a/lighthouse-core/audits/script-elements-test-audit.js b/lighthouse-core/audits/script-elements-test-audit.js index 2078dca89b9c..b08df7b81701 100644 --- a/lighthouse-core/audits/script-elements-test-audit.js +++ b/lighthouse-core/audits/script-elements-test-audit.js @@ -18,7 +18,7 @@ * test-only audit in our core list instead. */ -module.exports = { +export default { meta: { id: 'script-elements-test-audit', title: 'ScriptElements', diff --git a/lighthouse-core/audits/script-treemap-data.js b/lighthouse-core/audits/script-treemap-data.js index 0e46533a3a97..ae06d5e6268b 100644 --- a/lighthouse-core/audits/script-treemap-data.js +++ b/lighthouse-core/audits/script-treemap-data.js @@ -15,11 +15,12 @@ * @typedef {Omit<LH.Treemap.Node, 'name'|'children'>} SourceData */ -const Audit = require('./audit.js'); -const JsBundles = require('../computed/js-bundles.js'); -const UnusedJavaScriptSummary = require('../computed/unused-javascript-summary.js'); -const ModuleDuplication = require('../computed/module-duplication.js'); -const {isInline} = require('../lib/script-helpers.js'); +import {Audit} from './audit.js'; + +import JsBundles from '../computed/js-bundles.js'; +import UnusedJavaScriptSummary from '../computed/unused-javascript-summary.js'; +import ModuleDuplication from '../computed/module-duplication.js'; +import {isInline} from '../lib/script-helpers.js'; class ScriptTreemapDataAudit extends Audit { /** @@ -285,4 +286,4 @@ class ScriptTreemapDataAudit extends Audit { } } -module.exports = ScriptTreemapDataAudit; +export default ScriptTreemapDataAudit; diff --git a/lighthouse-core/audits/seo/canonical.js b/lighthouse-core/audits/seo/canonical.js index 99aa4bae015c..3eb35452dbfb 100644 --- a/lighthouse-core/audits/seo/canonical.js +++ b/lighthouse-core/audits/seo/canonical.js @@ -5,10 +5,10 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const URL = require('../../lib/url-shim.js'); -const MainResource = require('../../computed/main-resource.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import URL from '../../lib/url-shim.js'; +import MainResource from '../../computed/main-resource.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on a page's rel=canonical link. This descriptive title is shown to users when the rel=canonical link is valid. "rel=canonical" is an HTML attribute and value and so should not be translated. */ @@ -43,7 +43,7 @@ const UIStrings = { 'instead of an equivalent page of content', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @typedef CanonicalURLData @@ -214,5 +214,5 @@ class Canonical extends Audit { } } -module.exports = Canonical; -module.exports.UIStrings = UIStrings; +export default Canonical; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/crawlable-anchors.js b/lighthouse-core/audits/seo/crawlable-anchors.js index 821208300258..9726720cdd9a 100644 --- a/lighthouse-core/audits/seo/crawlable-anchors.js +++ b/lighthouse-core/audits/seo/crawlable-anchors.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on whether links have potentially-crawlable href attributes. This descriptive title is shown when all links on the page are potentially-crawlable. */ @@ -19,7 +19,7 @@ const UIStrings = { columnFailingLink: 'Uncrawlable Link', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class CrawlableAnchors extends Audit { /** @@ -90,5 +90,5 @@ class CrawlableAnchors extends Audit { } } -module.exports = CrawlableAnchors; -module.exports.UIStrings = UIStrings; +export default CrawlableAnchors; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/font-size.js b/lighthouse-core/audits/seo/font-size.js index 0a212c080234..0a4f01d3965a 100644 --- a/lighthouse-core/audits/seo/font-size.js +++ b/lighthouse-core/audits/seo/font-size.js @@ -7,9 +7,11 @@ /** @typedef {LH.Artifacts.FontSize['analyzedFailingNodesData'][0]} FailingNodeData */ -const i18n = require('../../lib/i18n/i18n.js'); -const Audit = require('../audit.js'); -const ComputedViewportMeta = require('../../computed/viewport-meta.js'); +import * as i18n from '../../lib/i18n/i18n.js'; + +import {Audit} from '../audit.js'; +import ComputedViewportMeta from '../../computed/viewport-meta.js'; + const MINIMAL_PERCENTAGE_OF_LEGIBLE_TEXT = 60; const UIStrings = { @@ -36,7 +38,7 @@ const UIStrings = { columnFontSize: 'Font Size', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @param {Array<FailingNodeData>} fontSizeArtifact @@ -340,5 +342,5 @@ class FontSize extends Audit { } } -module.exports = FontSize; -module.exports.UIStrings = UIStrings; +export default FontSize; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/hreflang.js b/lighthouse-core/audits/seo/hreflang.js index 3749560332f1..51162d8ea6b8 100644 --- a/lighthouse-core/audits/seo/hreflang.js +++ b/lighthouse-core/audits/seo/hreflang.js @@ -9,9 +9,10 @@ /** @typedef {{source: Source, subItems: {type: 'subitems', items: SubItem[]}}} InvalidHreflang */ /** @typedef {{reason: LH.IcuMessage}} SubItem */ -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const {isValidLang} = require('../../../third-party/axe/valid-langs.js'); +import {Audit} from '../audit.js'; + +import * as i18n from '../../lib/i18n/i18n.js'; +import {isValidLang} from '../../../third-party/axe/valid-langs.js'; const NO_LANGUAGE = 'x-default'; @@ -30,7 +31,7 @@ const UIStrings = { notFullyQualified: 'Relative href value', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @param {string} href @@ -145,5 +146,5 @@ class Hreflang extends Audit { } } -module.exports = Hreflang; -module.exports.UIStrings = UIStrings; +export default Hreflang; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/http-status-code.js b/lighthouse-core/audits/seo/http-status-code.js index 9814b2bc72a1..f5cef37fc10a 100644 --- a/lighthouse-core/audits/seo/http-status-code.js +++ b/lighthouse-core/audits/seo/http-status-code.js @@ -5,11 +5,12 @@ */ 'use strict'; -const Audit = require('../audit.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import MainResource from '../../computed/main-resource.js'; + const HTTP_UNSUCCESSFUL_CODE_LOW = 400; const HTTP_UNSUCCESSFUL_CODE_HIGH = 599; -const i18n = require('../../lib/i18n/i18n.js'); -const MainResource = require('../../computed/main-resource.js'); const UIStrings = { /** Title of a Lighthouse audit that provides detail on the HTTP status code a page responds with. This descriptive title is shown when the page has responded with a valid HTTP status code. */ @@ -21,7 +22,7 @@ const UIStrings = { '[Learn more](https://web.dev/http-status-code/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class HTTPStatusCode extends Audit { /** @@ -64,5 +65,5 @@ class HTTPStatusCode extends Audit { } } -module.exports = HTTPStatusCode; -module.exports.UIStrings = UIStrings; +export default HTTPStatusCode; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/is-crawlable.js b/lighthouse-core/audits/seo/is-crawlable.js index f356589e9b20..071611871a8a 100644 --- a/lighthouse-core/audits/seo/is-crawlable.js +++ b/lighthouse-core/audits/seo/is-crawlable.js @@ -5,18 +5,20 @@ */ 'use strict'; -const Audit = require('../audit.js'); -// TODO(esmodules): cast can be removed when this switches to import. -const robotsParser = /** @type {typeof import('robots-parser').default} */ (/** @type {unknown} */(require('robots-parser'))); // eslint-disable-line max-len -const URL = require('../../lib/url-shim.js'); -const MainResource = require('../../computed/main-resource.js'); +import {Audit} from '../audit.js'; + +import robotsParser from 'robots-parser'; + +import URL from '../../lib/url-shim.js'; +import MainResource from '../../computed/main-resource.js'; +import * as i18n from '../../lib/i18n/i18n.js'; + const BLOCKLIST = new Set([ 'noindex', 'none', ]); const ROBOTS_HEADER = 'x-robots-tag'; const UNAVAILABLE_AFTER = 'unavailable_after'; -const i18n = require('../../lib/i18n/i18n.js'); const UIStrings = { /** Title of a Lighthouse audit that provides detail on if search-engine crawlers are blocked from indexing the page. This title is shown when the page is not blocked from indexing and can be crawled. */ @@ -28,7 +30,7 @@ const UIStrings = { 'if they don\'t have permission to crawl them. [Learn more](https://web.dev/is-crawable/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * Checks if given directive is a valid unavailable_after directive with a date in the past @@ -151,5 +153,5 @@ class IsCrawlable extends Audit { } } -module.exports = IsCrawlable; -module.exports.UIStrings = UIStrings; +export default IsCrawlable; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/link-text.js b/lighthouse-core/audits/seo/link-text.js index e451035199f9..6bb0fe544578 100644 --- a/lighthouse-core/audits/seo/link-text.js +++ b/lighthouse-core/audits/seo/link-text.js @@ -5,8 +5,10 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const URL = require('../../lib/url-shim.js'); +import {Audit} from '../audit.js'; +import URL from '../../lib/url-shim.js'; +import * as i18n from '../../lib/i18n/i18n.js'; + const BLOCKLIST = new Set([ // English 'click here', @@ -74,7 +76,6 @@ const BLOCKLIST = new Set([ 'mer info', 'mer information', ]); -const i18n = require('../../lib/i18n/i18n.js'); const UIStrings = { /** Title of a Lighthouse audit that tests if each link on a page contains a sufficient description of what a user will find when they click it. Generic, non-descriptive text like "click here" doesn't give an indication of what the link leads to. This descriptive title is shown when all links on the page have sufficient textual descriptions. */ @@ -91,7 +92,7 @@ const UIStrings = { }`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class LinkText extends Audit { /** @@ -156,5 +157,5 @@ class LinkText extends Audit { } } -module.exports = LinkText; -module.exports.UIStrings = UIStrings; +export default LinkText; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/manual/structured-data.js b/lighthouse-core/audits/seo/manual/structured-data.js index d87bfbb09153..f3ad46f6ca4a 100644 --- a/lighthouse-core/audits/seo/manual/structured-data.js +++ b/lighthouse-core/audits/seo/manual/structured-data.js @@ -5,8 +5,8 @@ */ 'use strict'; -const ManualAudit = require('../../manual/manual-audit.js'); -const i18n = require('../../../lib/i18n/i18n.js'); +import ManualAudit from '../../manual/manual-audit.js'; +import * as i18n from '../../../lib/i18n/i18n.js'; const UIStrings = { /** Description of a Lighthouse audit that provides detail on the structured data in a page. "Structured data" is a standardized data format on a page that helps a search engine categorize and understand its contents. This description is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ @@ -15,7 +15,7 @@ const UIStrings = { title: 'Structured data is valid', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview Manual SEO audit to check if structured data on page is valid. @@ -34,5 +34,5 @@ class StructuredData extends ManualAudit { } } -module.exports = StructuredData; -module.exports.UIStrings = UIStrings; +export default StructuredData; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/meta-description.js b/lighthouse-core/audits/seo/meta-description.js index 88d5bfb5eb03..f9339e1b40e5 100644 --- a/lighthouse-core/audits/seo/meta-description.js +++ b/lighthouse-core/audits/seo/meta-description.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the web page's document meta description. This descriptive title is shown when the document has a meta description. "meta" should be left untranslated because it refers to an HTML element. */ @@ -21,7 +21,7 @@ const UIStrings = { explanation: 'Description text is empty.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class Description extends Audit { /** @@ -63,5 +63,5 @@ class Description extends Audit { } } -module.exports = Description; -module.exports.UIStrings = UIStrings; +export default Description; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/plugins.js b/lighthouse-core/audits/seo/plugins.js index 6b2d2c338a92..38969cf9bdc1 100644 --- a/lighthouse-core/audits/seo/plugins.js +++ b/lighthouse-core/audits/seo/plugins.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('../audit.js'); -const URL = require('../../lib/url-shim.js'); +import {Audit} from '../audit.js'; +import URL from '../../lib/url-shim.js'; const JAVA_APPLET_TYPE = 'application/x-java-applet'; const JAVA_BEAN_TYPE = 'application/x-java-bean'; @@ -31,7 +31,7 @@ const SOURCE_PARAMS = new Set([ 'source', 'src', ]); -const i18n = require('../../lib/i18n/i18n.js'); +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the browser plugins used by the page. This descriptive title is shown when there is no plugin content on the page that would restrict search indexing. */ @@ -44,7 +44,7 @@ const UIStrings = { '[Learn more](https://web.dev/plugins/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * Verifies if given MIME type matches any known plugin MIME type @@ -148,5 +148,5 @@ class Plugins extends Audit { } } -module.exports = Plugins; -module.exports.UIStrings = UIStrings; +export default Plugins; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/robots-txt.js b/lighthouse-core/audits/seo/robots-txt.js index 13fecbe49d26..1292c4581b96 100644 --- a/lighthouse-core/audits/seo/robots-txt.js +++ b/lighthouse-core/audits/seo/robots-txt.js @@ -12,8 +12,9 @@ * https://github.com/GoogleChrome/lighthouse/issues/4356#issuecomment-375489925 */ -const Audit = require('../audit.js'); -const URL = require('../../lib/url-shim.js'); +import {Audit} from '../audit.js'; + +import URL from '../../lib/url-shim.js'; const HTTP_CLIENT_ERROR_CODE_LOW = 400; const HTTP_SERVER_ERROR_CODE_LOW = 500; @@ -31,7 +32,7 @@ const DIRECTIVE_SAFELIST = new Set([ 'request-rate', 'visit-time', 'noindex', // not officially supported, but used in the wild ]); const SITEMAP_VALID_PROTOCOLS = new Set(['https:', 'http:', 'ftp:']); -const i18n = require('../../lib/i18n/i18n.js'); +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the site's robots.txt file. Note: "robots.txt" is a canonical filename and should not be translated. This descriptive title is shown when the robots.txt file is present and configured correctly. */ @@ -55,7 +56,7 @@ const UIStrings = { explanation: 'Lighthouse was unable to download a robots.txt file', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @param {string} directiveName @@ -252,5 +253,5 @@ class RobotsTxt extends Audit { } } -module.exports = RobotsTxt; -module.exports.UIStrings = UIStrings; +export default RobotsTxt; +export {UIStrings}; diff --git a/lighthouse-core/audits/seo/tap-targets.js b/lighthouse-core/audits/seo/tap-targets.js index 846d112fb582..c17e53b4b86d 100644 --- a/lighthouse-core/audits/seo/tap-targets.js +++ b/lighthouse-core/audits/seo/tap-targets.js @@ -9,18 +9,21 @@ * @fileoverview Checks that links, buttons, etc. are sufficiently large and that there's * no other tap target that's too close so that the user might accidentally tap on. */ -const Audit = require('../audit.js'); -const ComputedViewportMeta = require('../../computed/viewport-meta.js'); -const { +import {Audit} from '../audit.js'; + +import ComputedViewportMeta from '../../computed/viewport-meta.js'; + +import { rectsTouchOrOverlap, getRectOverlapArea, getRectAtCenter, allRectsContainedWithinEachOther, getLargestRect, getBoundingRectWithPadding, -} = require('../../lib/rect-helpers.js'); -const {getTappableRectsFromClientRects} = require('../../lib/tappable-rects.js'); -const i18n = require('../../lib/i18n/i18n.js'); +} from '../../lib/rect-helpers.js'; + +import {getTappableRectsFromClientRects} from '../../lib/tappable-rects.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on whether tap targets (like buttons and links) on a page are big enough so they can easily be tapped on a mobile device. This descriptive title is shown when tap targets are easy to tap on. */ @@ -40,7 +43,7 @@ const UIStrings = { displayValue: '{decimalProportion, number, percent} appropriately sized tap targets', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const FINGER_SIZE_PX = 48; // Ratio of the finger area tapping on an unintended element @@ -317,8 +320,8 @@ class TapTargets extends Audit { TapTargets.FINGER_SIZE_PX = FINGER_SIZE_PX; -module.exports = TapTargets; -module.exports.UIStrings = UIStrings; +export default TapTargets; +export {UIStrings}; /** @typedef {{ diff --git a/lighthouse-core/audits/server-response-time.js b/lighthouse-core/audits/server-response-time.js index 95838d28e2b3..9a4d88478f54 100644 --- a/lighthouse-core/audits/server-response-time.js +++ b/lighthouse-core/audits/server-response-time.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const MainResource = require('../computed/main-resource.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import MainResource from '../computed/main-resource.js'; const UIStrings = { /** Title of a diagnostic audit that provides detail on how long it took from starting a request to when the server started responding. This descriptive title is shown to users when the amount is acceptable and no user action is required. */ @@ -20,7 +20,7 @@ const UIStrings = { displayValue: `Root document took {timeInMs, number, milliseconds}\xa0ms`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // Due to the way that DevTools throttling works we cannot see if server response took less than ~570ms. // We set our failure threshold to 600ms to avoid those false positives but we want devs to shoot for 100ms. @@ -87,5 +87,5 @@ class ServerResponseTime extends Audit { } } -module.exports = ServerResponseTime; -module.exports.UIStrings = UIStrings; +export default ServerResponseTime; +export {UIStrings}; diff --git a/lighthouse-core/audits/service-worker.js b/lighthouse-core/audits/service-worker.js index 800fd98f61fc..e2c92c9f08c3 100644 --- a/lighthouse-core/audits/service-worker.js +++ b/lighthouse-core/audits/service-worker.js @@ -5,9 +5,9 @@ */ 'use strict'; -const URL = require('../lib/url-shim.js'); -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); +import URL from '../lib/url-shim.js'; +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on a page's service worker. This descriptive title is shown to users when a service worker is registered and valid. */ @@ -39,7 +39,7 @@ const UIStrings = { 'the `start_url` ({startUrl}) is not in the service worker\'s scope ({scopeUrl})', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class ServiceWorker extends Audit { /** @@ -180,5 +180,5 @@ class ServiceWorker extends Audit { } } -module.exports = ServiceWorker; -module.exports.UIStrings = UIStrings; +export default ServiceWorker; +export {UIStrings}; diff --git a/lighthouse-core/audits/splash-screen.js b/lighthouse-core/audits/splash-screen.js index 2dbcd3606150..98059d1521c8 100644 --- a/lighthouse-core/audits/splash-screen.js +++ b/lighthouse-core/audits/splash-screen.js @@ -5,9 +5,9 @@ */ 'use strict'; -const MultiCheckAudit = require('./multi-check-audit.js'); -const ManifestValues = require('../computed/manifest-values.js'); -const i18n = require('../lib/i18n/i18n.js'); +import MultiCheckAudit from './multi-check-audit.js'; +import ManifestValues from '../computed/manifest-values.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on splash screens. This descriptive title is shown to users when the site has a custom splash screen. */ @@ -20,7 +20,7 @@ const UIStrings = { 'more](https://web.dev/splash-screen/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview @@ -95,5 +95,5 @@ class SplashScreen extends MultiCheckAudit { } } -module.exports = SplashScreen; -module.exports.UIStrings = UIStrings; +export default SplashScreen; +export {UIStrings}; diff --git a/lighthouse-core/audits/themed-omnibox.js b/lighthouse-core/audits/themed-omnibox.js index 95556fd444e6..26355b3925de 100644 --- a/lighthouse-core/audits/themed-omnibox.js +++ b/lighthouse-core/audits/themed-omnibox.js @@ -5,10 +5,10 @@ */ 'use strict'; -const MultiCheckAudit = require('./multi-check-audit.js'); -const ManifestValues = require('../computed/manifest-values.js'); -const cssParsers = require('cssstyle/lib/parsers'); -const i18n = require('../lib/i18n/i18n.js'); +import MultiCheckAudit from './multi-check-audit.js'; +import ManifestValues from '../computed/manifest-values.js'; +import cssParsers from 'cssstyle/lib/parsers.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the theme color the web page has set for the browser's address bar. This descriptive title is shown to users when an address-bar theme color has been set. */ @@ -20,7 +20,7 @@ const UIStrings = { '[Learn more](https://web.dev/themed-omnibox/).', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview @@ -106,5 +106,5 @@ class ThemedOmnibox extends MultiCheckAudit { } } -module.exports = ThemedOmnibox; -module.exports.UIStrings = UIStrings; +export default ThemedOmnibox; +export {UIStrings}; diff --git a/lighthouse-core/audits/third-party-facades.js b/lighthouse-core/audits/third-party-facades.js index 286e8a1837d3..1a0915087196 100644 --- a/lighthouse-core/audits/third-party-facades.js +++ b/lighthouse-core/audits/third-party-facades.js @@ -20,13 +20,14 @@ /** @typedef {{product: ThirdPartyProduct, entity: ThirdPartyEntity}} FacadableProduct */ -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const thirdPartyWeb = require('../lib/third-party-web.js'); -const NetworkRecords = require('../computed/network-records.js'); -const MainResource = require('../computed/main-resource.js'); -const MainThreadTasks = require('../computed/main-thread-tasks.js'); -const ThirdPartySummary = require('./third-party-summary.js'); +import {Audit} from './audit.js'; + +import * as i18n from '../lib/i18n/i18n.js'; +import thirdPartyWeb from '../lib/third-party-web.js'; +import NetworkRecords from '../computed/network-records.js'; +import MainResource from '../computed/main-resource.js'; +import MainThreadTasks from '../computed/main-thread-tasks.js'; +import ThirdPartySummary from './third-party-summary.js'; const UIStrings = { /** Title of a diagnostic audit that provides details about the third-party code on a web page that can be lazy loaded with a facade alternative. This descriptive title is shown to users when no resources have facade alternatives available. A facade is a lightweight component which looks like the desired resource. Lazy loading means resources are deferred until they are needed. Third-party code refers to resources that are not within the control of the site owner. */ @@ -65,7 +66,7 @@ const UIStrings = { categorySocial: '{productName} (Social)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @type {Record<string, string>} */ const CATEGORY_UI_MAP = { @@ -93,7 +94,7 @@ class ThirdPartyFacades extends Audit { /** * Sort items by transfer size and combine small items into a single row. * Items will be mutated in place to a maximum of 6 rows. - * @param {ThirdPartySummary.URLSummary[]} items + * @param {import('./third-party-summary.js').URLSummary[]} items */ static condenseItems(items) { items.sort((a, b) => b.transferSize - a.transferSize); @@ -120,7 +121,7 @@ class ThirdPartyFacades extends Audit { } /** - * @param {Map<string, ThirdPartySummary.Summary>} byURL + * @param {Map<string, import('./third-party-summary.js').Summary>} byURL * @param {ThirdPartyEntity | undefined} mainEntity * @return {FacadableProduct[]} */ @@ -180,7 +181,7 @@ class ThirdPartyFacades extends Audit { const items = Array.from(urls).map((url) => { const urlStats = summaries.byURL.get(url); - return /** @type {ThirdPartySummary.URLSummary} */ ({url, ...urlStats}); + return /** @type {import('./third-party-summary.js').URLSummary} */ ({url, ...urlStats}); }); this.condenseItems(items); results.push({ @@ -217,5 +218,5 @@ class ThirdPartyFacades extends Audit { } } -module.exports = ThirdPartyFacades; -module.exports.UIStrings = UIStrings; +export default ThirdPartyFacades; +export {UIStrings}; diff --git a/lighthouse-core/audits/third-party-summary.js b/lighthouse-core/audits/third-party-summary.js index c7089d168020..c9c0b209e847 100644 --- a/lighthouse-core/audits/third-party-summary.js +++ b/lighthouse-core/audits/third-party-summary.js @@ -5,12 +5,12 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const thirdPartyWeb = require('../lib/third-party-web.js'); -const NetworkRecords = require('../computed/network-records.js'); -const MainThreadTasks = require('../computed/main-thread-tasks.js'); -const {getJavaScriptURLs, getAttributableURLForTask} = require('../lib/tracehouse/task-summary.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import thirdPartyWeb from '../lib/third-party-web.js'; +import NetworkRecords from '../computed/network-records.js'; +import MainThreadTasks from '../computed/main-thread-tasks.js'; +import {getJavaScriptURLs, getAttributableURLForTask} from '../lib/tracehouse/task-summary.js'; const UIStrings = { /** Title of a diagnostic audit that provides details about the code on a web page that the user doesn't control (referred to as "third-party code"). This descriptive title is shown to users when the amount is acceptable and no user action is required. */ @@ -28,7 +28,7 @@ const UIStrings = { `{timeInMs, number, milliseconds}\xa0ms`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // A page passes when all third-party code blocks for less than 250 ms. const PASS_THRESHOLD_IN_MS = 250; @@ -255,5 +255,5 @@ class ThirdPartySummary extends Audit { } } -module.exports = ThirdPartySummary; -module.exports.UIStrings = UIStrings; +export default ThirdPartySummary; +export {UIStrings}; diff --git a/lighthouse-core/audits/timing-budget.js b/lighthouse-core/audits/timing-budget.js index 8abe4779e73b..4a394886088e 100644 --- a/lighthouse-core/audits/timing-budget.js +++ b/lighthouse-core/audits/timing-budget.js @@ -5,11 +5,11 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const TimingSummary = require('../computed/metrics/timing-summary.js'); -const MainResource = require('../computed/main-resource.js'); -const Budget = require('../config/budget.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import TimingSummary from '../computed/metrics/timing-summary.js'; +import MainResource from '../computed/main-resource.js'; +import {Budget} from '../config/budget.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that compares how quickly the page loads against targets set by the user. Timing budgets are a type of performance budget. */ @@ -22,7 +22,7 @@ const UIStrings = { columnMeasurement: 'Measurement', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @typedef {{metric: LH.Budget.TimingMetric, label: LH.IcuMessage, measurement?: LH.Audit.Details.NumericValue|number, overBudget?: LH.Audit.Details.NumericValue|number}} BudgetItem */ @@ -171,5 +171,5 @@ class TimingBudget extends Audit { } } -module.exports = TimingBudget; -module.exports.UIStrings = UIStrings; +export default TimingBudget; +export {UIStrings}; diff --git a/lighthouse-core/audits/unsized-images.js b/lighthouse-core/audits/unsized-images.js index d44e8d541fcc..d7b2a445e155 100644 --- a/lighthouse-core/audits/unsized-images.js +++ b/lighthouse-core/audits/unsized-images.js @@ -10,9 +10,9 @@ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('./../lib/i18n/i18n.js'); -const URL = require('./../lib/url-shim.js'); +import {Audit} from './audit.js'; +import * as i18n from './../lib/i18n/i18n.js'; +import URL from './../lib/url-shim.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on whether all images have explicit width and height. This descriptive title is shown to users when every image has explicit width and height */ @@ -23,7 +23,7 @@ const UIStrings = { description: 'Set an explicit width and height on image elements to reduce layout shifts and improve CLS. [Learn more](https://web.dev/optimize-cls/#images-without-dimensions)', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class UnsizedImages extends Audit { /** @@ -159,5 +159,5 @@ class UnsizedImages extends Audit { } } -module.exports = UnsizedImages; -module.exports.UIStrings = UIStrings; +export default UnsizedImages; +export {UIStrings}; diff --git a/lighthouse-core/audits/user-timings.js b/lighthouse-core/audits/user-timings.js index f47019360dd1..bc55c5b9cda4 100644 --- a/lighthouse-core/audits/user-timings.js +++ b/lighthouse-core/audits/user-timings.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); -const ComputedUserTimings = require('../computed/user-timings.js'); +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import ComputedUserTimings from '../computed/user-timings.js'; const UIStrings = { /** Descriptive title of a diagnostic audit that provides details on any timestamps generated by the page. User Timing refers to the 'User Timing API', which enables a website to record specific times as 'marks', or spans of time as 'measures'. */ @@ -25,7 +25,7 @@ const UIStrings = { columnType: 'Type', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @typedef {{name: string, isMark: true, args: LH.TraceEvent['args'], startTime: number}} MarkEvent */ /** @typedef {{name: string, isMark: false, args: LH.TraceEvent['args'], startTime: number, endTime: number, duration: number}} MeasureEvent */ @@ -116,5 +116,5 @@ class UserTimings extends Audit { } } -module.exports = UserTimings; -module.exports.UIStrings = UIStrings; +export default UserTimings; +export {UIStrings}; diff --git a/lighthouse-core/audits/uses-rel-preconnect.js b/lighthouse-core/audits/uses-rel-preconnect.js index d7a26ec31f9a..9422938e77d5 100644 --- a/lighthouse-core/audits/uses-rel-preconnect.js +++ b/lighthouse-core/audits/uses-rel-preconnect.js @@ -6,17 +6,17 @@ 'use strict'; -const Audit = require('./audit.js'); -const UnusedBytes = require('./byte-efficiency/byte-efficiency-audit.js'); -const URL = require('../lib/url-shim.js'); -const i18n = require('../lib/i18n/i18n.js'); -const NetworkRecords = require('../computed/network-records.js'); -const MainResource = require('../computed/main-resource.js'); -const LoadSimulator = require('../computed/load-simulator.js'); -const ProcessedTrace = require('../computed/processed-trace.js'); -const ProcessedNavigation = require('../computed/processed-navigation.js'); -const PageDependencyGraph = require('../computed/page-dependency-graph.js'); -const LanternLCP = require('../computed/metrics/lantern-largest-contentful-paint.js'); +import {Audit} from './audit.js'; +import {ByteEfficiencyAudit} from './byte-efficiency/byte-efficiency-audit.js'; +import URL from '../lib/url-shim.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import NetworkRecords from '../computed/network-records.js'; +import MainResource from '../computed/main-resource.js'; +import LoadSimulator from '../computed/load-simulator.js'; +import ProcessedTrace from '../computed/processed-trace.js'; +import ProcessedNavigation from '../computed/processed-navigation.js'; +import PageDependencyGraph from '../computed/page-dependency-graph.js'; +import LanternLCP from '../computed/metrics/lantern-largest-contentful-paint.js'; // Preconnect establishes a "clean" socket. Chrome's socket manager will keep an unused socket // around for 10s. Meaning, the time delta between processing preconnect a request should be <10s, @@ -52,7 +52,7 @@ const UIStrings = { 'These should be used sparingly and only to the most important origins.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class UsesRelPreconnectAudit extends Audit { /** @@ -238,7 +238,7 @@ class UsesRelPreconnectAudit extends Audit { const details = Audit.makeOpportunityDetails(headings, results, maxWasted); return { - score: UnusedBytes.scoreForWastedMs(maxWasted), + score: ByteEfficiencyAudit.scoreForWastedMs(maxWasted), numericValue: maxWasted, numericUnit: 'millisecond', displayValue: maxWasted ? @@ -250,5 +250,5 @@ class UsesRelPreconnectAudit extends Audit { } } -module.exports = UsesRelPreconnectAudit; -module.exports.UIStrings = UIStrings; +export default UsesRelPreconnectAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/uses-rel-preload.js b/lighthouse-core/audits/uses-rel-preload.js index 49959f978097..17bac8da352f 100644 --- a/lighthouse-core/audits/uses-rel-preload.js +++ b/lighthouse-core/audits/uses-rel-preload.js @@ -5,15 +5,15 @@ */ 'use strict'; -const URL = require('../lib/url-shim.js'); -const NetworkRequest = require('../lib/network-request.js'); -const Audit = require('./audit.js'); -const UnusedBytes = require('./byte-efficiency/byte-efficiency-audit.js'); -const CriticalRequestChains = require('../computed/critical-request-chains.js'); -const i18n = require('../lib/i18n/i18n.js'); -const MainResource = require('../computed/main-resource.js'); -const PageDependencyGraph = require('../computed/page-dependency-graph.js'); -const LoadSimulator = require('../computed/load-simulator.js'); +import URL from '../lib/url-shim.js'; +import {NetworkRequest} from '../lib/network-request.js'; +import {Audit} from './audit.js'; +import {ByteEfficiencyAudit} from './byte-efficiency/byte-efficiency-audit.js'; +import CriticalRequestChains from '../computed/critical-request-chains.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import MainResource from '../computed/main-resource.js'; +import PageDependencyGraph from '../computed/page-dependency-graph.js'; +import LoadSimulator from '../computed/load-simulator.js'; const UIStrings = { /** Imperative title of a Lighthouse audit that tells the user to use <link rel=preload> to initiate important network requests earlier during page load. This is displayed in a list of audit titles that Lighthouse generates. */ @@ -29,7 +29,7 @@ const UIStrings = { 'by the browser. Check that you are using the `crossorigin` attribute properly.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const THRESHOLD_IN_MS = 100; @@ -242,7 +242,7 @@ class UsesRelPreloadAudit extends Audit { const details = Audit.makeOpportunityDetails(headings, results, wastedMs); return { - score: UnusedBytes.scoreForWastedMs(wastedMs), + score: ByteEfficiencyAudit.scoreForWastedMs(wastedMs), numericValue: wastedMs, numericUnit: 'millisecond', displayValue: wastedMs ? @@ -263,5 +263,5 @@ class UsesRelPreloadAudit extends Audit { } } -module.exports = UsesRelPreloadAudit; -module.exports.UIStrings = UIStrings; +export default UsesRelPreloadAudit; +export {UIStrings}; diff --git a/lighthouse-core/audits/valid-source-maps.js b/lighthouse-core/audits/valid-source-maps.js index 6dd465df2c78..345c292e9fea 100644 --- a/lighthouse-core/audits/valid-source-maps.js +++ b/lighthouse-core/audits/valid-source-maps.js @@ -5,9 +5,9 @@ */ 'use strict'; -const thirdPartyWeb = require('../lib/third-party-web.js'); -const Audit = require('./audit.js'); -const i18n = require('../lib/i18n/i18n.js'); +import thirdPartyWeb from '../lib/third-party-web.js'; +import {Audit} from './audit.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on HTTP to HTTPS redirects. This descriptive title is shown to users when HTTP traffic is redirected to HTTPS. */ @@ -30,7 +30,7 @@ const UIStrings = { }`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const LARGE_JS_BYTE_THRESHOLD = 500 * 1024; @@ -151,5 +151,5 @@ class ValidSourceMaps extends Audit { } } -module.exports = ValidSourceMaps; -module.exports.UIStrings = UIStrings; +export default ValidSourceMaps; +export {UIStrings}; diff --git a/lighthouse-core/audits/viewport.js b/lighthouse-core/audits/viewport.js index d91af1906cd6..74006a212cc9 100644 --- a/lighthouse-core/audits/viewport.js +++ b/lighthouse-core/audits/viewport.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const ComputedViewportMeta = require('../computed/viewport-meta.js'); -const i18n = require('../lib/i18n/i18n.js'); +import {Audit} from './audit.js'; +import ComputedViewportMeta from '../computed/viewport-meta.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** Title of a Lighthouse audit that provides detail on the viewport meta tag in a web page's html. This descriptive title is shown to users when a viewport tag is set and configured. */ @@ -23,7 +23,7 @@ const UIStrings = { explanationNoTag: 'No `<meta name="viewport">` tag found', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); class Viewport extends Audit { /** @@ -61,5 +61,5 @@ class Viewport extends Audit { } } -module.exports = Viewport; -module.exports.UIStrings = UIStrings; +export default Viewport; +export {UIStrings}; diff --git a/lighthouse-core/audits/violation-audit.js b/lighthouse-core/audits/violation-audit.js index a322d6b20f66..c609f0782b05 100644 --- a/lighthouse-core/audits/violation-audit.js +++ b/lighthouse-core/audits/violation-audit.js @@ -5,8 +5,8 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const JsBundles = require('../computed/js-bundles.js'); +import {Audit} from './audit.js'; +import JsBundles from '../computed/js-bundles.js'; class ViolationAudit extends Audit { /** @@ -47,4 +47,4 @@ class ViolationAudit extends Audit { } } -module.exports = ViolationAudit; +export default ViolationAudit; diff --git a/lighthouse-core/audits/work-during-interaction.js b/lighthouse-core/audits/work-during-interaction.js index b50075b95543..44807db99b1b 100644 --- a/lighthouse-core/audits/work-during-interaction.js +++ b/lighthouse-core/audits/work-during-interaction.js @@ -5,17 +5,17 @@ */ 'use strict'; -const Audit = require('./audit.js'); -const ComputedResponsivenes = require('../computed/metrics/responsiveness.js'); -const ProcessedTrace = require('../computed/processed-trace.js'); -const i18n = require('../lib/i18n/i18n.js'); -const NetworkRecords = require('../computed/network-records.js'); -const MainThreadTasks = require('../lib/tracehouse/main-thread-tasks.js'); -const {taskGroups} = require('../lib/tracehouse/task-groups.js'); -const TraceProcessor = require('../lib/tracehouse/trace-processor.js'); -const {getExecutionTimingsByURL} = require('../lib/tracehouse/task-summary.js'); -const inpThresholds = require('./metrics/experimental-interaction-to-next-paint.js').defaultOptions; -const LighthouseError = require('../lib/lh-error.js'); +import {Audit} from './audit.js'; +import ComputedResponsivenes from '../computed/metrics/responsiveness.js'; +import ProcessedTrace from '../computed/processed-trace.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import NetworkRecords from '../computed/network-records.js'; +import {MainThreadTasks} from '../lib/tracehouse/main-thread-tasks.js'; +import {taskGroups} from '../lib/tracehouse/task-groups.js'; +import {TraceProcessor} from '../lib/tracehouse/trace-processor.js'; +import {getExecutionTimingsByURL} from '../lib/tracehouse/task-summary.js'; +import ExperimentalInteractionToNextPaint from './metrics/experimental-interaction-to-next-paint.js'; +import {LighthouseError} from '../lib/lh-error.js'; /** @typedef {import('../computed/metrics/responsiveness.js').EventTimingEvent} EventTimingEvent */ /** @typedef {import('../lib/tracehouse/main-thread-tasks.js').TaskNode} TaskNode */ @@ -44,7 +44,7 @@ const UIStrings = { eventTarget: 'Event target', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @fileoverview This metric gives a high-percentile measure of responsiveness to input. @@ -266,7 +266,7 @@ class WorkDuringInteraction extends Audit { const duration = interactionEvent.args.data.duration; const displayValue = str_(UIStrings.displayValue, {timeInMs: duration, interactionType}); return { - score: duration < inpThresholds.p10 ? 1 : 0, + score: duration < ExperimentalInteractionToNextPaint.defaultOptions.p10 ? 1 : 0, displayValue, details: { type: 'list', @@ -276,5 +276,5 @@ class WorkDuringInteraction extends Audit { } } -module.exports = WorkDuringInteraction; -module.exports.UIStrings = UIStrings; +export default WorkDuringInteraction; +export {UIStrings}; diff --git a/lighthouse-core/computed/computed-artifact.js b/lighthouse-core/computed/computed-artifact.js index eb0e63e2baaa..8425c17eefae 100644 --- a/lighthouse-core/computed/computed-artifact.js +++ b/lighthouse-core/computed/computed-artifact.js @@ -5,8 +5,8 @@ */ 'use strict'; -const ArbitraryEqualityMap = require('../lib/arbitrary-equality-map.js'); -const log = require('lighthouse-logger'); +import {ArbitraryEqualityMap} from '../lib/arbitrary-equality-map.js'; +import log from 'lighthouse-logger'; /** * Decorate computableArtifact with a caching `request()` method which will @@ -59,4 +59,4 @@ function makeComputedArtifact(computableArtifact, keys) { return Object.assign(computableArtifact, {request}); } -module.exports = makeComputedArtifact; +export {makeComputedArtifact}; diff --git a/lighthouse-core/computed/critical-request-chains.js b/lighthouse-core/computed/critical-request-chains.js index 13da33e423ef..76ce47afdae3 100644 --- a/lighthouse-core/computed/critical-request-chains.js +++ b/lighthouse-core/computed/critical-request-chains.js @@ -5,10 +5,10 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const NetworkRequest = require('../lib/network-request.js'); -const MainResource = require('./main-resource.js'); -const PageDependencyGraph = require('./page-dependency-graph.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import {NetworkRequest} from '../lib/network-request.js'; +import MainResource from './main-resource.js'; +import PageDependencyGraph from './page-dependency-graph.js'; class CriticalRequestChains { /** @@ -139,4 +139,4 @@ class CriticalRequestChains { } } -module.exports = makeComputedArtifact(CriticalRequestChains, ['URL', 'devtoolsLog', 'trace']); +export default makeComputedArtifact(CriticalRequestChains, ['URL', 'devtoolsLog', 'trace']); diff --git a/lighthouse-core/computed/image-records.js b/lighthouse-core/computed/image-records.js index 5a534fb240ec..5473d7c5c7a0 100644 --- a/lighthouse-core/computed/image-records.js +++ b/lighthouse-core/computed/image-records.js @@ -5,8 +5,8 @@ */ 'use strict'; -const URL = require('../lib/url-shim.js'); -const makeComputedArtifact = require('./computed-artifact.js'); +import URL from '../lib/url-shim.js'; +import {makeComputedArtifact} from './computed-artifact.js'; class ImageRecords { /** @@ -59,5 +59,5 @@ class ImageRecords { } } -module.exports = makeComputedArtifact(ImageRecords, ['ImageElements', 'networkRecords']); +export default makeComputedArtifact(ImageRecords, ['ImageElements', 'networkRecords']); diff --git a/lighthouse-core/computed/js-bundles.js b/lighthouse-core/computed/js-bundles.js index 3404a87ca772..edea2fe0d459 100644 --- a/lighthouse-core/computed/js-bundles.js +++ b/lighthouse-core/computed/js-bundles.js @@ -5,9 +5,9 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const makeComputedArtifact = require('./computed-artifact.js'); -const SDK = require('../lib/cdt/SDK.js'); +import log from 'lighthouse-logger'; +import {makeComputedArtifact} from './computed-artifact.js'; +import SDK from '../lib/cdt/SDK.js'; /** * Calculate the number of bytes contributed by each source file @@ -116,4 +116,4 @@ class JSBundles { } } -module.exports = makeComputedArtifact(JSBundles, ['Scripts', 'SourceMaps']); +export default makeComputedArtifact(JSBundles, ['Scripts', 'SourceMaps']); diff --git a/lighthouse-core/computed/load-simulator.js b/lighthouse-core/computed/load-simulator.js index bc56c39dbef4..789fcde098e3 100644 --- a/lighthouse-core/computed/load-simulator.js +++ b/lighthouse-core/computed/load-simulator.js @@ -5,10 +5,10 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const constants = require('../config/constants.js'); -const Simulator = require('../lib/dependency-graph/simulator/simulator.js'); -const NetworkAnalysis = require('./network-analysis.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import * as constants from '../config/constants.js'; +import {Simulator} from '../lib/dependency-graph/simulator/simulator.js'; +import NetworkAnalysis from './network-analysis.js'; class LoadSimulator { /** @@ -89,4 +89,7 @@ class LoadSimulator { } } -module.exports = makeComputedArtifact(LoadSimulator, ['devtoolsLog', 'settings']); +// TODO(esmodules): For all computed artifacts: +// const LoadSimulatorComputed = makeComputedArtifact(LoadSimulator, ['devtoolsLog', 'settings']); +// export {LoadSimulator as LoadSimulatorComputed}; +export default makeComputedArtifact(LoadSimulator, ['devtoolsLog', 'settings']); diff --git a/lighthouse-core/computed/main-resource.js b/lighthouse-core/computed/main-resource.js index e05619127d37..3c75662dc47c 100644 --- a/lighthouse-core/computed/main-resource.js +++ b/lighthouse-core/computed/main-resource.js @@ -5,9 +5,9 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const NetworkAnalyzer = require('../lib/dependency-graph/simulator/network-analyzer.js'); -const NetworkRecords = require('./network-records.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import {NetworkAnalyzer} from '../lib/dependency-graph/simulator/network-analyzer.js'; +import NetworkRecords from './network-records.js'; /** * @fileoverview This artifact identifies the main resource on the page. Current solution assumes @@ -32,4 +32,4 @@ class MainResource { } } -module.exports = makeComputedArtifact(MainResource, ['URL', 'devtoolsLog']); +export default makeComputedArtifact(MainResource, ['URL', 'devtoolsLog']); diff --git a/lighthouse-core/computed/main-thread-tasks.js b/lighthouse-core/computed/main-thread-tasks.js index 76d39a9129b3..bbd789182450 100644 --- a/lighthouse-core/computed/main-thread-tasks.js +++ b/lighthouse-core/computed/main-thread-tasks.js @@ -5,9 +5,9 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const MainThreadTasks_ = require('../lib/tracehouse/main-thread-tasks.js'); -const ProcessedTrace = require('./processed-trace.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import {MainThreadTasks as MainThreadTasks_} from '../lib/tracehouse/main-thread-tasks.js'; +import ProcessedTrace from './processed-trace.js'; class MainThreadTasks { /** @@ -21,4 +21,4 @@ class MainThreadTasks { } } -module.exports = makeComputedArtifact(MainThreadTasks, null); +export default makeComputedArtifact(MainThreadTasks, null); diff --git a/lighthouse-core/computed/manifest-values.js b/lighthouse-core/computed/manifest-values.js index a68ed0c32df5..229f602c1861 100644 --- a/lighthouse-core/computed/manifest-values.js +++ b/lighthouse-core/computed/manifest-values.js @@ -5,8 +5,8 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const icons = require('../lib/icons.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import * as icons from '../lib/icons.js'; const PWA_DISPLAY_VALUES = ['minimal-ui', 'fullscreen', 'standalone']; @@ -132,4 +132,4 @@ class ManifestValues { } } -module.exports = makeComputedArtifact(ManifestValues, ['InstallabilityErrors', 'WebAppManifest']); +export default makeComputedArtifact(ManifestValues, ['InstallabilityErrors', 'WebAppManifest']); diff --git a/lighthouse-core/computed/metrics/cumulative-layout-shift.js b/lighthouse-core/computed/metrics/cumulative-layout-shift.js index 55797fb055bd..9c8aee57af31 100644 --- a/lighthouse-core/computed/metrics/cumulative-layout-shift.js +++ b/lighthouse-core/computed/metrics/cumulative-layout-shift.js @@ -5,9 +5,9 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const ProcessedTrace = require('../processed-trace.js'); -const LighthouseError = require('../../lib/lh-error.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import ProcessedTrace from '../processed-trace.js'; +import {LighthouseError} from '../../lib/lh-error.js'; /** @typedef {{ts: number, isMainFrame: boolean, weightedScore: number}} LayoutShiftEvent */ @@ -126,4 +126,4 @@ class CumulativeLayoutShift { } } -module.exports = makeComputedArtifact(CumulativeLayoutShift, null); +export default makeComputedArtifact(CumulativeLayoutShift, null); diff --git a/lighthouse-core/computed/metrics/first-contentful-paint-all-frames.js b/lighthouse-core/computed/metrics/first-contentful-paint-all-frames.js index 023b42fe6fb7..dc42b30af0ba 100644 --- a/lighthouse-core/computed/metrics/first-contentful-paint-all-frames.js +++ b/lighthouse-core/computed/metrics/first-contentful-paint-all-frames.js @@ -5,8 +5,8 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const NavigationMetric = require('./navigation-metric.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import NavigationMetric from './navigation-metric.js'; class FirstContentfulPaintAllFrames extends NavigationMetric { /** @@ -31,7 +31,7 @@ class FirstContentfulPaintAllFrames extends NavigationMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( FirstContentfulPaintAllFrames, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/first-contentful-paint.js b/lighthouse-core/computed/metrics/first-contentful-paint.js index 7db90d4ddbe0..49746bf9da8b 100644 --- a/lighthouse-core/computed/metrics/first-contentful-paint.js +++ b/lighthouse-core/computed/metrics/first-contentful-paint.js @@ -5,9 +5,9 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const NavigationMetric = require('./navigation-metric.js'); -const LanternFirstContentfulPaint = require('./lantern-first-contentful-paint.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import NavigationMetric from './navigation-metric.js'; +import LanternFirstContentfulPaint from './lantern-first-contentful-paint.js'; class FirstContentfulPaint extends NavigationMetric { /** @@ -34,7 +34,7 @@ class FirstContentfulPaint extends NavigationMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( FirstContentfulPaint, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/first-meaningful-paint.js b/lighthouse-core/computed/metrics/first-meaningful-paint.js index 65831143a011..af4cfe2622c9 100644 --- a/lighthouse-core/computed/metrics/first-meaningful-paint.js +++ b/lighthouse-core/computed/metrics/first-meaningful-paint.js @@ -5,10 +5,10 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const NavigationMetric = require('./navigation-metric.js'); -const LighthouseError = require('../../lib/lh-error.js'); -const LanternFirstMeaningfulPaint = require('./lantern-first-meaningful-paint.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import NavigationMetric from './navigation-metric.js'; +import {LighthouseError} from '../../lib/lh-error.js'; +import LanternFirstMeaningfulPaint from './lantern-first-meaningful-paint.js'; class FirstMeaningfulPaint extends NavigationMetric { /** @@ -38,7 +38,7 @@ class FirstMeaningfulPaint extends NavigationMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( FirstMeaningfulPaint, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/interactive.js b/lighthouse-core/computed/metrics/interactive.js index 31ea8ff7e9b3..401648ab7043 100644 --- a/lighthouse-core/computed/metrics/interactive.js +++ b/lighthouse-core/computed/metrics/interactive.js @@ -5,13 +5,12 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const NavigationMetric = require('./navigation-metric.js'); -const LanternInteractive = require('./lantern-interactive.js'); - -const NetworkMonitor = require('../../gather/driver/network-monitor.js'); -const TracingProcessor = require('../../lib/tracehouse/trace-processor.js'); -const LighthouseError = require('../../lib/lh-error.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import NavigationMetric from './navigation-metric.js'; +import LanternInteractive from './lantern-interactive.js'; +import {NetworkMonitor} from '../../gather/driver/network-monitor.js'; +import {TraceProcessor} from '../../lib/tracehouse/trace-processor.js'; +import {LighthouseError} from '../../lib/lh-error.js'; const REQUIRED_QUIET_WINDOW = 5000; const ALLOWED_CONCURRENT_REQUESTS = 2; @@ -161,7 +160,7 @@ class Interactive extends NavigationMetric { throw new LighthouseError(LighthouseError.errors.NO_DCL); } - const longTasks = TracingProcessor.getMainThreadTopLevelEvents(processedTrace) + const longTasks = TraceProcessor.getMainThreadTopLevelEvents(processedTrace) .filter(event => event.duration >= 50); const quietPeriodInfo = Interactive.findOverlappingQuietPeriods( longTasks, @@ -181,7 +180,7 @@ class Interactive extends NavigationMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( Interactive, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/lantern-first-contentful-paint.js b/lighthouse-core/computed/metrics/lantern-first-contentful-paint.js index 21a0906085b7..bb46d0e31c85 100644 --- a/lighthouse-core/computed/metrics/lantern-first-contentful-paint.js +++ b/lighthouse-core/computed/metrics/lantern-first-contentful-paint.js @@ -5,13 +5,13 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const LanternMetric = require('./lantern-metric.js'); -const BaseNode = require('../../lib/dependency-graph/base-node.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import LanternMetric from './lantern-metric.js'; +import {BaseNode} from '../../lib/dependency-graph/base-node.js'; -/** @typedef {BaseNode.Node} Node */ -/** @typedef {import('../../lib/dependency-graph/cpu-node')} CPUNode */ -/** @typedef {import('../../lib/dependency-graph/network-node')} NetworkNode */ +/** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ +/** @typedef {import('../../lib/dependency-graph/cpu-node').CPUNode} CPUNode */ +/** @typedef {import('../../lib/dependency-graph/network-node').NetworkNode} NetworkNode */ class LanternFirstContentfulPaint extends LanternMetric { /** @@ -198,7 +198,7 @@ class LanternFirstContentfulPaint extends LanternMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LanternFirstContentfulPaint, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/lantern-first-meaningful-paint.js b/lighthouse-core/computed/metrics/lantern-first-meaningful-paint.js index 1d01579fb3f4..0581d1b85f03 100644 --- a/lighthouse-core/computed/metrics/lantern-first-meaningful-paint.js +++ b/lighthouse-core/computed/metrics/lantern-first-meaningful-paint.js @@ -5,10 +5,10 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const LanternMetric = require('./lantern-metric.js'); -const LighthouseError = require('../../lib/lh-error.js'); -const LanternFirstContentfulPaint = require('./lantern-first-contentful-paint.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import LanternMetric from './lantern-metric.js'; +import {LighthouseError} from '../../lib/lh-error.js'; +import LanternFirstContentfulPaint from './lantern-first-contentful-paint.js'; /** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ @@ -77,7 +77,7 @@ class LanternFirstMeaningfulPaint extends LanternMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LanternFirstMeaningfulPaint, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/lantern-interactive.js b/lighthouse-core/computed/metrics/lantern-interactive.js index d84637832231..d2d9e2d050ba 100644 --- a/lighthouse-core/computed/metrics/lantern-interactive.js +++ b/lighthouse-core/computed/metrics/lantern-interactive.js @@ -5,13 +5,13 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const LanternMetric = require('./lantern-metric.js'); -const BaseNode = require('../../lib/dependency-graph/base-node.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const LanternFirstMeaningfulPaint = require('./lantern-first-meaningful-paint.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import LanternMetric from './lantern-metric.js'; +import {BaseNode} from '../../lib/dependency-graph/base-node.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import LanternFirstMeaningfulPaint from './lantern-first-meaningful-paint.js'; -/** @typedef {BaseNode.Node} Node */ +/** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ // Any CPU task of 20 ms or more will end up being a critical long task on mobile const CRITICAL_LONG_TASK_THRESHOLD = 20; @@ -107,7 +107,7 @@ class LanternInteractive extends LanternMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LanternInteractive, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/lantern-largest-contentful-paint.js b/lighthouse-core/computed/metrics/lantern-largest-contentful-paint.js index e7a5fda6e2d5..156dc296f5af 100644 --- a/lighthouse-core/computed/metrics/lantern-largest-contentful-paint.js +++ b/lighthouse-core/computed/metrics/lantern-largest-contentful-paint.js @@ -5,10 +5,10 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const LanternMetric = require('./lantern-metric.js'); -const LighthouseError = require('../../lib/lh-error.js'); -const LanternFirstContentfulPaint = require('./lantern-first-contentful-paint.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import LanternMetric from './lantern-metric.js'; +import {LighthouseError} from '../../lib/lh-error.js'; +import LanternFirstContentfulPaint from './lantern-first-contentful-paint.js'; /** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ @@ -105,7 +105,7 @@ class LanternLargestContentfulPaint extends LanternMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LanternLargestContentfulPaint, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/lantern-max-potential-fid.js b/lighthouse-core/computed/metrics/lantern-max-potential-fid.js index 9b092d2ce3a5..ecaec4656b25 100644 --- a/lighthouse-core/computed/metrics/lantern-max-potential-fid.js +++ b/lighthouse-core/computed/metrics/lantern-max-potential-fid.js @@ -5,12 +5,12 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const LanternMetricArtifact = require('./lantern-metric.js'); -const BaseNode = require('../../lib/dependency-graph/base-node.js'); -const LanternFirstContentfulPaint = require('./lantern-first-contentful-paint.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import LanternMetricArtifact from './lantern-metric.js'; +import {BaseNode} from '../../lib/dependency-graph/base-node.js'; +import LanternFirstContentfulPaint from './lantern-first-contentful-paint.js'; -/** @typedef {BaseNode.Node} Node */ +/** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ class LanternMaxPotentialFID extends LanternMetricArtifact { /** @@ -87,7 +87,7 @@ class LanternMaxPotentialFID extends LanternMetricArtifact { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LanternMaxPotentialFID, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/lantern-metric.js b/lighthouse-core/computed/metrics/lantern-metric.js index 609702dfa58b..95f2cd2f19da 100644 --- a/lighthouse-core/computed/metrics/lantern-metric.js +++ b/lighthouse-core/computed/metrics/lantern-metric.js @@ -5,16 +5,16 @@ */ 'use strict'; -const BaseNode = require('../../lib/dependency-graph/base-node.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const ProcessedTrace = require('../processed-trace.js'); -const ProcessedNavigation = require('../processed-navigation.js'); -const PageDependencyGraph = require('../page-dependency-graph.js'); -const LoadSimulator = require('../load-simulator.js'); +import {BaseNode} from '../../lib/dependency-graph/base-node.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import ProcessedTrace from '../processed-trace.js'; +import ProcessedNavigation from '../processed-navigation.js'; +import PageDependencyGraph from '../page-dependency-graph.js'; +import LoadSimulator from '../load-simulator.js'; -/** @typedef {BaseNode.Node} Node */ -/** @typedef {import('../../lib/dependency-graph/network-node')} NetworkNode */ -/** @typedef {import('../../lib/dependency-graph/simulator/simulator')} Simulator */ +/** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ +/** @typedef {import('../../lib/dependency-graph/network-node').NetworkNode} NetworkNode */ +/** @typedef {import('../../lib/dependency-graph/simulator/simulator').Simulator} Simulator */ /** * @typedef Extras @@ -162,4 +162,4 @@ class LanternMetricArtifact { } } -module.exports = LanternMetricArtifact; +export default LanternMetricArtifact; diff --git a/lighthouse-core/computed/metrics/lantern-speed-index.js b/lighthouse-core/computed/metrics/lantern-speed-index.js index 096afb7d70f1..2e22bf6d774b 100644 --- a/lighthouse-core/computed/metrics/lantern-speed-index.js +++ b/lighthouse-core/computed/metrics/lantern-speed-index.js @@ -5,14 +5,14 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const LanternMetric = require('./lantern-metric.js'); -const BaseNode = require('../../lib/dependency-graph/base-node.js'); -const Speedline = require('../speedline.js'); -const LanternFirstContentfulPaint = require('./lantern-first-contentful-paint.js'); -const defaultThrottling = require('../../config/constants.js').throttling; +import {makeComputedArtifact} from '../computed-artifact.js'; +import LanternMetric from './lantern-metric.js'; +import {BaseNode} from '../../lib/dependency-graph/base-node.js'; +import Speedline from '../speedline.js'; +import LanternFirstContentfulPaint from './lantern-first-contentful-paint.js'; +import {throttling as defaultThrottling} from '../../config/constants.js'; -/** @typedef {BaseNode.Node} Node */ +/** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ class LanternSpeedIndex extends LanternMetric { /** @@ -144,7 +144,7 @@ class LanternSpeedIndex extends LanternMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LanternSpeedIndex, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/lantern-total-blocking-time.js b/lighthouse-core/computed/metrics/lantern-total-blocking-time.js index a49705203743..c6091a451dfd 100644 --- a/lighthouse-core/computed/metrics/lantern-total-blocking-time.js +++ b/lighthouse-core/computed/metrics/lantern-total-blocking-time.js @@ -5,14 +5,14 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const LanternMetric = require('./lantern-metric.js'); -const BaseNode = require('../../lib/dependency-graph/base-node.js'); -const LanternFirstContentfulPaint = require('./lantern-first-contentful-paint.js'); -const LanternInteractive = require('./lantern-interactive.js'); -const {BLOCKING_TIME_THRESHOLD, calculateSumOfBlockingTime} = require('./tbt-utils.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import LanternMetric from './lantern-metric.js'; +import {BaseNode} from '../../lib/dependency-graph/base-node.js'; +import LanternFirstContentfulPaint from './lantern-first-contentful-paint.js'; +import LanternInteractive from './lantern-interactive.js'; +import {BLOCKING_TIME_THRESHOLD, calculateSumOfBlockingTime} from './tbt-utils.js'; -/** @typedef {BaseNode.Node} Node */ +/** @typedef {import('../../lib/dependency-graph/base-node.js').Node} Node */ class LanternTotalBlockingTime extends LanternMetric { /** @@ -120,7 +120,7 @@ class LanternTotalBlockingTime extends LanternMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LanternTotalBlockingTime, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/largest-contentful-paint-all-frames.js b/lighthouse-core/computed/metrics/largest-contentful-paint-all-frames.js index b1d2116fdadb..6e65cf6474b3 100644 --- a/lighthouse-core/computed/metrics/largest-contentful-paint-all-frames.js +++ b/lighthouse-core/computed/metrics/largest-contentful-paint-all-frames.js @@ -9,9 +9,10 @@ * @fileoverview Computed Largest Contentful Paint (LCP) for all frames. */ -const makeComputedArtifact = require('../computed-artifact.js'); -const NavigationMetric = require('./navigation-metric.js'); -const LighthouseError = require('../../lib/lh-error.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; + +import NavigationMetric from './navigation-metric.js'; +import {LighthouseError} from '../../lib/lh-error.js'; class LargestContentfulPaintAllFrames extends NavigationMetric { /** @@ -39,7 +40,7 @@ class LargestContentfulPaintAllFrames extends NavigationMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LargestContentfulPaintAllFrames, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/largest-contentful-paint.js b/lighthouse-core/computed/metrics/largest-contentful-paint.js index 6ef769bae1e8..efde759a1e5b 100644 --- a/lighthouse-core/computed/metrics/largest-contentful-paint.js +++ b/lighthouse-core/computed/metrics/largest-contentful-paint.js @@ -13,10 +13,11 @@ * @see https://web.dev/largest-contentful-paint */ -const makeComputedArtifact = require('../computed-artifact.js'); -const NavigationMetric = require('./navigation-metric.js'); -const LighthouseError = require('../../lib/lh-error.js'); -const LanternLargestContentfulPaint = require('./lantern-largest-contentful-paint.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; + +import NavigationMetric from './navigation-metric.js'; +import {LighthouseError} from '../../lib/lh-error.js'; +import LanternLargestContentfulPaint from './lantern-largest-contentful-paint.js'; class LargestContentfulPaint extends NavigationMetric { /** @@ -46,7 +47,7 @@ class LargestContentfulPaint extends NavigationMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( LargestContentfulPaint, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/max-potential-fid.js b/lighthouse-core/computed/metrics/max-potential-fid.js index dfb0dd6bd9e8..13ea0bf06773 100644 --- a/lighthouse-core/computed/metrics/max-potential-fid.js +++ b/lighthouse-core/computed/metrics/max-potential-fid.js @@ -5,10 +5,10 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const NavigationMetric = require('./navigation-metric.js'); -const LanternMaxPotentialFID = require('./lantern-max-potential-fid.js'); -const TracingProcessor = require('../../lib/tracehouse/trace-processor.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import NavigationMetric from './navigation-metric.js'; +import LanternMaxPotentialFID from './lantern-max-potential-fid.js'; +import {TraceProcessor} from '../../lib/tracehouse/trace-processor.js'; class MaxPotentialFID extends NavigationMetric { /** @@ -28,7 +28,7 @@ class MaxPotentialFID extends NavigationMetric { static computeObservedMetric(data) { const {firstContentfulPaint} = data.processedNavigation.timings; - const events = TracingProcessor.getMainThreadTopLevelEvents( + const events = TraceProcessor.getMainThreadTopLevelEvents( data.processedTrace, firstContentfulPaint ).filter(evt => evt.duration >= 1); @@ -39,7 +39,7 @@ class MaxPotentialFID extends NavigationMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( MaxPotentialFID, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/metric.js b/lighthouse-core/computed/metrics/metric.js index b09c97fb24c0..ffc568967a9d 100644 --- a/lighthouse-core/computed/metrics/metric.js +++ b/lighthouse-core/computed/metrics/metric.js @@ -5,10 +5,10 @@ */ 'use strict'; -const TracingProcessor = require('../../lib/tracehouse/trace-processor.js'); -const ProcessedTrace = require('../processed-trace.js'); -const ProcessedNavigation = require('../processed-navigation.js'); -const NetworkRecords = require('../network-records.js'); +import {TraceProcessor} from '../../lib/tracehouse/trace-processor.js'; +import ProcessedTrace from '../processed-trace.js'; +import ProcessedNavigation from '../processed-navigation.js'; +import NetworkRecords from '../network-records.js'; /** * @fileOverview Encapsulates logic for choosing the correct metric computation method based on the @@ -80,7 +80,7 @@ class Metric { processedNavigation, }, data); - TracingProcessor.assertHasToplevelEvents(augmentedData.processedTrace.mainThreadEvents); + TraceProcessor.assertHasToplevelEvents(augmentedData.processedTrace.mainThreadEvents); switch (settings.throttlingMethod) { case 'simulate': @@ -98,4 +98,4 @@ class Metric { } } -module.exports = Metric; +export default Metric; diff --git a/lighthouse-core/computed/metrics/navigation-metric.js b/lighthouse-core/computed/metrics/navigation-metric.js index e87e0ed708c6..f0ad2c82bb5e 100644 --- a/lighthouse-core/computed/metrics/navigation-metric.js +++ b/lighthouse-core/computed/metrics/navigation-metric.js @@ -5,7 +5,7 @@ */ 'use strict'; -const Metric = require('./metric.js'); +import Metric from './metric.js'; /** * @fileOverview Enforces that a metric can only be computed on navigations. @@ -43,4 +43,4 @@ class NavigationMetric extends Metric { } } -module.exports = NavigationMetric; +export default NavigationMetric; diff --git a/lighthouse-core/computed/metrics/responsiveness.js b/lighthouse-core/computed/metrics/responsiveness.js index 97cf274f2256..98db761337db 100644 --- a/lighthouse-core/computed/metrics/responsiveness.js +++ b/lighthouse-core/computed/metrics/responsiveness.js @@ -31,8 +31,8 @@ * @typedef {{name: 'FallbackTiming', duration: number}} FallbackTimingEvent */ -const makeComputedArtifact = require('../computed-artifact.js'); -const ProcessedTrace = require('../processed-trace.js'); +import ProcessedTrace from '../processed-trace.js'; +import {makeComputedArtifact} from '../computed-artifact.js'; const KEYBOARD_EVENTS = new Set(['keydown', 'keypress', 'keyup']); const CLICK_TAP_DRAG_EVENTS = new Set([ @@ -151,7 +151,7 @@ class Responsiveness { } } -module.exports = makeComputedArtifact(Responsiveness, [ +export default makeComputedArtifact(Responsiveness, [ 'trace', 'settings', ]); diff --git a/lighthouse-core/computed/metrics/speed-index.js b/lighthouse-core/computed/metrics/speed-index.js index b0588542749e..3760bff79b26 100644 --- a/lighthouse-core/computed/metrics/speed-index.js +++ b/lighthouse-core/computed/metrics/speed-index.js @@ -5,10 +5,10 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const NavigationMetric = require('./navigation-metric.js'); -const LanternSpeedIndex = require('./lantern-speed-index.js'); -const Speedline = require('../speedline.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import NavigationMetric from './navigation-metric.js'; +import LanternSpeedIndex from './lantern-speed-index.js'; +import Speedline from '../speedline.js'; class SpeedIndex extends NavigationMetric { /** @@ -34,7 +34,7 @@ class SpeedIndex extends NavigationMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( SpeedIndex, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/tbt-utils.js b/lighthouse-core/computed/metrics/tbt-utils.js index 657d9a976216..5840fd52a1ea 100644 --- a/lighthouse-core/computed/metrics/tbt-utils.js +++ b/lighthouse-core/computed/metrics/tbt-utils.js @@ -51,7 +51,7 @@ function calculateSumOfBlockingTime(topLevelEvents, startTimeMs, endTimeMs) { return sumBlockingTime; } -module.exports = { +export { BLOCKING_TIME_THRESHOLD, calculateSumOfBlockingTime, }; diff --git a/lighthouse-core/computed/metrics/timing-summary.js b/lighthouse-core/computed/metrics/timing-summary.js index 53ecc231a00b..5a3cad8d4593 100644 --- a/lighthouse-core/computed/metrics/timing-summary.js +++ b/lighthouse-core/computed/metrics/timing-summary.js @@ -5,20 +5,20 @@ */ 'use strict'; -const ProcessedTrace = require('../processed-trace.js'); -const ProcessedNavigation = require('../processed-navigation.js'); -const Speedline = require('../speedline.js'); -const FirstContentfulPaint = require('./first-contentful-paint.js'); -const FirstContentfulPaintAllFrames = require('./first-contentful-paint-all-frames.js'); -const FirstMeaningfulPaint = require('./first-meaningful-paint.js'); -const LargestContentfulPaint = require('./largest-contentful-paint.js'); -const LargestContentfulPaintAllFrames = require('./largest-contentful-paint-all-frames.js'); -const Interactive = require('./interactive.js'); -const CumulativeLayoutShift = require('./cumulative-layout-shift.js'); -const SpeedIndex = require('./speed-index.js'); -const MaxPotentialFID = require('./max-potential-fid.js'); -const TotalBlockingTime = require('./total-blocking-time.js'); -const makeComputedArtifact = require('../computed-artifact.js'); +import ProcessedTrace from '../processed-trace.js'; +import ProcessedNavigation from '../processed-navigation.js'; +import Speedline from '../speedline.js'; +import FirstContentfulPaint from './first-contentful-paint.js'; +import FirstContentfulPaintAllFrames from './first-contentful-paint-all-frames.js'; +import FirstMeaningfulPaint from './first-meaningful-paint.js'; +import LargestContentfulPaint from './largest-contentful-paint.js'; +import LargestContentfulPaintAllFrames from './largest-contentful-paint-all-frames.js'; +import Interactive from './interactive.js'; +import CumulativeLayoutShift from './cumulative-layout-shift.js'; +import SpeedIndex from './speed-index.js'; +import MaxPotentialFID from './max-potential-fid.js'; +import TotalBlockingTime from './total-blocking-time.js'; +import {makeComputedArtifact} from '../computed-artifact.js'; class TimingSummary { /** @@ -151,7 +151,7 @@ class TimingSummary { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( TimingSummary, ['devtoolsLog', 'gatherContext', 'settings', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/metrics/total-blocking-time.js b/lighthouse-core/computed/metrics/total-blocking-time.js index eb9faa7c669a..a7c3b7d0aa77 100644 --- a/lighthouse-core/computed/metrics/total-blocking-time.js +++ b/lighthouse-core/computed/metrics/total-blocking-time.js @@ -5,12 +5,12 @@ */ 'use strict'; -const makeComputedArtifact = require('../computed-artifact.js'); -const ComputedMetric = require('./metric.js'); -const TraceProcessor = require('../../lib/tracehouse/trace-processor.js'); -const LanternTotalBlockingTime = require('./lantern-total-blocking-time.js'); -const TimetoInteractive = require('./interactive.js'); -const {calculateSumOfBlockingTime} = require('./tbt-utils.js'); +import {makeComputedArtifact} from '../computed-artifact.js'; +import ComputedMetric from './metric.js'; +import {TraceProcessor} from '../../lib/tracehouse/trace-processor.js'; +import LanternTotalBlockingTime from './lantern-total-blocking-time.js'; +import TimetoInteractive from './interactive.js'; +import {calculateSumOfBlockingTime} from './tbt-utils.js'; /** * @fileoverview This audit determines Total Blocking Time. @@ -68,7 +68,7 @@ class TotalBlockingTime extends ComputedMetric { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( TotalBlockingTime, ['devtoolsLog', 'gatherContext', 'settings', 'simulator', 'trace', 'URL'] ); diff --git a/lighthouse-core/computed/module-duplication.js b/lighthouse-core/computed/module-duplication.js index 18812702c146..9ad61262f53f 100644 --- a/lighthouse-core/computed/module-duplication.js +++ b/lighthouse-core/computed/module-duplication.js @@ -5,8 +5,8 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const JsBundles = require('./js-bundles.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import JsBundles from './js-bundles.js'; const RELATIVE_SIZE_THRESHOLD = 0.1; const ABSOLUTE_SIZE_THRESHOLD_BYTES = 1024 * 0.5; @@ -134,4 +134,4 @@ class ModuleDuplication { } } -module.exports = makeComputedArtifact(ModuleDuplication, ['Scripts', 'SourceMaps']); +export default makeComputedArtifact(ModuleDuplication, ['Scripts', 'SourceMaps']); diff --git a/lighthouse-core/computed/network-analysis.js b/lighthouse-core/computed/network-analysis.js index 6d10dc15ad49..40183d15c0c6 100644 --- a/lighthouse-core/computed/network-analysis.js +++ b/lighthouse-core/computed/network-analysis.js @@ -5,9 +5,9 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const NetworkAnalyzer = require('../lib/dependency-graph/simulator/network-analyzer.js'); -const NetworkRecords = require('./network-records.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import {NetworkAnalyzer} from '../lib/dependency-graph/simulator/network-analyzer.js'; +import NetworkRecords from './network-records.js'; class NetworkAnalysis { /** @@ -61,4 +61,4 @@ class NetworkAnalysis { } } -module.exports = makeComputedArtifact(NetworkAnalysis, null); +export default makeComputedArtifact(NetworkAnalysis, null); diff --git a/lighthouse-core/computed/network-records.js b/lighthouse-core/computed/network-records.js index 361a3f73b930..e0a02e7aa0f0 100644 --- a/lighthouse-core/computed/network-records.js +++ b/lighthouse-core/computed/network-records.js @@ -5,8 +5,8 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const NetworkRecorder = require('../lib/network-recorder.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import {NetworkRecorder} from '../lib/network-recorder.js'; class NetworkRecords { /** @@ -18,4 +18,4 @@ class NetworkRecords { } } -module.exports = makeComputedArtifact(NetworkRecords, null); +export default makeComputedArtifact(NetworkRecords, null); diff --git a/lighthouse-core/computed/page-dependency-graph.js b/lighthouse-core/computed/page-dependency-graph.js index f1084d9a61e1..2a50641b874b 100644 --- a/lighthouse-core/computed/page-dependency-graph.js +++ b/lighthouse-core/computed/page-dependency-graph.js @@ -5,14 +5,14 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const NetworkNode = require('../lib/dependency-graph/network-node.js'); -const CPUNode = require('../lib/dependency-graph/cpu-node.js'); -const TracingProcessor = require('../lib/tracehouse/trace-processor.js'); -const NetworkRequest = require('../lib/network-request.js'); -const ProcessedTrace = require('./processed-trace.js'); -const NetworkRecords = require('./network-records.js'); -const NetworkAnalyzer = require('../lib/dependency-graph/simulator/network-analyzer.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import {NetworkNode} from '../lib/dependency-graph/network-node.js'; +import {CPUNode} from '../lib/dependency-graph/cpu-node.js'; +import {TraceProcessor} from '../lib/tracehouse/trace-processor.js'; +import {NetworkRequest} from '../lib/network-request.js'; +import ProcessedTrace from './processed-trace.js'; +import NetworkRecords from './network-records.js'; +import {NetworkAnalyzer} from '../lib/dependency-graph/simulator/network-analyzer.js'; /** @typedef {import('../lib/dependency-graph/base-node.js').Node} Node */ /** @typedef {Omit<LH.Artifacts['URL'], 'initialUrl'|'finalUrl'>} URLArtifact */ @@ -111,14 +111,14 @@ class PageDependencyGraph { const nodes = []; let i = 0; - TracingProcessor.assertHasToplevelEvents(mainThreadEvents); + TraceProcessor.assertHasToplevelEvents(mainThreadEvents); while (i < mainThreadEvents.length) { const evt = mainThreadEvents[i]; i++; // Skip all trace events that aren't schedulable tasks with sizable duration - if (!TracingProcessor.isScheduleableTask(evt) || !evt.dur) { + if (!TraceProcessor.isScheduleableTask(evt) || !evt.dur) { continue; } @@ -504,7 +504,7 @@ class PageDependencyGraph { } } -module.exports = makeComputedArtifact(PageDependencyGraph, ['devtoolsLog', 'trace', 'URL']); +export default makeComputedArtifact(PageDependencyGraph, ['devtoolsLog', 'trace', 'URL']); /** * @typedef {Object} NetworkNodeOutput diff --git a/lighthouse-core/computed/processed-navigation.js b/lighthouse-core/computed/processed-navigation.js index bb7f00a3bcd3..58b5413c3704 100644 --- a/lighthouse-core/computed/processed-navigation.js +++ b/lighthouse-core/computed/processed-navigation.js @@ -5,8 +5,8 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const LHTraceProcessor = require('../lib/lh-trace-processor.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import LHTraceProcessor from '../lib/lh-trace-processor.js'; class ProcessedNavigation { /** @@ -18,4 +18,4 @@ class ProcessedNavigation { } } -module.exports = makeComputedArtifact(ProcessedNavigation, null); +export default makeComputedArtifact(ProcessedNavigation, null); diff --git a/lighthouse-core/computed/processed-trace.js b/lighthouse-core/computed/processed-trace.js index c66a20f645d0..8b88241f9c39 100644 --- a/lighthouse-core/computed/processed-trace.js +++ b/lighthouse-core/computed/processed-trace.js @@ -5,8 +5,8 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const LHTraceProcessor = require('../lib/lh-trace-processor.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import LHTraceProcessor from '../lib/lh-trace-processor.js'; class ProcessedTrace { /** @@ -18,4 +18,4 @@ class ProcessedTrace { } } -module.exports = makeComputedArtifact(ProcessedTrace, null); +export default makeComputedArtifact(ProcessedTrace, null); diff --git a/lighthouse-core/computed/resource-summary.js b/lighthouse-core/computed/resource-summary.js index 8e3f27d0f9fc..61e905d322a6 100644 --- a/lighthouse-core/computed/resource-summary.js +++ b/lighthouse-core/computed/resource-summary.js @@ -5,12 +5,12 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const NetworkRecords = require('./network-records.js'); -const URL = require('../lib/url-shim.js'); -const NetworkRequest = require('../lib/network-request.js'); -const Budget = require('../config/budget.js'); -const {Util} = require('../util-commonjs.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import NetworkRecords from './network-records.js'; +import URL from '../lib/url-shim.js'; +import {NetworkRequest} from '../lib/network-request.js'; +import {Budget} from '../config/budget.js'; +import {Util} from '../util.cjs'; /** @typedef {{count: number, resourceSize: number, transferSize: number}} ResourceEntry */ @@ -111,4 +111,4 @@ class ResourceSummary { } } -module.exports = makeComputedArtifact(ResourceSummary, ['URL', 'devtoolsLog', 'budgets']); +export default makeComputedArtifact(ResourceSummary, ['URL', 'devtoolsLog', 'budgets']); diff --git a/lighthouse-core/computed/screenshots.js b/lighthouse-core/computed/screenshots.js index 8c76aef4679c..e114e0fbf8ed 100644 --- a/lighthouse-core/computed/screenshots.js +++ b/lighthouse-core/computed/screenshots.js @@ -5,7 +5,7 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); +import {makeComputedArtifact} from './computed-artifact.js'; const SCREENSHOT_TRACE_NAME = 'Screenshot'; @@ -26,4 +26,4 @@ class Screenshots { } } -module.exports = makeComputedArtifact(Screenshots, null); +export default makeComputedArtifact(Screenshots, null); diff --git a/lighthouse-core/computed/speedline.js b/lighthouse-core/computed/speedline.js index 977448b5a7d8..ff0c9f912e8e 100644 --- a/lighthouse-core/computed/speedline.js +++ b/lighthouse-core/computed/speedline.js @@ -5,10 +5,10 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const speedline = require('speedline-core'); -const LighthouseError = require('../lib/lh-error.js'); -const ProcessedTrace = require('./processed-trace.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import speedline from 'speedline-core'; +import {LighthouseError} from '../lib/lh-error.js'; +import ProcessedTrace from './processed-trace.js'; class Speedline { /** @@ -51,4 +51,4 @@ class Speedline { } } -module.exports = makeComputedArtifact(Speedline, null); +export default makeComputedArtifact(Speedline, null); diff --git a/lighthouse-core/computed/trace-of-tab.js b/lighthouse-core/computed/trace-of-tab.js index ff600b1782ec..48ff48b42437 100644 --- a/lighthouse-core/computed/trace-of-tab.js +++ b/lighthouse-core/computed/trace-of-tab.js @@ -7,10 +7,11 @@ /** @fileoverview This file is no longer used internally, but remains here for backcompat with plugins. */ -const log = require('lighthouse-logger'); -const makeComputedArtifact = require('./computed-artifact.js'); -const ProcessedTrace = require('./processed-trace.js'); -const ProcessedNavigation = require('./processed-navigation.js'); +import log from 'lighthouse-logger'; + +import {makeComputedArtifact} from './computed-artifact.js'; +import ProcessedTrace from './processed-trace.js'; +import ProcessedNavigation from './processed-navigation.js'; class TraceOfTab { /** @@ -26,5 +27,5 @@ class TraceOfTab { } log.warn(`trace-of-tab`, `trace-of-tab is deprecated, use processed-trace / processed-navigation instead`); // eslint-disable-line max-len -module.exports = makeComputedArtifact(TraceOfTab, null); +export default makeComputedArtifact(TraceOfTab, null); diff --git a/lighthouse-core/computed/unused-css.js b/lighthouse-core/computed/unused-css.js index 7f1227f48609..3dd97026fd10 100644 --- a/lighthouse-core/computed/unused-css.js +++ b/lighthouse-core/computed/unused-css.js @@ -5,9 +5,9 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const ByteEfficiencyAudit = require('../audits/byte-efficiency/byte-efficiency-audit.js'); -const NetworkRecords = require('./network-records.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import {ByteEfficiencyAudit} from '../audits/byte-efficiency/byte-efficiency-audit.js'; +import NetworkRecords from './network-records.js'; const PREVIEW_LENGTH = 100; @@ -150,4 +150,4 @@ class UnusedCSS { } } -module.exports = makeComputedArtifact(UnusedCSS, ['CSSUsage', 'devtoolsLog']); +export default makeComputedArtifact(UnusedCSS, ['CSSUsage', 'devtoolsLog']); diff --git a/lighthouse-core/computed/unused-javascript-summary.js b/lighthouse-core/computed/unused-javascript-summary.js index 72db19b20c93..061221ac5dad 100644 --- a/lighthouse-core/computed/unused-javascript-summary.js +++ b/lighthouse-core/computed/unused-javascript-summary.js @@ -5,7 +5,7 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); +import {makeComputedArtifact} from './computed-artifact.js'; /** * @typedef WasteData @@ -149,7 +149,7 @@ class UnusedJavascriptSummary { } } -module.exports = makeComputedArtifact( +export default makeComputedArtifact( UnusedJavascriptSummary, ['bundle', 'scriptCoverage', 'scriptId'] ); diff --git a/lighthouse-core/computed/user-timings.js b/lighthouse-core/computed/user-timings.js index 7bc5fe271d46..b602fbd96569 100644 --- a/lighthouse-core/computed/user-timings.js +++ b/lighthouse-core/computed/user-timings.js @@ -5,8 +5,8 @@ */ 'use strict'; -const makeComputedArtifact = require('./computed-artifact.js'); -const ProcessedTrace = require('./processed-trace.js'); +import {makeComputedArtifact} from './computed-artifact.js'; +import ProcessedTrace from './processed-trace.js'; /** @typedef {{name: string, isMark: true, args: LH.TraceEvent['args'], startTime: number}} MarkEvent */ /** @typedef {{name: string, isMark: false, args: LH.TraceEvent['args'], startTime: number, endTime: number, duration: number}} MeasureEvent */ @@ -80,4 +80,4 @@ class UserTimings { } } -module.exports = makeComputedArtifact(UserTimings, null); +export default makeComputedArtifact(UserTimings, null); diff --git a/lighthouse-core/computed/viewport-meta.js b/lighthouse-core/computed/viewport-meta.js index 55598de5f5fe..f8239e4b25f0 100644 --- a/lighthouse-core/computed/viewport-meta.js +++ b/lighthouse-core/computed/viewport-meta.js @@ -5,9 +5,8 @@ */ 'use strict'; -const Parser = require('metaviewport-parser'); - -const makeComputedArtifact = require('./computed-artifact.js'); +import Parser from 'metaviewport-parser'; +import {makeComputedArtifact} from './computed-artifact.js'; class ViewportMeta { /** @@ -46,7 +45,7 @@ class ViewportMeta { } } -module.exports = makeComputedArtifact(ViewportMeta, null); +export default makeComputedArtifact(ViewportMeta, null); /** * @typedef {object} ViewportMetaResult diff --git a/lighthouse-core/config/budget.js b/lighthouse-core/config/budget.js index 91f675438a7b..689d7edfeb3f 100644 --- a/lighthouse-core/config/budget.js +++ b/lighthouse-core/config/budget.js @@ -338,4 +338,4 @@ class Budget { } } -module.exports = Budget; +export {Budget}; diff --git a/lighthouse-core/config/config-helpers.js b/lighthouse-core/config/config-helpers.js index c6ac07ab44bd..d4c2d280014c 100644 --- a/lighthouse-core/config/config-helpers.js +++ b/lighthouse-core/config/config-helpers.js @@ -5,17 +5,21 @@ */ 'use strict'; -const path = require('path'); -const isDeepEqual = require('lodash/isEqual.js'); -const constants = require('./constants.js'); -const Budget = require('./budget.js'); -const ConfigPlugin = require('./config-plugin.js'); -const Runner = require('../runner.js'); -const i18n = require('../lib/i18n/i18n.js'); -const validation = require('../fraggle-rock/config/validation.js'); - -/** @typedef {typeof import('../gather/gatherers/gatherer.js')} GathererConstructor */ -/** @typedef {typeof import('../audits/audit.js')} Audit */ +import path from 'path'; +import {createRequire} from 'module'; +import isDeepEqual from 'lodash/isEqual.js'; +import * as constants from './constants.js'; +import {Budget} from './budget.js'; +import ConfigPlugin from './config-plugin.js'; +import {Runner} from '../runner.js'; +import * as i18n from '../lib/i18n/i18n.js'; +import * as validation from '../fraggle-rock/config/validation.js'; +import {getModuleDirectory} from '../../esm-utils.js'; + +const require = createRequire(import.meta.url); + +/** @typedef {typeof import('../gather/gatherers/gatherer.js').Gatherer} GathererConstructor */ +/** @typedef {typeof import('../audits/audit.js')['Audit']} Audit */ /** @typedef {InstanceType<GathererConstructor>} Gatherer */ function isBundledEnvironment() { @@ -203,17 +207,41 @@ function expandAuditShorthand(audit) { } } -/** @type {Map<string, any>} */ +/** @type {Map<string, Promise<any>>} */ const bundledModules = new Map(/* BUILD_REPLACE_BUNDLED_MODULES */); /** - * Wraps `require` with an entrypoint for bundled dynamic modules. + * Wraps `import`/`require` with an entrypoint for bundled dynamic modules. * See build-bundle.js * @param {string} requirePath */ async function requireWrapper(requirePath) { - // This is async because eventually this function needs to do async dynamic imports. - return bundledModules.get(requirePath) || require(requirePath); + /** @type {any} */ + let module; + if (bundledModules.has(requirePath)) { + module = await bundledModules.get(requirePath); + } else if (requirePath.match(/\.(js|mjs|cjs)$/)) { + module = await import(requirePath); + } else { + requirePath += '.js'; + module = await import(requirePath); + } + + if (module.default) return module.default; + + // Find a valid named export. + // TODO(esmodules): actually make all the audits/gatherers use named exports + const methods = new Set(['meta']); + const possibleNamedExports = Object.keys(module).filter(key => { + if (!(module[key] && module[key] instanceof Object)) return false; + return Object.getOwnPropertyNames(module[key]).some(method => methods.has(method)); + }); + if (possibleNamedExports.length === 1) return possibleNamedExports[0]; + if (possibleNamedExports.length > 1) { + throw new Error(`module '${requirePath}' has too many possible exports`); + } + + throw new Error(`module '${requirePath}' missing default export`); } /** @@ -259,7 +287,7 @@ function requireAudit(auditPath, coreAuditList, configDir) { // Otherwise, attempt to find it elsewhere. This throws if not found. const absolutePath = resolveModulePath(auditPath, configDir, 'audit'); // Use a relative path so bundler can easily expose it. - requirePath = path.relative(__dirname, absolutePath); + requirePath = path.relative(getModuleDirectory(import.meta), absolutePath); } } @@ -478,8 +506,8 @@ function resolveModulePath(moduleIdentifier, configDir, category) { const errorString = 'Unable to locate ' + (category ? `${category}: ` : '') + `\`${moduleIdentifier}\`. - Tried to require() from these locations: - ${__dirname} + Tried to resolve the module from these locations: + ${getModuleDirectory(import.meta)} ${cwdPath}`; if (!configDir) { @@ -592,7 +620,7 @@ function flagsToFRContext(flags) { }; } -module.exports = { +export { deepClone, deepCloneConfigJson, mergeConfigFragment, diff --git a/lighthouse-core/config/config-plugin.js b/lighthouse-core/config/config-plugin.js index 434474b027e1..8f38844108b3 100644 --- a/lighthouse-core/config/config-plugin.js +++ b/lighthouse-core/config/config-plugin.js @@ -5,7 +5,7 @@ */ 'use strict'; -const i18n = require('../lib/i18n/i18n.js'); +import * as i18n from '../lib/i18n/i18n.js'; /** * @param {unknown} arr @@ -248,4 +248,4 @@ class ConfigPlugin { } } -module.exports = ConfigPlugin; +export default ConfigPlugin; diff --git a/lighthouse-core/config/config.js b/lighthouse-core/config/config.js index e2cc45a545a1..41477e3e3456 100644 --- a/lighthouse-core/config/config.js +++ b/lighthouse-core/config/config.js @@ -5,16 +5,15 @@ */ 'use strict'; -const defaultConfigPath = './default-config.js'; -const defaultConfig = require('./default-config.js'); -const constants = require('./constants.js'); -const format = require('../../shared/localization/format.js'); -const validation = require('./../fraggle-rock/config/validation.js'); - -const log = require('lighthouse-logger'); -const path = require('path'); -const Runner = require('../runner.js'); -const { +import defaultConfig from './default-config.js'; +import * as constants from './constants.js'; +import format from '../../shared/localization/format.js'; +import * as validation from './../fraggle-rock/config/validation.js'; +import log from 'lighthouse-logger'; +import path from 'path'; +import {Runner} from '../runner.js'; + +import { mergePlugins, mergeConfigFragment, resolveSettings, @@ -22,9 +21,12 @@ const { resolveGathererToDefn, deepClone, deepCloneConfigJson, -} = require('./config-helpers.js'); +} from './config-helpers.js'; +import {getModuleDirectory} from '../../esm-utils.js'; + +const defaultConfigPath = './default-config.js'; -/** @typedef {typeof import('../gather/gatherers/gatherer.js')} GathererConstructor */ +/** @typedef {typeof import('../gather/gatherers/gatherer.js').Gatherer} GathererConstructor */ /** @typedef {InstanceType<GathererConstructor>} Gatherer */ /** @@ -167,7 +169,7 @@ class Config { if (!configJSON) { configJSON = defaultConfig; - configPath = path.resolve(__dirname, defaultConfigPath); + configPath = path.resolve(getModuleDirectory(import.meta), defaultConfigPath); } if (configPath && !path.isAbsolute(configPath)) { @@ -559,4 +561,4 @@ class Config { } } -module.exports = Config; +export {Config}; diff --git a/lighthouse-core/config/constants.js b/lighthouse-core/config/constants.js index 17c3a99490a9..9f2f582410e5 100644 --- a/lighthouse-core/config/constants.js +++ b/lighthouse-core/config/constants.js @@ -158,7 +158,7 @@ const nonSimulatedPassConfigOverrides = { cpuQuietThresholdMs: 5250, }; -module.exports = { +export { throttling, screenEmulationMetrics, userAgents, diff --git a/lighthouse-core/config/default-config.js b/lighthouse-core/config/default-config.js index 359187f854d2..3633f3319ee4 100644 --- a/lighthouse-core/config/default-config.js +++ b/lighthouse-core/config/default-config.js @@ -7,9 +7,10 @@ /* eslint-disable max-len */ -const constants = require('./constants.js'); -const i18n = require('../lib/i18n/i18n.js'); -const m2a = require('./metrics-to-audits.js'); +import * as constants from './constants.js'; + +import * as i18n from '../lib/i18n/i18n.js'; +import {metricsToAudits} from './metrics-to-audits.js'; const UIStrings = { /** Title of the Performance category of audits. Equivalent to 'Web performance', this term is inclusive of all web page speed and loading optimization topics. Also used as a label of a score gauge; try to limit to 20 characters. */ @@ -120,7 +121,7 @@ const UIStrings = { pwaOptimizedGroupTitle: 'PWA Optimized', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @type {LH.Config.Json} */ const defaultConfig = { @@ -413,12 +414,12 @@ const defaultConfig = { title: str_(UIStrings.performanceCategoryTitle), supportedModes: ['navigation', 'timespan', 'snapshot'], auditRefs: [ - {id: 'first-contentful-paint', weight: 10, group: 'metrics', acronym: 'FCP', relevantAudits: m2a.fcpRelevantAudits}, + {id: 'first-contentful-paint', weight: 10, group: 'metrics', acronym: 'FCP', relevantAudits: metricsToAudits.fcpRelevantAudits}, {id: 'interactive', weight: 10, group: 'metrics', acronym: 'TTI'}, {id: 'speed-index', weight: 10, group: 'metrics', acronym: 'SI'}, - {id: 'total-blocking-time', weight: 30, group: 'metrics', acronym: 'TBT', relevantAudits: m2a.tbtRelevantAudits}, - {id: 'largest-contentful-paint', weight: 25, group: 'metrics', acronym: 'LCP', relevantAudits: m2a.lcpRelevantAudits}, - {id: 'cumulative-layout-shift', weight: 15, group: 'metrics', acronym: 'CLS', relevantAudits: m2a.clsRelevantAudits}, + {id: 'total-blocking-time', weight: 30, group: 'metrics', acronym: 'TBT', relevantAudits: metricsToAudits.tbtRelevantAudits}, + {id: 'largest-contentful-paint', weight: 25, group: 'metrics', acronym: 'LCP', relevantAudits: metricsToAudits.lcpRelevantAudits}, + {id: 'cumulative-layout-shift', weight: 15, group: 'metrics', acronym: 'CLS', relevantAudits: metricsToAudits.clsRelevantAudits}, // These are our "invisible" metrics. Not displayed, but still in the LHR. {id: 'max-potential-fid', weight: 0, group: 'hidden'}, @@ -624,10 +625,10 @@ const defaultConfig = { }, }; -module.exports = defaultConfig; +export default defaultConfig; // Use `defineProperty` so that the strings are accesible from original but ignored when we copy it -Object.defineProperty(module.exports, 'UIStrings', { +Object.defineProperty(defaultConfig, 'UIStrings', { enumerable: false, get: () => UIStrings, }); diff --git a/lighthouse-core/config/desktop-config.js b/lighthouse-core/config/desktop-config.js index 2703b4d9b645..fc8bc4560fac 100644 --- a/lighthouse-core/config/desktop-config.js +++ b/lighthouse-core/config/desktop-config.js @@ -5,7 +5,7 @@ */ 'use strict'; -const constants = require('./constants.js'); +import * as constants from './constants.js'; /** @type {LH.Config.Json} */ const config = { @@ -18,4 +18,4 @@ const config = { }, }; -module.exports = config; +export default config; diff --git a/lighthouse-core/config/experimental-config.js b/lighthouse-core/config/experimental-config.js index 5671f5f43cf5..a382a5dbe67e 100644 --- a/lighthouse-core/config/experimental-config.js +++ b/lighthouse-core/config/experimental-config.js @@ -27,4 +27,4 @@ const config = { }, }; -module.exports = config; +export default config; diff --git a/lighthouse-core/config/full-config.js b/lighthouse-core/config/full-config.js index e8a202ae0c3f..c8cbe77c0fab 100644 --- a/lighthouse-core/config/full-config.js +++ b/lighthouse-core/config/full-config.js @@ -11,4 +11,4 @@ const fullConfig = { settings: {}, }; -module.exports = fullConfig; +export default fullConfig; diff --git a/lighthouse-core/config/lr-desktop-config.js b/lighthouse-core/config/lr-desktop-config.js index 04f164c88d5c..d25c4969d8f1 100644 --- a/lighthouse-core/config/lr-desktop-config.js +++ b/lighthouse-core/config/lr-desktop-config.js @@ -5,7 +5,7 @@ */ 'use strict'; -const constants = require('./constants.js'); +import * as constants from './constants.js'; /** @type {LH.Config.Json} */ const config = { @@ -22,4 +22,4 @@ const config = { }, }; -module.exports = config; +export default config; diff --git a/lighthouse-core/config/lr-mobile-config.js b/lighthouse-core/config/lr-mobile-config.js index 7c6af55a17c2..4bcf28ca5c67 100644 --- a/lighthouse-core/config/lr-mobile-config.js +++ b/lighthouse-core/config/lr-mobile-config.js @@ -28,4 +28,4 @@ const config = { }, }; -module.exports = config; +export default config; diff --git a/lighthouse-core/config/metrics-to-audits.js b/lighthouse-core/config/metrics-to-audits.js index e1348a54f96d..f1b48df2c961 100644 --- a/lighthouse-core/config/metrics-to-audits.js +++ b/lighthouse-core/config/metrics-to-audits.js @@ -52,7 +52,7 @@ const inpRelevantAudits = [ 'work-during-interaction', ]; -module.exports = { +export const metricsToAudits = { fcpRelevantAudits, lcpRelevantAudits, tbtRelevantAudits, diff --git a/lighthouse-core/config/perf-config.js b/lighthouse-core/config/perf-config.js index 0e6f5903823f..ee9a98d95295 100644 --- a/lighthouse-core/config/perf-config.js +++ b/lighthouse-core/config/perf-config.js @@ -14,4 +14,4 @@ const perfConfig = { }, }; -module.exports = perfConfig; +export default perfConfig; diff --git a/lighthouse-core/fraggle-rock/api.js b/lighthouse-core/fraggle-rock/api.js index 57ab155580dd..7d1fcc9dbbfc 100644 --- a/lighthouse-core/fraggle-rock/api.js +++ b/lighthouse-core/fraggle-rock/api.js @@ -5,12 +5,12 @@ */ 'use strict'; -const {UserFlow, auditGatherSteps} = require('./user-flow.js'); -const {snapshotGather} = require('./gather/snapshot-runner.js'); -const {startTimespanGather} = require('./gather/timespan-runner.js'); -const {navigationGather} = require('./gather/navigation-runner.js'); -const {generateFlowReportHtml} = require('../../report/generator/report-generator.js'); -const Runner = require('../runner.js'); +import {UserFlow, auditGatherSteps} from './user-flow.js'; +import {snapshotGather} from './gather/snapshot-runner.js'; +import {startTimespanGather} from './gather/timespan-runner.js'; +import {navigationGather} from './gather/navigation-runner.js'; +import ReportGenerator from '../../report/generator/report-generator.js'; +import {Runner} from '../runner.js'; /** * @param {LH.Puppeteer.Page} page @@ -55,7 +55,7 @@ async function startTimespan(...params) { * @param {LH.FlowResult} flowResult */ async function generateFlowReport(flowResult) { - return generateFlowReportHtml(flowResult); + return ReportGenerator.generateFlowReportHtml(flowResult); } /** @@ -67,7 +67,7 @@ async function auditFlowArtifacts(flowArtifacts, config) { return await auditGatherSteps(gatherSteps, {name, config}); } -module.exports = { +export { snapshot, startTimespan, navigation, diff --git a/lighthouse-core/fraggle-rock/config/config.js b/lighthouse-core/fraggle-rock/config/config.js index 2241476f990e..f51547d62fd0 100644 --- a/lighthouse-core/fraggle-rock/config/config.js +++ b/lighthouse-core/fraggle-rock/config/config.js @@ -5,22 +5,24 @@ */ 'use strict'; -const path = require('path'); -const log = require('lighthouse-logger'); -const Runner = require('../../runner.js'); -const format = require('../../../shared/localization/format.js'); -const defaultConfig = require('./default-config.js'); -const {defaultNavigationConfig, nonSimulatedPassConfigOverrides} = require('../../config/constants.js'); // eslint-disable-line max-len -const { +import path from 'path'; +import log from 'lighthouse-logger'; +import {Runner} from '../../runner.js'; +import defaultConfig from './default-config.js'; +import {defaultNavigationConfig, nonSimulatedPassConfigOverrides} from '../../config/constants.js'; // eslint-disable-line max-len + +import { isFRGathererDefn, throwInvalidDependencyOrder, isValidArtifactDependency, throwInvalidArtifactDependency, assertArtifactTopologicalOrder, assertValidConfig, -} = require('./validation.js'); -const {filterConfigByGatherMode, filterConfigByExplicitFilters} = require('./filters.js'); -const { +} from './validation.js'; + +import {filterConfigByGatherMode, filterConfigByExplicitFilters} from './filters.js'; + +import { deepCloneConfigJson, resolveSettings, resolveAuditsToDefns, @@ -28,8 +30,12 @@ const { mergePlugins, mergeConfigFragment, mergeConfigFragmentArrayByKey, -} = require('../../config/config-helpers.js'); -const defaultConfigPath = path.join(__dirname, './default-config.js'); +} from '../../config/config-helpers.js'; + +import {getModuleDirectory} from '../../../esm-utils.js'; +import * as format from '../../../shared/localization/format.js'; + +const defaultConfigPath = path.join(getModuleDirectory(import.meta), './default-config.js'); /** @typedef {LH.Config.FRContext & {gatherMode: LH.Gatherer.GatherMode}} ConfigContext */ @@ -134,7 +140,8 @@ async function resolveArtifactsToDefns(artifacts, configDir) { const artifactDefnsBySymbol = new Map(); const coreGathererList = Runner.getGathererList(); - const artifactDefnsPromises = artifacts.map(async (artifactJson) => { + const artifactDefns = []; + for (const artifactJson of artifacts) { /** @type {LH.Config.GathererJson} */ // @ts-expect-error - remove when legacy runner path is removed. const gathererJson = artifactJson.gatherer; @@ -155,9 +162,8 @@ async function resolveArtifactsToDefns(artifacts, configDir) { const symbol = artifact.gatherer.instance.meta.symbol; if (symbol) artifactDefnsBySymbol.set(symbol, artifact); - return artifact; - }); - const artifactDefns = await Promise.all(artifactDefnsPromises); + artifactDefns.push(artifact); + } log.timeEnd(status); return artifactDefns; @@ -323,4 +329,8 @@ function getConfigDisplayString(config) { return JSON.stringify(jsonConfig, null, 2); } -module.exports = {resolveWorkingCopy, initializeConfig, getConfigDisplayString}; +export { + resolveWorkingCopy, + initializeConfig, + getConfigDisplayString, +}; diff --git a/lighthouse-core/fraggle-rock/config/default-config.js b/lighthouse-core/fraggle-rock/config/default-config.js index 333d526e0af9..7b3a1f4c97e5 100644 --- a/lighthouse-core/fraggle-rock/config/default-config.js +++ b/lighthouse-core/fraggle-rock/config/default-config.js @@ -5,9 +5,9 @@ */ 'use strict'; -const legacyDefaultConfig = require('../../config/default-config.js'); -const m2a = require('../../config/metrics-to-audits.js'); -const {deepClone} = require('../../config/config-helpers.js'); +import legacyDefaultConfig from '../../config/default-config.js'; +import {deepClone} from '../../config/config-helpers.js'; +import {metricsToAudits} from '../../config/metrics-to-audits.js'; /** @type {LH.Config.AuditJson[]} */ const frAudits = [ @@ -21,7 +21,7 @@ const frCategoryAuditRefExtensions = { 'performance': [ {id: 'uses-responsive-images-snapshot', weight: 0}, {id: 'experimental-interaction-to-next-paint', weight: 0, group: 'metrics', acronym: 'INP', - relevantAudits: m2a.inpRelevantAudits}, + relevantAudits: metricsToAudits.inpRelevantAudits}, {id: 'work-during-interaction', weight: 0}, ], }; @@ -205,4 +205,4 @@ const defaultConfig = { groups: legacyDefaultConfig.groups, }; -module.exports = defaultConfig; +export default defaultConfig; diff --git a/lighthouse-core/fraggle-rock/config/filters.js b/lighthouse-core/fraggle-rock/config/filters.js index f4beff315096..8d9a76dd8390 100644 --- a/lighthouse-core/fraggle-rock/config/filters.js +++ b/lighthouse-core/fraggle-rock/config/filters.js @@ -5,9 +5,8 @@ */ 'use strict'; -const log = require('lighthouse-logger'); - -const Audit = require('../../audits/audit.js'); +import log from 'lighthouse-logger'; +import {Audit} from '../../audits/audit.js'; /** @type {Record<keyof LH.FRBaseArtifacts, string>} */ const baseArtifactKeySource = { @@ -324,7 +323,7 @@ function filterConfigByExplicitFilters(config, filters) { }; } -module.exports = { +export { filterConfigByGatherMode, filterConfigByExplicitFilters, filterArtifactsByGatherMode, diff --git a/lighthouse-core/fraggle-rock/config/validation.js b/lighthouse-core/fraggle-rock/config/validation.js index d24a7724d66e..971fa3258183 100644 --- a/lighthouse-core/fraggle-rock/config/validation.js +++ b/lighthouse-core/fraggle-rock/config/validation.js @@ -5,9 +5,9 @@ */ 'use strict'; -const Audit = require('../../audits/audit.js'); -const BaseFRGatherer = require('../gather/base-gatherer.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import {Audit} from '../../audits/audit.js'; +import BaseFRGatherer from '../gather/base-gatherer.js'; +import * as i18n from '../../lib/i18n/i18n.js'; /** * @param {LH.Config.GathererDefn | LH.Config.AnyFRGathererDefn} gathererDefn @@ -297,7 +297,7 @@ function throwInvalidArtifactDependency(artifactId, dependencyKey) { ); } -module.exports = { +export { isFRGathererDefn, isValidArtifactDependency, assertValidPluginName, diff --git a/lighthouse-core/fraggle-rock/gather/base-artifacts.js b/lighthouse-core/fraggle-rock/gather/base-artifacts.js index f616b6a64841..4c4744d58c02 100644 --- a/lighthouse-core/fraggle-rock/gather/base-artifacts.js +++ b/lighthouse-core/fraggle-rock/gather/base-artifacts.js @@ -5,13 +5,11 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const isDeepEqual = require('lodash/isEqual.js'); -const { - getBrowserVersion, - getBenchmarkIndex, - getEnvironmentWarnings, -} = require('../../gather/driver/environment.js'); +import log from 'lighthouse-logger'; +import isDeepEqual from 'lodash/isEqual.js'; +import { + getBrowserVersion, getBenchmarkIndex, getEnvironmentWarnings, +} from '../../gather/driver/environment.js'; /** * @param {LH.Config.FRConfig} config @@ -96,7 +94,7 @@ function finalizeArtifacts(baseArtifacts, gathererArtifacts) { return artifacts; } -module.exports = { +export { getBaseArtifacts, finalizeArtifacts, }; diff --git a/lighthouse-core/fraggle-rock/gather/base-gatherer.js b/lighthouse-core/fraggle-rock/gather/base-gatherer.js index 471d8f57611b..6db4be913d27 100644 --- a/lighthouse-core/fraggle-rock/gather/base-gatherer.js +++ b/lighthouse-core/fraggle-rock/gather/base-gatherer.js @@ -104,4 +104,5 @@ class FRGatherer { } } -module.exports = FRGatherer; +// TODO(esmodules): do not use default export +export default FRGatherer; diff --git a/lighthouse-core/fraggle-rock/gather/driver.js b/lighthouse-core/fraggle-rock/gather/driver.js index 00def9d384d4..7c34ba574a06 100644 --- a/lighthouse-core/fraggle-rock/gather/driver.js +++ b/lighthouse-core/fraggle-rock/gather/driver.js @@ -5,10 +5,10 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const ExecutionContext = require('../../gather/driver/execution-context.js'); -const Fetcher = require('../../gather/fetcher.js'); -const TargetManager = require('../../gather/driver/target-manager.js'); +import log from 'lighthouse-logger'; +import {ExecutionContext} from '../../gather/driver/execution-context.js'; +import {TargetManager} from '../../gather/driver/target-manager.js'; +import {Fetcher} from '../../gather/fetcher.js'; /** @return {*} */ const throwNotConnectedFn = () => { @@ -89,4 +89,4 @@ class Driver { } } -module.exports = Driver; +export {Driver}; diff --git a/lighthouse-core/fraggle-rock/gather/navigation-runner.js b/lighthouse-core/fraggle-rock/gather/navigation-runner.js index eb838abcb3d9..2792f4300392 100644 --- a/lighthouse-core/fraggle-rock/gather/navigation-runner.js +++ b/lighthouse-core/fraggle-rock/gather/navigation-runner.js @@ -5,29 +5,25 @@ */ 'use strict'; -const puppeteer = require('puppeteer-core'); -const log = require('lighthouse-logger'); -const Driver = require('./driver.js'); -const Runner = require('../../runner.js'); -const { - getEmptyArtifactState, - collectPhaseArtifacts, - awaitArtifacts, -} = require('./runner-helpers.js'); -const prepare = require('../../gather/driver/prepare.js'); -const {gotoURL} = require('../../gather/driver/navigation.js'); -const storage = require('../../gather/driver/storage.js'); -const emulation = require('../../lib/emulation.js'); -const {defaultNavigationConfig} = require('../../config/constants.js'); -const {initializeConfig} = require('../config/config.js'); -const {getBaseArtifacts, finalizeArtifacts} = require('./base-artifacts.js'); -const format = require('../../../shared/localization/format.js'); -const LighthouseError = require('../../lib/lh-error.js'); -const URL = require('../../lib/url-shim.js'); -const {getPageLoadError} = require('../../lib/navigation-error.js'); -const Trace = require('../../gather/gatherers/trace.js'); -const DevtoolsLog = require('../../gather/gatherers/devtools-log.js'); -const NetworkRecords = require('../../computed/network-records.js'); +import puppeteer from 'puppeteer-core'; +import log from 'lighthouse-logger'; +import {Driver} from './driver.js'; +import {Runner} from '../../runner.js'; +import {getEmptyArtifactState, collectPhaseArtifacts, awaitArtifacts} from './runner-helpers.js'; +import * as prepare from '../../gather/driver/prepare.js'; +import {gotoURL} from '../../gather/driver/navigation.js'; +import * as storage from '../../gather/driver/storage.js'; +import * as emulation from '../../lib/emulation.js'; +import {defaultNavigationConfig} from '../../config/constants.js'; +import {initializeConfig} from '../config/config.js'; +import {getBaseArtifacts, finalizeArtifacts} from './base-artifacts.js'; +import format from '../../../shared/localization/format.js'; +import {LighthouseError} from '../../lib/lh-error.js'; +import URL from '../../lib/url-shim.js'; +import {getPageLoadError} from '../../lib/navigation-error.js'; +import Trace from '../../gather/gatherers/trace.js'; +import DevtoolsLog from '../../gather/gatherers/devtools-log.js'; +import NetworkRecords from '../../computed/network-records.js'; /** @typedef {{skipAboutBlank?: boolean}} InternalOptions */ @@ -148,11 +144,11 @@ async function _collectDebugData(navigationContext, phaseState) { const getArtifactState = phaseState.artifactState.getArtifact; const devtoolsLogArtifactId = devtoolsLogArtifactDefn?.id; - const devtoolsLog = devtoolsLogArtifactId && await getArtifactState[devtoolsLogArtifactId]; - const records = devtoolsLog && await NetworkRecords.request(devtoolsLog, navigationContext); + const devtoolsLog = devtoolsLogArtifactId && (await getArtifactState[devtoolsLogArtifactId]); + const records = devtoolsLog && (await NetworkRecords.request(devtoolsLog, navigationContext)); const traceArtifactId = traceArtifactDefn?.id; - const trace = traceArtifactId && await getArtifactState[traceArtifactId]; + const trace = traceArtifactId && (await getArtifactState[traceArtifactId]); return {devtoolsLog, records, trace}; } @@ -356,7 +352,7 @@ async function navigationGather(requestor, options) { return {artifacts, runnerOptions}; } -module.exports = { +export { navigationGather, _setup, _setupNavigation, diff --git a/lighthouse-core/fraggle-rock/gather/runner-helpers.js b/lighthouse-core/fraggle-rock/gather/runner-helpers.js index ee8ac4fa5bb7..2792cca924ac 100644 --- a/lighthouse-core/fraggle-rock/gather/runner-helpers.js +++ b/lighthouse-core/fraggle-rock/gather/runner-helpers.js @@ -7,7 +7,7 @@ /** * @typedef CollectPhaseArtifactOptions - * @property {import('./driver.js')} driver + * @property {import('./driver.js').Driver} driver * @property {Array<LH.Config.AnyArtifactDefn>} artifactDefinitions * @property {ArtifactState} artifactState * @property {LH.FRBaseArtifacts} baseArtifacts @@ -23,7 +23,7 @@ /** @typedef {LH.Gatherer.FRTransitionalContext<LH.Gatherer.DependencyKey>['dependencies']} Dependencies */ -const log = require('lighthouse-logger'); +import log from 'lighthouse-logger'; /** * @@ -149,7 +149,7 @@ async function awaitArtifacts(artifactState) { return artifacts; } -module.exports = { +export { getEmptyArtifactState, awaitArtifacts, collectPhaseArtifacts, diff --git a/lighthouse-core/fraggle-rock/gather/session.js b/lighthouse-core/fraggle-rock/gather/session.js index 106b913c0f14..79dd3e46916c 100644 --- a/lighthouse-core/fraggle-rock/gather/session.js +++ b/lighthouse-core/fraggle-rock/gather/session.js @@ -5,8 +5,8 @@ */ 'use strict'; -const EventEmitter = require('events').EventEmitter; -const LighthouseError = require('../../lib/lh-error.js'); +import EventEmitter from 'events'; +import {LighthouseError} from '../../lib/lh-error.js'; // Controls how long to wait for a response after sending a DevTools protocol command. const DEFAULT_PROTOCOL_TIMEOUT = 30000; @@ -111,4 +111,4 @@ class ProtocolSession extends CrdpEventEmitter { } } -module.exports = ProtocolSession; +export {ProtocolSession}; diff --git a/lighthouse-core/fraggle-rock/gather/snapshot-runner.js b/lighthouse-core/fraggle-rock/gather/snapshot-runner.js index c4038448b336..bcb9a3aa67a0 100644 --- a/lighthouse-core/fraggle-rock/gather/snapshot-runner.js +++ b/lighthouse-core/fraggle-rock/gather/snapshot-runner.js @@ -5,16 +5,12 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const Driver = require('./driver.js'); -const Runner = require('../../runner.js'); -const { - getEmptyArtifactState, - collectPhaseArtifacts, - awaitArtifacts, -} = require('./runner-helpers.js'); -const {initializeConfig} = require('../config/config.js'); -const {getBaseArtifacts, finalizeArtifacts} = require('./base-artifacts.js'); +import log from 'lighthouse-logger'; +import {Driver} from './driver.js'; +import {Runner} from '../../runner.js'; +import {getEmptyArtifactState, collectPhaseArtifacts, awaitArtifacts} from './runner-helpers.js'; +import {initializeConfig} from '../config/config.js'; +import {getBaseArtifacts, finalizeArtifacts} from './base-artifacts.js'; /** * @param {{page: LH.Puppeteer.Page, config?: LH.Config.Json, configContext?: LH.Config.FRContext}} options @@ -65,6 +61,6 @@ async function snapshotGather(options) { return {artifacts, runnerOptions}; } -module.exports = { +export { snapshotGather, }; diff --git a/lighthouse-core/fraggle-rock/gather/timespan-runner.js b/lighthouse-core/fraggle-rock/gather/timespan-runner.js index 8daeb1da225e..a0a15c45072b 100644 --- a/lighthouse-core/fraggle-rock/gather/timespan-runner.js +++ b/lighthouse-core/fraggle-rock/gather/timespan-runner.js @@ -5,17 +5,13 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const Driver = require('./driver.js'); -const Runner = require('../../runner.js'); -const { - getEmptyArtifactState, - collectPhaseArtifacts, - awaitArtifacts, -} = require('./runner-helpers.js'); -const {prepareTargetForTimespanMode} = require('../../gather/driver/prepare.js'); -const {initializeConfig} = require('../config/config.js'); -const {getBaseArtifacts, finalizeArtifacts} = require('./base-artifacts.js'); +import log from 'lighthouse-logger'; +import {Driver} from './driver.js'; +import {Runner} from '../../runner.js'; +import {getEmptyArtifactState, collectPhaseArtifacts, awaitArtifacts} from './runner-helpers.js'; +import {prepareTargetForTimespanMode} from '../../gather/driver/prepare.js'; +import {initializeConfig} from '../config/config.js'; +import {getBaseArtifacts, finalizeArtifacts} from './base-artifacts.js'; /** * @param {{page: LH.Puppeteer.Page, config?: LH.Config.Json, configContext?: LH.Config.FRContext}} options @@ -78,6 +74,6 @@ async function startTimespanGather(options) { }; } -module.exports = { +export { startTimespanGather, }; diff --git a/lighthouse-core/fraggle-rock/user-flow.js b/lighthouse-core/fraggle-rock/user-flow.js index c2e09c6ef294..788ae18e2852 100644 --- a/lighthouse-core/fraggle-rock/user-flow.js +++ b/lighthouse-core/fraggle-rock/user-flow.js @@ -5,12 +5,12 @@ */ 'use strict'; -const {generateFlowReportHtml} = require('../../report/generator/report-generator.js'); -const {snapshotGather} = require('./gather/snapshot-runner.js'); -const {startTimespanGather} = require('./gather/timespan-runner.js'); -const {navigationGather} = require('./gather/navigation-runner.js'); -const Runner = require('../runner.js'); -const {initializeConfig} = require('./config/config.js'); +import ReportGenerator from '../../report/generator/report-generator.js'; +import {snapshotGather} from './gather/snapshot-runner.js'; +import {startTimespanGather} from './gather/timespan-runner.js'; +import {navigationGather} from './gather/navigation-runner.js'; +import {Runner} from '../runner.js'; +import {initializeConfig} from './config/config.js'; /** @typedef {Parameters<snapshotGather>[0]} FrOptions */ /** @typedef {Omit<FrOptions, 'page'> & {name?: string}} UserFlowOptions */ @@ -220,7 +220,7 @@ class UserFlow { */ async generateReport() { const flowResult = await this.createFlowResult(); - return generateFlowReportHtml(flowResult); + return ReportGenerator.generateFlowReportHtml(flowResult); } /** @@ -273,7 +273,7 @@ async function auditGatherSteps(gatherSteps, options) { } -module.exports = { +export { UserFlow, auditGatherSteps, }; diff --git a/lighthouse-core/gather/connections/connection.js b/lighthouse-core/gather/connections/connection.js index 730521d6c528..eb22a7b08a00 100644 --- a/lighthouse-core/gather/connections/connection.js +++ b/lighthouse-core/gather/connections/connection.js @@ -5,9 +5,9 @@ */ 'use strict'; -const EventEmitter = require('events').EventEmitter; -const log = require('lighthouse-logger'); -const LighthouseError = require('../../lib/lh-error.js'); +import {EventEmitter} from 'events'; +import log from 'lighthouse-logger'; +import {LighthouseError} from '../../lib/lh-error.js'; // TODO(bckenny): CommandCallback properties should be tied by command type after // https://github.com/Microsoft/TypeScript/pull/22348. See driver.js TODO. @@ -176,4 +176,4 @@ class Connection { } } -module.exports = Connection; +export {Connection}; diff --git a/lighthouse-core/gather/connections/cri.js b/lighthouse-core/gather/connections/cri.js index 66b4a060dca4..3e9606e45d10 100644 --- a/lighthouse-core/gather/connections/cri.js +++ b/lighthouse-core/gather/connections/cri.js @@ -5,11 +5,11 @@ */ 'use strict'; -const Connection = require('./connection.js'); -const WebSocket = require('ws'); -const http = require('http'); -const log = require('lighthouse-logger'); -const LighthouseError = require('../../lib/lh-error.js'); +import {Connection} from './connection.js'; +import WebSocket from 'ws'; +import http from 'http'; +import log from 'lighthouse-logger'; +import {LighthouseError} from '../../lib/lh-error.js'; const DEFAULT_HOSTNAME = '127.0.0.1'; const CONNECT_TIMEOUT = 10000; @@ -158,4 +158,4 @@ class CriConnection extends Connection { } } -module.exports = CriConnection; +export {CriConnection}; diff --git a/lighthouse-core/gather/connections/raw.js b/lighthouse-core/gather/connections/raw.js index e701a7a07280..62af13d83912 100644 --- a/lighthouse-core/gather/connections/raw.js +++ b/lighthouse-core/gather/connections/raw.js @@ -5,7 +5,7 @@ */ 'use strict'; -const Connection = require('./connection.js'); +import {Connection} from './connection.js'; /* eslint-disable no-unused-vars */ @@ -55,4 +55,4 @@ class RawConnection extends Connection { } } -module.exports = RawConnection; +export {RawConnection}; diff --git a/lighthouse-core/gather/driver.js b/lighthouse-core/gather/driver.js index 0ad306167ad4..9b0a987d9b59 100644 --- a/lighthouse-core/gather/driver.js +++ b/lighthouse-core/gather/driver.js @@ -5,20 +5,15 @@ */ 'use strict'; -const Fetcher = require('./fetcher.js'); -const ExecutionContext = require('./driver/execution-context.js'); -const LighthouseError = require('../lib/lh-error.js'); -const {fetchResponseBodyFromCache} = require('../gather/driver/network.js'); -const EventEmitter = require('events').EventEmitter; - -const log = require('lighthouse-logger'); -const DevtoolsMessageLog = require('./gatherers/devtools-log.js').DevtoolsMessageLog; -const TraceGatherer = require('./gatherers/trace.js'); - -// Pulled in for Connection type checking. -// eslint-disable-next-line no-unused-vars -const Connection = require('./connections/connection.js'); -const {getBrowserVersion} = require('./driver/environment.js'); +import {Fetcher} from './fetcher.js'; +import {ExecutionContext} from './driver/execution-context.js'; +import {LighthouseError} from '../lib/lh-error.js'; +import {fetchResponseBodyFromCache} from '../gather/driver/network.js'; +import {EventEmitter} from 'events'; +import log from 'lighthouse-logger'; +import {DevtoolsMessageLog} from './gatherers/devtools-log.js'; +import TraceGatherer from './gatherers/trace.js'; +import {getBrowserVersion} from './driver/environment.js'; // Controls how long to wait for a response after sending a DevTools protocol command. const DEFAULT_PROTOCOL_TIMEOUT = 30000; @@ -67,7 +62,7 @@ class Driver { fetcher = new Fetcher(this.defaultSession); /** - * @param {Connection} connection + * @param {import('./connections/connection.js').Connection} connection */ constructor(connection) { this._connection = connection; @@ -483,4 +478,4 @@ class Driver { } } -module.exports = Driver; +export {Driver}; diff --git a/lighthouse-core/gather/driver/dom.js b/lighthouse-core/gather/driver/dom.js index c5629fca103d..bb8d43ff5f8e 100644 --- a/lighthouse-core/gather/driver/dom.js +++ b/lighthouse-core/gather/driver/dom.js @@ -55,4 +55,4 @@ async function resolveDevtoolsNodePathToObjectId(session, path) { } } -module.exports = {resolveNodeIdToObjectId, resolveDevtoolsNodePathToObjectId}; +export {resolveNodeIdToObjectId, resolveDevtoolsNodePathToObjectId}; diff --git a/lighthouse-core/gather/driver/environment.js b/lighthouse-core/gather/driver/environment.js index 8345d8a9349d..03494ea4bd2b 100644 --- a/lighthouse-core/gather/driver/environment.js +++ b/lighthouse-core/gather/driver/environment.js @@ -5,10 +5,10 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const constants = require('../../config/constants.js'); -const pageFunctions = require('../../lib/page-functions.js'); -const i18n = require('../../lib/i18n/i18n.js'); +import log from 'lighthouse-logger'; +import * as constants from '../../config/constants.js'; +import {pageFunctions} from '../../lib/page-functions.js'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** @@ -27,7 +27,7 @@ const UIStrings = { */ const SLOW_CPU_BENCHMARK_INDEX_THRESHOLD = 1000; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** * @param {LH.Gatherer.FRProtocolSession} session @@ -96,7 +96,7 @@ function getEnvironmentWarnings(context) { ].filter(/** @return {s is LH.IcuMessage} */ s => !!s); } -module.exports = { +export { UIStrings, getBrowserVersion, getBenchmarkIndex, diff --git a/lighthouse-core/gather/driver/execution-context.js b/lighthouse-core/gather/driver/execution-context.js index a0212a574a6f..17f7537371c3 100644 --- a/lighthouse-core/gather/driver/execution-context.js +++ b/lighthouse-core/gather/driver/execution-context.js @@ -7,7 +7,7 @@ /* global window */ -const pageFunctions = require('../../lib/page-functions.js'); +import {pageFunctions} from '../../lib/page-functions.js'; class ExecutionContext { /** @param {LH.Gatherer.FRProtocolSession} session */ @@ -249,4 +249,4 @@ class ExecutionContext { } } -module.exports = ExecutionContext; +export {ExecutionContext}; diff --git a/lighthouse-core/gather/driver/navigation.js b/lighthouse-core/gather/driver/navigation.js index 25a77d6abc70..eb7ed673f706 100644 --- a/lighthouse-core/gather/driver/navigation.js +++ b/lighthouse-core/gather/driver/navigation.js @@ -5,12 +5,12 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const NetworkMonitor = require('./network-monitor.js'); -const {waitForFullyLoaded, waitForFrameNavigated, waitForUserToContinue} = require('./wait-for-condition.js'); // eslint-disable-line max-len -const constants = require('../../config/constants.js'); -const i18n = require('../../lib/i18n/i18n.js'); -const URL = require('../../lib/url-shim.js'); +import log from 'lighthouse-logger'; +import {NetworkMonitor} from './network-monitor.js'; +import {waitForFullyLoaded, waitForFrameNavigated, waitForUserToContinue} from './wait-for-condition.js'; // eslint-disable-line max-len +import * as constants from '../../config/constants.js'; +import * as i18n from '../../lib/i18n/i18n.js'; +import URL from '../../lib/url-shim.js'; const UIStrings = { /** @@ -28,7 +28,7 @@ const UIStrings = { 'Results may be incomplete.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // Controls how long to wait after FCP before continuing @@ -179,4 +179,4 @@ function getNavigationWarnings(navigation) { return warnings; } -module.exports = {gotoURL, getNavigationWarnings, UIStrings}; +export {gotoURL, getNavigationWarnings, UIStrings}; diff --git a/lighthouse-core/gather/driver/network-monitor.js b/lighthouse-core/gather/driver/network-monitor.js index e70724bcd313..3b9fbd56c49b 100644 --- a/lighthouse-core/gather/driver/network-monitor.js +++ b/lighthouse-core/gather/driver/network-monitor.js @@ -10,11 +10,12 @@ * status inspection state. */ -const log = require('lighthouse-logger'); -const {EventEmitter} = require('events'); -const NetworkRecorder = require('../../lib/network-recorder.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const URL = require('../../lib/url-shim.js'); +import log from 'lighthouse-logger'; + +import {EventEmitter} from 'events'; +import {NetworkRecorder} from '../../lib/network-recorder.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import URL from '../../lib/url-shim.js'; /** @typedef {import('../../lib/network-recorder.js').NetworkRecorderEventMap} NetworkRecorderEventMap */ /** @typedef {'network-2-idle'|'network-critical-idle'|'networkidle'|'networkbusy'|'network-critical-busy'|'network-2-busy'} NetworkMonitorEvent_ */ @@ -256,4 +257,4 @@ class NetworkMonitor extends NetworkMonitorEventEmitter { } } -module.exports = NetworkMonitor; +export {NetworkMonitor}; diff --git a/lighthouse-core/gather/driver/network.js b/lighthouse-core/gather/driver/network.js index c4c29250a391..ccf165eb934f 100644 --- a/lighthouse-core/gather/driver/network.js +++ b/lighthouse-core/gather/driver/network.js @@ -5,7 +5,7 @@ */ 'use strict'; -const NetworkRequest = require('../../lib/network-request.js'); +import {NetworkRequest} from '../../lib/network-request.js'; /** * Return the body of the response with the given ID. Rejects if getting the @@ -25,4 +25,4 @@ async function fetchResponseBodyFromCache(session, requestId, timeout = 1000) { return result.body; } -module.exports = {fetchResponseBodyFromCache}; +export {fetchResponseBodyFromCache}; diff --git a/lighthouse-core/gather/driver/prepare.js b/lighthouse-core/gather/driver/prepare.js index 1f2eaa0300cc..6a4ce9b53620 100644 --- a/lighthouse-core/gather/driver/prepare.js +++ b/lighthouse-core/gather/driver/prepare.js @@ -5,10 +5,10 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const storage = require('./storage.js'); -const emulation = require('../../lib/emulation.js'); -const pageFunctions = require('../../lib/page-functions.js'); +import log from 'lighthouse-logger'; +import * as storage from './storage.js'; +import * as emulation from '../../lib/emulation.js'; +import {pageFunctions} from '../../lib/page-functions.js'; /** * Enables `Debugger` domain to receive async stacktrace information on network request initiators. @@ -218,7 +218,7 @@ async function prepareTargetForIndividualNavigation(session, settings, navigatio return {warnings}; } -module.exports = { +export { prepareThrottlingAndNetwork, prepareTargetForTimespanMode, prepareTargetForNavigationMode, diff --git a/lighthouse-core/gather/driver/service-workers.js b/lighthouse-core/gather/driver/service-workers.js index 5de97fd3279e..f1c33588facb 100644 --- a/lighthouse-core/gather/driver/service-workers.js +++ b/lighthouse-core/gather/driver/service-workers.js @@ -50,4 +50,4 @@ function getServiceWorkerRegistrations(session) { }); } -module.exports = {getServiceWorkerVersions, getServiceWorkerRegistrations}; +export {getServiceWorkerVersions, getServiceWorkerRegistrations}; diff --git a/lighthouse-core/gather/driver/storage.js b/lighthouse-core/gather/driver/storage.js index 40d16d93dd08..aed202f09208 100644 --- a/lighthouse-core/gather/driver/storage.js +++ b/lighthouse-core/gather/driver/storage.js @@ -5,8 +5,8 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const i18n = require('../../lib/i18n/i18n.js'); +import log from 'lighthouse-logger'; +import * as i18n from '../../lib/i18n/i18n.js'; const UIStrings = { /** @@ -24,7 +24,7 @@ const UIStrings = { }`, }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @@ -117,7 +117,7 @@ async function clearBrowserCaches(session) { log.timeEnd(status); } -module.exports = { +export { clearDataForOrigin, clearBrowserCaches, getImportantStorageWarning, diff --git a/lighthouse-core/gather/driver/target-manager.js b/lighthouse-core/gather/driver/target-manager.js index 1bcdb2155774..883c84a352f4 100644 --- a/lighthouse-core/gather/driver/target-manager.js +++ b/lighthouse-core/gather/driver/target-manager.js @@ -5,9 +5,14 @@ */ 'use strict'; -const EventEmitter = require('events').EventEmitter; -const log = require('lighthouse-logger'); -const ProtocolSession = require('../../fraggle-rock/gather/session.js'); +/** + * @fileoverview This class tracks multiple targets (the page itself and its OOPIFs) and allows consumers to + * listen for protocol events before each target is resumed. + */ + +import EventEmitter from 'events'; +import log from 'lighthouse-logger'; +import {ProtocolSession} from '../../fraggle-rock/gather/session.js'; /** * @typedef {{ @@ -199,4 +204,4 @@ class TargetManager extends ProtocolEventEmitter { } } -module.exports = TargetManager; +export {TargetManager}; diff --git a/lighthouse-core/gather/driver/wait-for-condition.js b/lighthouse-core/gather/driver/wait-for-condition.js index 276ffcc2159e..a5629e146edc 100644 --- a/lighthouse-core/gather/driver/wait-for-condition.js +++ b/lighthouse-core/gather/driver/wait-for-condition.js @@ -7,11 +7,12 @@ /* global window */ -const log = require('lighthouse-logger'); -const LighthouseError = require('../../lib/lh-error.js'); -const ExecutionContext = require('./execution-context.js'); +import log from 'lighthouse-logger'; -/** @typedef {import('./network-monitor.js')} NetworkMonitor */ +import {LighthouseError} from '../../lib/lh-error.js'; +import {ExecutionContext} from './execution-context.js'; + +/** @typedef {InstanceType<import('./network-monitor.js')['NetworkMonitor']>} NetworkMonitor */ /** @typedef {import('./network-monitor.js').NetworkMonitorEvent} NetworkMonitorEvent */ /** @typedef {{promise: Promise<void>, cancel: function(): void}} CancellableWait */ @@ -524,7 +525,7 @@ function waitForUserToContinue(driver) { return driver.executionContext.evaluate(createInPagePromise, {args: []}); } -module.exports = { +export { waitForNothing, waitForFrameNavigated, waitForFcp, diff --git a/lighthouse-core/gather/fetcher.js b/lighthouse-core/gather/fetcher.js index 1150b8fbba96..0f29c08354e6 100644 --- a/lighthouse-core/gather/fetcher.js +++ b/lighthouse-core/gather/fetcher.js @@ -139,4 +139,4 @@ class Fetcher { } } -module.exports = Fetcher; +export {Fetcher}; diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index f78961f96358..a459fad9629a 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -5,26 +5,26 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const NetworkRecords = require('../computed/network-records.js'); -const {getPageLoadError} = require('../lib/navigation-error.js'); -const emulation = require('../lib/emulation.js'); -const constants = require('../config/constants.js'); -const format = require('../../shared/localization/format.js'); -const {getBenchmarkIndex, getEnvironmentWarnings} = require('./driver/environment.js'); -const prepare = require('./driver/prepare.js'); -const storage = require('./driver/storage.js'); -const navigation = require('./driver/navigation.js'); -const serviceWorkers = require('./driver/service-workers.js'); -const WebAppManifest = require('./gatherers/web-app-manifest.js'); -const InstallabilityErrors = require('./gatherers/installability-errors.js'); -const NetworkUserAgent = require('./gatherers/network-user-agent.js'); -const Stacks = require('./gatherers/stacks.js'); -const URL = require('../lib/url-shim.js'); -const {finalizeArtifacts} = require('../fraggle-rock/gather/base-artifacts.js'); - -/** @typedef {import('../gather/driver.js')} Driver */ -/** @typedef {import('../lib/arbitrary-equality-map.js')} ArbitraryEqualityMap */ +import log from 'lighthouse-logger'; +import NetworkRecords from '../computed/network-records.js'; +import {getPageLoadError} from '../lib/navigation-error.js'; +import * as emulation from '../lib/emulation.js'; +import * as constants from '../config/constants.js'; +import format from '../../shared/localization/format.js'; +import {getBenchmarkIndex, getEnvironmentWarnings} from './driver/environment.js'; +import * as prepare from './driver/prepare.js'; +import * as storage from './driver/storage.js'; +import * as navigation from './driver/navigation.js'; +import * as serviceWorkers from './driver/service-workers.js'; +import WebAppManifest from './gatherers/web-app-manifest.js'; +import InstallabilityErrors from './gatherers/installability-errors.js'; +import NetworkUserAgent from './gatherers/network-user-agent.js'; +import Stacks from './gatherers/stacks.js'; +import {finalizeArtifacts} from '../fraggle-rock/gather/base-artifacts.js'; +import URLShim from '../lib/url-shim.js'; + +/** @typedef {import('../gather/driver.js').Driver} Driver */ +/** @typedef {import('../lib/arbitrary-equality-map.js').ArbitraryEqualityMap} ArbitraryEqualityMap */ /** * Each entry in each gatherer result array is the output of a gatherer phase: @@ -494,7 +494,7 @@ class GatherRunner { // Hack for running benchmarkIndex extra times. // Add a `bidx=20` query param, eg: https://www.example.com/?bidx=50 - const parsedUrl = URL.isValid(options.requestedUrl) && new URL(options.requestedUrl); + const parsedUrl = URLShim.isValid(options.requestedUrl) && new URL(options.requestedUrl); if (options.settings.channel === 'lr' && parsedUrl && parsedUrl.searchParams.has('bidx')) { const bidxRunCount = parsedUrl.searchParams.get('bidx') || 0; // Add the first bidx into the new set @@ -631,4 +631,4 @@ class GatherRunner { } } -module.exports = GatherRunner; +export {GatherRunner}; diff --git a/lighthouse-core/gather/gatherers/accessibility.js b/lighthouse-core/gather/gatherers/accessibility.js index ae75a17650bd..00dac7589bce 100644 --- a/lighthouse-core/gather/gatherers/accessibility.js +++ b/lighthouse-core/gather/gatherers/accessibility.js @@ -7,9 +7,10 @@ /* global window, document, getNodeDetails */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const axeLibSource = require('../../lib/axe.js').source; -const pageFunctions = require('../../lib/page-functions.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; + +import {axeSource} from '../../lib/axe.js'; +import {pageFunctions} from '../../lib/page-functions.js'; /** * @return {Promise<LH.Artifacts.Accessibility>} @@ -173,7 +174,7 @@ class Accessibility extends FRGatherer { args: [], useIsolation: true, deps: [ - axeLibSource, + axeSource, pageFunctions.getNodeDetailsString, createAxeRuleResultArtifact, ], @@ -181,4 +182,4 @@ class Accessibility extends FRGatherer { } } -module.exports = Accessibility; +export default Accessibility; diff --git a/lighthouse-core/gather/gatherers/anchor-elements.js b/lighthouse-core/gather/gatherers/anchor-elements.js index efc62078b6c9..1efa6cb09753 100644 --- a/lighthouse-core/gather/gatherers/anchor-elements.js +++ b/lighthouse-core/gather/gatherers/anchor-elements.js @@ -7,9 +7,10 @@ /* global getNodeDetails */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const dom = require('../driver/dom.js'); -const pageFunctions = require('../../lib/page-functions.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; + +import {pageFunctions} from '../../lib/page-functions.js'; +import {resolveDevtoolsNodePathToObjectId} from '../driver/dom.js'; /* eslint-env browser, node */ @@ -80,7 +81,7 @@ function collectAnchorElements() { * @return {Promise<Array<{type: string}>>} */ async function getEventListeners(session, devtoolsNodePath) { - const objectId = await dom.resolveDevtoolsNodePathToObjectId(session, devtoolsNodePath); + const objectId = await resolveDevtoolsNodePathToObjectId(session, devtoolsNodePath); if (!objectId) return []; const response = await session.sendCommand('DOMDebugger.getEventListeners', { @@ -130,4 +131,4 @@ class AnchorElements extends FRGatherer { } } -module.exports = AnchorElements; +export default AnchorElements; diff --git a/lighthouse-core/gather/gatherers/cache-contents.js b/lighthouse-core/gather/gatherers/cache-contents.js index 675f7b9699d0..14b90f53fa5f 100644 --- a/lighthouse-core/gather/gatherers/cache-contents.js +++ b/lighthouse-core/gather/gatherers/cache-contents.js @@ -7,7 +7,7 @@ /* global caches */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; /** * @return {Promise<Array<string>>} @@ -56,4 +56,4 @@ class CacheContents extends FRGatherer { } } -module.exports = CacheContents; +export default CacheContents; diff --git a/lighthouse-core/gather/gatherers/console-messages.js b/lighthouse-core/gather/gatherers/console-messages.js index 481d07370d3a..1b967034b8ff 100644 --- a/lighthouse-core/gather/gatherers/console-messages.js +++ b/lighthouse-core/gather/gatherers/console-messages.js @@ -11,7 +11,7 @@ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; /** * @param {LH.Crdp.Runtime.RemoteObject} obj @@ -172,4 +172,4 @@ class ConsoleMessages extends FRGatherer { } } -module.exports = ConsoleMessages; +export default ConsoleMessages; diff --git a/lighthouse-core/gather/gatherers/css-usage.js b/lighthouse-core/gather/gatherers/css-usage.js index bd131d311cfd..0eaeab64cb3e 100644 --- a/lighthouse-core/gather/gatherers/css-usage.js +++ b/lighthouse-core/gather/gatherers/css-usage.js @@ -5,13 +5,14 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const Sentry = require('../../lib/sentry.js'); - /** * @fileoverview Tracks unused CSS rules. */ + +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import log from 'lighthouse-logger'; +import {Sentry} from '../../lib/sentry.js'; + class CSSUsage extends FRGatherer { constructor() { super(); @@ -146,4 +147,4 @@ class CSSUsage extends FRGatherer { } } -module.exports = CSSUsage; +export default CSSUsage; diff --git a/lighthouse-core/gather/gatherers/devtools-log-compat.js b/lighthouse-core/gather/gatherers/devtools-log-compat.js index e8e3e9961844..7175bb8ad5bf 100644 --- a/lighthouse-core/gather/gatherers/devtools-log-compat.js +++ b/lighthouse-core/gather/gatherers/devtools-log-compat.js @@ -11,8 +11,9 @@ * when devtools logs and traces were special-cased. */ -const DevtoolsLogGatherer = require('./devtools-log.js'); -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import DevtoolsLogGatherer from './devtools-log.js'; + +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; /** @implements {LH.Gatherer.FRGathererInstance<'DevtoolsLog'>} */ class DevtoolsLogCompat extends FRGatherer { @@ -33,4 +34,4 @@ class DevtoolsLogCompat extends FRGatherer { } } -module.exports = DevtoolsLogCompat; +export default DevtoolsLogCompat; diff --git a/lighthouse-core/gather/gatherers/devtools-log.js b/lighthouse-core/gather/gatherers/devtools-log.js index 7a6b8a08ddb7..1058d36185d3 100644 --- a/lighthouse-core/gather/gatherers/devtools-log.js +++ b/lighthouse-core/gather/gatherers/devtools-log.js @@ -11,7 +11,7 @@ * This protocol log can be used to recreate the network records using lib/network-recorder.js. */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; class DevtoolsLog extends FRGatherer { static symbol = Symbol('DevtoolsLog'); @@ -112,5 +112,5 @@ class DevtoolsMessageLog { } } -module.exports = DevtoolsLog; -module.exports.DevtoolsMessageLog = DevtoolsMessageLog; +export default DevtoolsLog; +export {DevtoolsMessageLog}; diff --git a/lighthouse-core/gather/gatherers/dobetterweb/doctype.js b/lighthouse-core/gather/gatherers/dobetterweb/doctype.js index 72eab418958a..3ab8e71e46d8 100644 --- a/lighthouse-core/gather/gatherers/dobetterweb/doctype.js +++ b/lighthouse-core/gather/gatherers/dobetterweb/doctype.js @@ -5,7 +5,7 @@ */ 'use strict'; -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; /* global document */ @@ -45,4 +45,4 @@ class Doctype extends FRGatherer { } } -module.exports = Doctype; +export default Doctype; diff --git a/lighthouse-core/gather/gatherers/dobetterweb/domstats.js b/lighthouse-core/gather/gatherers/dobetterweb/domstats.js index d3d5c6c0b058..29901cf67b47 100644 --- a/lighthouse-core/gather/gatherers/dobetterweb/domstats.js +++ b/lighthouse-core/gather/gatherers/dobetterweb/domstats.js @@ -13,8 +13,8 @@ 'use strict'; -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); -const pageFunctions = require('../../../lib/page-functions.js'); +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; +import {pageFunctions} from '../../../lib/page-functions.js'; /** * Calculates the maximum tree depth of the DOM. @@ -100,4 +100,4 @@ class DOMStats extends FRGatherer { } } -module.exports = DOMStats; +export default DOMStats; diff --git a/lighthouse-core/gather/gatherers/dobetterweb/optimized-images.js b/lighthouse-core/gather/gatherers/dobetterweb/optimized-images.js index 2b0d0b4b8812..8737e19b0ac7 100644 --- a/lighthouse-core/gather/gatherers/dobetterweb/optimized-images.js +++ b/lighthouse-core/gather/gatherers/dobetterweb/optimized-images.js @@ -10,13 +10,13 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); -const URL = require('../../../lib/url-shim.js'); -const NetworkRequest = require('../../../lib/network-request.js'); -const Sentry = require('../../../lib/sentry.js'); -const NetworkRecords = require('../../../computed/network-records.js'); -const DevtoolsLog = require('../devtools-log.js'); +import log from 'lighthouse-logger'; +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; +import URL from '../../../lib/url-shim.js'; +import {NetworkRequest} from '../../../lib/network-request.js'; +import {Sentry} from '../../../lib/sentry.js'; +import NetworkRecords from '../../../computed/network-records.js'; +import DevtoolsLog from '../devtools-log.js'; // Image encoding can be slow and we don't want to spend forever on it. // Cap our encoding to 5 seconds, anything after that will be estimated. @@ -189,4 +189,4 @@ class OptimizedImages extends FRGatherer { } } -module.exports = OptimizedImages; +export default OptimizedImages; diff --git a/lighthouse-core/gather/gatherers/dobetterweb/password-inputs-with-prevented-paste.js b/lighthouse-core/gather/gatherers/dobetterweb/password-inputs-with-prevented-paste.js index 0fff0b5d8269..5bc428f05c93 100644 --- a/lighthouse-core/gather/gatherers/dobetterweb/password-inputs-with-prevented-paste.js +++ b/lighthouse-core/gather/gatherers/dobetterweb/password-inputs-with-prevented-paste.js @@ -7,8 +7,9 @@ /* global document ClipboardEvent getNodeDetails */ -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); -const pageFunctions = require('../../../lib/page-functions.js'); +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; + +import {pageFunctions} from '../../../lib/page-functions.js'; /** * @return {LH.Artifacts['PasswordInputsWithPreventedPaste']} @@ -47,4 +48,4 @@ class PasswordInputsWithPreventedPaste extends FRGatherer { } -module.exports = PasswordInputsWithPreventedPaste; +export default PasswordInputsWithPreventedPaste; diff --git a/lighthouse-core/gather/gatherers/dobetterweb/response-compression.js b/lighthouse-core/gather/gatherers/dobetterweb/response-compression.js index 16cc4028842a..3931b142da4c 100644 --- a/lighthouse-core/gather/gatherers/dobetterweb/response-compression.js +++ b/lighthouse-core/gather/gatherers/dobetterweb/response-compression.js @@ -10,15 +10,15 @@ */ 'use strict'; -const {Buffer} = require('buffer'); -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); -const URL = require('../../../lib/url-shim.js'); -const Sentry = require('../../../lib/sentry.js'); -const NetworkRequest = require('../../../lib/network-request.js'); -const gzip = require('zlib').gzip; -const DevtoolsLog = require('../devtools-log.js'); -const {fetchResponseBodyFromCache} = require('../../driver/network.js'); -const NetworkRecords = require('../../../computed/network-records.js'); +import {Buffer} from 'buffer'; +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; +import URL from '../../../lib/url-shim.js'; +import {Sentry} from '../../../lib/sentry.js'; +import {NetworkRequest} from '../../../lib/network-request.js'; +import {gzip} from 'zlib'; +import DevtoolsLog from '../devtools-log.js'; +import {fetchResponseBodyFromCache} from '../../driver/network.js'; +import NetworkRecords from '../../../computed/network-records.js'; const CHROME_EXTENSION_PROTOCOL = 'chrome-extension:'; const compressionHeaders = [ @@ -151,4 +151,4 @@ class ResponseCompression extends FRGatherer { } } -module.exports = ResponseCompression; +export default ResponseCompression; diff --git a/lighthouse-core/gather/gatherers/dobetterweb/tags-blocking-first-paint.js b/lighthouse-core/gather/gatherers/dobetterweb/tags-blocking-first-paint.js index ec2a6eac939e..9801d6c5a735 100644 --- a/lighthouse-core/gather/gatherers/dobetterweb/tags-blocking-first-paint.js +++ b/lighthouse-core/gather/gatherers/dobetterweb/tags-blocking-first-paint.js @@ -18,9 +18,9 @@ 'use strict'; -const NetworkRecords = require('../../../computed/network-records.js'); -const DevtoolsLog = require('../devtools-log.js'); -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); +import NetworkRecords from '../../../computed/network-records.js'; +import DevtoolsLog from '../devtools-log.js'; +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; /* global document, window, HTMLLinkElement, SVGScriptElement */ @@ -235,4 +235,4 @@ class TagsBlockingFirstPaint extends FRGatherer { } } -module.exports = TagsBlockingFirstPaint; +export default TagsBlockingFirstPaint; diff --git a/lighthouse-core/gather/gatherers/full-page-screenshot.js b/lighthouse-core/gather/gatherers/full-page-screenshot.js index 58cd23f89405..0804a3efd69a 100644 --- a/lighthouse-core/gather/gatherers/full-page-screenshot.js +++ b/lighthouse-core/gather/gatherers/full-page-screenshot.js @@ -7,11 +7,12 @@ /* globals window document getBoundingClientRect requestAnimationFrame */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const emulation = require('../../lib/emulation.js'); -const pageFunctions = require('../../lib/page-functions.js'); -const NetworkMonitor = require('../driver/network-monitor.js'); -const {waitForNetworkIdle} = require('../driver/wait-for-condition.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; + +import * as emulation from '../../lib/emulation.js'; +import {pageFunctions} from '../../lib/page-functions.js'; +import {NetworkMonitor} from '../driver/network-monitor.js'; +import {waitForNetworkIdle} from '../driver/wait-for-condition.js'; // JPEG quality setting // Exploration and examples of reports using different quality settings: https://docs.google.com/document/d/1ZSffucIca9XDW2eEwfoevrk-OTl7WQFeMf0CgeJAA8M/edit# @@ -233,4 +234,4 @@ class FullPageScreenshot extends FRGatherer { } } -module.exports = FullPageScreenshot; +export default FullPageScreenshot; diff --git a/lighthouse-core/gather/gatherers/gatherer.js b/lighthouse-core/gather/gatherers/gatherer.js index 25deff88c49a..2d1eafb637ec 100644 --- a/lighthouse-core/gather/gatherers/gatherer.js +++ b/lighthouse-core/gather/gatherers/gatherer.js @@ -56,4 +56,4 @@ class Gatherer { /* eslint-enable no-unused-vars */ } -module.exports = Gatherer; +export {Gatherer}; diff --git a/lighthouse-core/gather/gatherers/global-listeners.js b/lighthouse-core/gather/gatherers/global-listeners.js index 2914a7af7b0d..e5df4ddcbc12 100644 --- a/lighthouse-core/gather/gatherers/global-listeners.js +++ b/lighthouse-core/gather/gatherers/global-listeners.js @@ -12,7 +12,7 @@ * around page unload, but this can be expanded in the future. */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; class GlobalListeners extends FRGatherer { /** @type {LH.Gatherer.GathererMeta} */ @@ -89,4 +89,4 @@ class GlobalListeners extends FRGatherer { } } -module.exports = GlobalListeners; +export default GlobalListeners; diff --git a/lighthouse-core/gather/gatherers/iframe-elements.js b/lighthouse-core/gather/gatherers/iframe-elements.js index b109778b0ef0..024aceb09c3f 100644 --- a/lighthouse-core/gather/gatherers/iframe-elements.js +++ b/lighthouse-core/gather/gatherers/iframe-elements.js @@ -7,8 +7,9 @@ /* global getNodeDetails */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const pageFunctions = require('../../lib/page-functions.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; + +import {pageFunctions} from '../../lib/page-functions.js'; /* eslint-env browser, node */ @@ -65,4 +66,4 @@ class IFrameElements extends FRGatherer { } } -module.exports = IFrameElements; +export default IFrameElements; diff --git a/lighthouse-core/gather/gatherers/image-elements.js b/lighthouse-core/gather/gatherers/image-elements.js index dcab9766a6dd..40ba3aac9c1c 100644 --- a/lighthouse-core/gather/gatherers/image-elements.js +++ b/lighthouse-core/gather/gatherers/image-elements.js @@ -9,10 +9,10 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const pageFunctions = require('../../lib/page-functions.js'); -const FontSize = require('./seo/font-size.js'); +import log from 'lighthouse-logger'; +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import {pageFunctions} from '../../lib/page-functions.js'; +import * as FontSize from './seo/font-size.js'; /* global window, getElementsInDocument, Image, getNodeDetails, ShadowRoot */ @@ -374,4 +374,4 @@ class ImageElements extends FRGatherer { } } -module.exports = ImageElements; +export default ImageElements; diff --git a/lighthouse-core/gather/gatherers/inputs.js b/lighthouse-core/gather/gatherers/inputs.js index 72c687715c64..6cfbad151d70 100644 --- a/lighthouse-core/gather/gatherers/inputs.js +++ b/lighthouse-core/gather/gatherers/inputs.js @@ -7,8 +7,9 @@ /* global getNodeDetails */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const pageFunctions = require('../../lib/page-functions.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; + +import {pageFunctions} from '../../lib/page-functions.js'; /* eslint-env browser, node */ @@ -58,7 +59,7 @@ function collectElements() { const parentFormIndex = parentFormEl ? [...formElToArtifact.keys()].indexOf(parentFormEl) : undefined; - const labelIndices = [...inputEl.labels || []].map((labelEl) => { + const labelIndices = [...(inputEl.labels || [])].map((labelEl) => { return [...labelElToArtifact.keys()].indexOf(labelEl); }); @@ -110,4 +111,4 @@ class Inputs extends FRGatherer { } } -module.exports = Inputs; +export default Inputs; diff --git a/lighthouse-core/gather/gatherers/inspector-issues.js b/lighthouse-core/gather/gatherers/inspector-issues.js index a1439fd3f9d1..c75fe9053b72 100644 --- a/lighthouse-core/gather/gatherers/inspector-issues.js +++ b/lighthouse-core/gather/gatherers/inspector-issues.js @@ -10,9 +10,9 @@ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const NetworkRecords = require('../../computed/network-records.js'); -const DevtoolsLog = require('./devtools-log.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import NetworkRecords from '../../computed/network-records.js'; +import DevtoolsLog from './devtools-log.js'; class InspectorIssues extends FRGatherer { /** @type {LH.Gatherer.GathererMeta<'DevtoolsLog'>} */ @@ -124,4 +124,4 @@ class InspectorIssues extends FRGatherer { } } -module.exports = InspectorIssues; +export default InspectorIssues; diff --git a/lighthouse-core/gather/gatherers/installability-errors.js b/lighthouse-core/gather/gatherers/installability-errors.js index 6f9160ee7602..68a35c2dff22 100644 --- a/lighthouse-core/gather/gatherers/installability-errors.js +++ b/lighthouse-core/gather/gatherers/installability-errors.js @@ -5,8 +5,8 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import log from 'lighthouse-logger'; +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; class InstallabilityErrors extends FRGatherer { /** @type {LH.Gatherer.GathererMeta} */ @@ -45,4 +45,4 @@ class InstallabilityErrors extends FRGatherer { } } -module.exports = InstallabilityErrors; +export default InstallabilityErrors; diff --git a/lighthouse-core/gather/gatherers/js-usage.js b/lighthouse-core/gather/gatherers/js-usage.js index 2e83af257799..12ed95d023ce 100644 --- a/lighthouse-core/gather/gatherers/js-usage.js +++ b/lighthouse-core/gather/gatherers/js-usage.js @@ -5,7 +5,7 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; /** * @fileoverview Tracks unused JavaScript @@ -67,4 +67,4 @@ class JsUsage extends FRGatherer { } } -module.exports = JsUsage; +export default JsUsage; diff --git a/lighthouse-core/gather/gatherers/link-elements.js b/lighthouse-core/gather/gatherers/link-elements.js index 244bbd3f4174..2512772c7d0d 100644 --- a/lighthouse-core/gather/gatherers/link-elements.js +++ b/lighthouse-core/gather/gatherers/link-elements.js @@ -5,12 +5,12 @@ */ 'use strict'; -const LinkHeader = require('http-link-header'); -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const {URL} = require('../../lib/url-shim.js'); -const pageFunctions = require('../../lib/page-functions.js'); -const DevtoolsLog = require('./devtools-log.js'); -const MainResource = require('../../computed/main-resource.js'); +import LinkHeader from 'http-link-header'; +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import URL from '../../lib/url-shim.js'; +import {pageFunctions} from '../../lib/page-functions.js'; +import DevtoolsLog from './devtools-log.js'; +import MainResource from '../../computed/main-resource.js'; /* globals HTMLLinkElement getNodeDetails */ @@ -179,4 +179,4 @@ class LinkElements extends FRGatherer { } } -module.exports = LinkElements; +export default LinkElements; diff --git a/lighthouse-core/gather/gatherers/main-document-content.js b/lighthouse-core/gather/gatherers/main-document-content.js index d63689e33877..df66bcb677af 100644 --- a/lighthouse-core/gather/gatherers/main-document-content.js +++ b/lighthouse-core/gather/gatherers/main-document-content.js @@ -5,10 +5,10 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const DevtoolsLog = require('./devtools-log.js'); -const {fetchResponseBodyFromCache} = require('../driver/network.js'); -const MainResource = require('../../computed/main-resource.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import DevtoolsLog from './devtools-log.js'; +import {fetchResponseBodyFromCache} from '../driver/network.js'; +import MainResource from '../../computed/main-resource.js'; /** * Collects the content of the main html document. @@ -51,4 +51,4 @@ class MainDocumentContent extends FRGatherer { } } -module.exports = MainDocumentContent; +export default MainDocumentContent; diff --git a/lighthouse-core/gather/gatherers/meta-elements.js b/lighthouse-core/gather/gatherers/meta-elements.js index 21fb66621a97..4dc91222668f 100644 --- a/lighthouse-core/gather/gatherers/meta-elements.js +++ b/lighthouse-core/gather/gatherers/meta-elements.js @@ -5,8 +5,8 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const pageFunctions = require('../../lib/page-functions.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import {pageFunctions} from '../../lib/page-functions.js'; /* globals getElementsInDocument getNodeDetails */ @@ -65,4 +65,4 @@ class MetaElements extends FRGatherer { } } -module.exports = MetaElements; +export default MetaElements; diff --git a/lighthouse-core/gather/gatherers/network-user-agent.js b/lighthouse-core/gather/gatherers/network-user-agent.js index e0b1c7284f03..ea41e7b6645e 100644 --- a/lighthouse-core/gather/gatherers/network-user-agent.js +++ b/lighthouse-core/gather/gatherers/network-user-agent.js @@ -5,8 +5,8 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const DevtoolsLogGatherer = require('./devtools-log.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import DevtoolsLogGatherer from './devtools-log.js'; /** @implements {LH.Gatherer.FRGathererInstance<'DevtoolsLog'>} */ class NetworkUserAgent extends FRGatherer { @@ -39,4 +39,4 @@ class NetworkUserAgent extends FRGatherer { } } -module.exports = NetworkUserAgent; +export default NetworkUserAgent; diff --git a/lighthouse-core/gather/gatherers/script-elements.js b/lighthouse-core/gather/gatherers/script-elements.js index 98b6d8ce8b02..617f38fa8729 100644 --- a/lighthouse-core/gather/gatherers/script-elements.js +++ b/lighthouse-core/gather/gatherers/script-elements.js @@ -5,11 +5,11 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const NetworkRecords = require('../../computed/network-records.js'); -const NetworkRequest = require('../../lib/network-request.js'); -const pageFunctions = require('../../lib/page-functions.js'); -const DevtoolsLog = require('./devtools-log.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import NetworkRecords from '../../computed/network-records.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import {pageFunctions} from '../../lib/page-functions.js'; +import DevtoolsLog from './devtools-log.js'; /* global getNodeDetails */ @@ -108,4 +108,4 @@ class ScriptElements extends FRGatherer { } } -module.exports = ScriptElements; +export default ScriptElements; diff --git a/lighthouse-core/gather/gatherers/scripts.js b/lighthouse-core/gather/gatherers/scripts.js index 4448d150fd7a..b9980177a16f 100644 --- a/lighthouse-core/gather/gatherers/scripts.js +++ b/lighthouse-core/gather/gatherers/scripts.js @@ -5,7 +5,7 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; /** * @template T, U @@ -137,4 +137,4 @@ class Scripts extends FRGatherer { } } -module.exports = Scripts; +export default Scripts; diff --git a/lighthouse-core/gather/gatherers/seo/embedded-content.js b/lighthouse-core/gather/gatherers/seo/embedded-content.js index e21178733743..3cfae69cebd2 100644 --- a/lighthouse-core/gather/gatherers/seo/embedded-content.js +++ b/lighthouse-core/gather/gatherers/seo/embedded-content.js @@ -7,8 +7,9 @@ /* globals getElementsInDocument getNodeDetails */ -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); -const pageFunctions = require('../../../lib/page-functions.js'); +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; + +import {pageFunctions} from '../../../lib/page-functions.js'; /** * @return {LH.Artifacts.EmbeddedContentInfo[]} @@ -61,4 +62,4 @@ class EmbeddedContent extends FRGatherer { } } -module.exports = EmbeddedContent; +export default EmbeddedContent; diff --git a/lighthouse-core/gather/gatherers/seo/font-size.js b/lighthouse-core/gather/gatherers/seo/font-size.js index 26a8afc67f7b..efbd18e83cfd 100644 --- a/lighthouse-core/gather/gatherers/seo/font-size.js +++ b/lighthouse-core/gather/gatherers/seo/font-size.js @@ -16,7 +16,8 @@ * This gatherer collects stylesheet metadata by itself, instead of relying on the styles gatherer which is slow (because it parses the stylesheet content). */ -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; + const FONT_SIZE_PROPERTY_NAME = 'font-size'; const MINIMAL_LEGIBLE_FONT_SIZE_PX = 12; // limit number of protocol calls to make sure that gatherer doesn't take more than 1-2s @@ -374,7 +375,9 @@ class FontSize extends FRGatherer { } } -module.exports = FontSize; -module.exports.computeSelectorSpecificity = computeSelectorSpecificity; -module.exports.getEffectiveFontRule = getEffectiveFontRule; -module.exports.findMostSpecificMatchedCSSRule = findMostSpecificMatchedCSSRule; +export default FontSize; +export { + computeSelectorSpecificity, + getEffectiveFontRule, + findMostSpecificMatchedCSSRule, +}; diff --git a/lighthouse-core/gather/gatherers/seo/robots-txt.js b/lighthouse-core/gather/gatherers/seo/robots-txt.js index 628e3160fc6e..1d244ed6f0ac 100644 --- a/lighthouse-core/gather/gatherers/seo/robots-txt.js +++ b/lighthouse-core/gather/gatherers/seo/robots-txt.js @@ -5,7 +5,7 @@ */ 'use strict'; -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; class RobotsTxt extends FRGatherer { /** @type {LH.Gatherer.GathererMeta} */ @@ -25,4 +25,4 @@ class RobotsTxt extends FRGatherer { } } -module.exports = RobotsTxt; +export default RobotsTxt; diff --git a/lighthouse-core/gather/gatherers/seo/tap-targets.js b/lighthouse-core/gather/gatherers/seo/tap-targets.js index 93eacec51f38..8f9d651f7d80 100644 --- a/lighthouse-core/gather/gatherers/seo/tap-targets.js +++ b/lighthouse-core/gather/gatherers/seo/tap-targets.js @@ -7,9 +7,10 @@ /* global document, window, getComputedStyle, getElementsInDocument, Node, getNodeDetails, getRectCenterPoint */ -const FRGatherer = require('../../../fraggle-rock/gather/base-gatherer.js'); -const pageFunctions = require('../../../lib/page-functions.js'); -const RectHelpers = require('../../../lib/rect-helpers.js'); +import FRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; + +import {pageFunctions} from '../../../lib/page-functions.js'; +import * as RectHelpers from '../../../lib/rect-helpers.js'; const TARGET_SELECTORS = [ 'button', @@ -367,4 +368,4 @@ class TapTargets extends FRGatherer { } } -module.exports = TapTargets; +export default TapTargets; diff --git a/lighthouse-core/gather/gatherers/service-worker.js b/lighthouse-core/gather/gatherers/service-worker.js index 211381024d04..c5a82a22921d 100644 --- a/lighthouse-core/gather/gatherers/service-worker.js +++ b/lighthouse-core/gather/gatherers/service-worker.js @@ -5,8 +5,8 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const serviceWorkers = require('../driver/service-workers.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import * as serviceWorkers from '../driver/service-workers.js'; class ServiceWorker extends FRGatherer { /** @type {LH.Gatherer.GathererMeta} */ @@ -42,4 +42,4 @@ class ServiceWorker extends FRGatherer { } } -module.exports = ServiceWorker; +export default ServiceWorker; diff --git a/lighthouse-core/gather/gatherers/source-maps.js b/lighthouse-core/gather/gatherers/source-maps.js index dac7e3bc7722..585c77ae6319 100644 --- a/lighthouse-core/gather/gatherers/source-maps.js +++ b/lighthouse-core/gather/gatherers/source-maps.js @@ -5,8 +5,8 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const URL = require('../../lib/url-shim.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; +import URL from '../../lib/url-shim.js'; /** * @fileoverview Gets JavaScript source maps. @@ -154,4 +154,4 @@ class SourceMaps extends FRGatherer { } } -module.exports = SourceMaps; +export default SourceMaps; diff --git a/lighthouse-core/gather/gatherers/stacks.js b/lighthouse-core/gather/gatherers/stacks.js index f0fe99fb8087..585403e5af4c 100644 --- a/lighthouse-core/gather/gatherers/stacks.js +++ b/lighthouse-core/gather/gatherers/stacks.js @@ -12,9 +12,17 @@ /* global window */ /* global d41d8cd98f00b204e9800998ecf8427e_LibraryDetectorTests */ -const fs = require('fs'); -const log = require('lighthouse-logger'); -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import fs from 'fs'; + +import log from 'lighthouse-logger'; +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; + +import {createRequire} from 'module'; + +// This is removed by rollup, because the only usage is to resolve a module path +// but that is replaced by the inline-fs plugin, leaving `require` unused. +const require = /* #__PURE__ */ createRequire(import.meta.url); + const libDetectorSource = fs.readFileSync( require.resolve('js-library-detector/library/libraries.js'), 'utf8'); @@ -122,4 +130,4 @@ class Stacks extends FRGatherer { } } -module.exports = Stacks; +export default Stacks; diff --git a/lighthouse-core/gather/gatherers/trace-compat.js b/lighthouse-core/gather/gatherers/trace-compat.js index 81db17c2aa75..097933a25f12 100644 --- a/lighthouse-core/gather/gatherers/trace-compat.js +++ b/lighthouse-core/gather/gatherers/trace-compat.js @@ -11,8 +11,9 @@ * when devtools logs and traces were special-cased. */ -const TraceGatherer = require('./trace.js'); -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import TraceGatherer from './trace.js'; + +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; /** @implements {LH.Gatherer.FRGathererInstance<'Trace'>} */ class TraceCompat extends FRGatherer { @@ -33,4 +34,4 @@ class TraceCompat extends FRGatherer { } } -module.exports = TraceCompat; +export default TraceCompat; diff --git a/lighthouse-core/gather/gatherers/trace-elements.js b/lighthouse-core/gather/gatherers/trace-elements.js index ff36e7543817..e7c52d138242 100644 --- a/lighthouse-core/gather/gatherers/trace-elements.js +++ b/lighthouse-core/gather/gatherers/trace-elements.js @@ -13,16 +13,17 @@ * We take the backend nodeId from the trace and use it to find the corresponding element in the DOM. */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const {resolveNodeIdToObjectId} = require('../driver/dom.js'); -const pageFunctions = require('../../lib/page-functions.js'); -const RectHelpers = require('../../lib/rect-helpers.js'); -const Sentry = require('../../lib/sentry.js'); -const Trace = require('./trace.js'); -const ProcessedTrace = require('../../computed/processed-trace.js'); -const ProcessedNavigation = require('../../computed/processed-navigation.js'); -const LighthouseError = require('../../lib/lh-error.js'); -const ComputedResponsivenes = require('../../computed/metrics/responsiveness.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; + +import {resolveNodeIdToObjectId} from '../driver/dom.js'; +import {pageFunctions} from '../../lib/page-functions.js'; +import * as RectHelpers from '../../lib/rect-helpers.js'; +import {Sentry} from '../../lib/sentry.js'; +import Trace from './trace.js'; +import ProcessedTrace from '../../computed/processed-trace.js'; +import ProcessedNavigation from '../../computed/processed-navigation.js'; +import {LighthouseError} from '../../lib/lh-error.js'; +import ComputedResponsiveness from '../../computed/metrics/responsiveness.js'; /** @typedef {{nodeId: number, score?: number, animations?: {name?: string, failureReasonsMask?: number, unsupportedProperties?: string[]}[]}} TraceElementData */ @@ -151,7 +152,7 @@ class TraceElements extends FRGatherer { static async getResponsivenessElement(trace, context) { const {settings} = context; try { - const responsivenessEvent = await ComputedResponsivenes.request({trace, settings}, context); + const responsivenessEvent = await ComputedResponsiveness.request({trace, settings}, context); if (!responsivenessEvent || responsivenessEvent.name === 'FallbackTiming') return; return {nodeId: responsivenessEvent.args.data.nodeId}; } catch { @@ -327,4 +328,4 @@ class TraceElements extends FRGatherer { } } -module.exports = TraceElements; +export default TraceElements; diff --git a/lighthouse-core/gather/gatherers/trace.js b/lighthouse-core/gather/gatherers/trace.js index ebb55b0d5a81..6117c424a7cb 100644 --- a/lighthouse-core/gather/gatherers/trace.js +++ b/lighthouse-core/gather/gatherers/trace.js @@ -11,8 +11,9 @@ * This protocol log can be used to recreate the network records using lib/network-recorder.js. */ -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); -const TraceProcessor = require('../../lib/tracehouse/trace-processor.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; + +import {TraceProcessor} from '../../lib/tracehouse/trace-processor.js'; class Trace extends FRGatherer { /** @type {LH.Trace} */ @@ -128,4 +129,4 @@ class Trace extends FRGatherer { } } -module.exports = Trace; +export default Trace; diff --git a/lighthouse-core/gather/gatherers/viewport-dimensions.js b/lighthouse-core/gather/gatherers/viewport-dimensions.js index c27c2205b248..71ae1f456c7f 100644 --- a/lighthouse-core/gather/gatherers/viewport-dimensions.js +++ b/lighthouse-core/gather/gatherers/viewport-dimensions.js @@ -5,7 +5,7 @@ */ 'use strict'; -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; /* global window */ @@ -55,4 +55,4 @@ class ViewportDimensions extends FRGatherer { } } -module.exports = ViewportDimensions; +export default ViewportDimensions; diff --git a/lighthouse-core/gather/gatherers/web-app-manifest.js b/lighthouse-core/gather/gatherers/web-app-manifest.js index 6736755d4653..655991d1a89c 100644 --- a/lighthouse-core/gather/gatherers/web-app-manifest.js +++ b/lighthouse-core/gather/gatherers/web-app-manifest.js @@ -5,9 +5,9 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const manifestParser = require('../../lib/manifest-parser.js'); -const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js'); +import log from 'lighthouse-logger'; +import {parseManifest} from '../../lib/manifest-parser.js'; +import FRGatherer from '../../fraggle-rock/gather/base-gatherer.js'; class WebAppManifest extends FRGatherer { /** @type {LH.Gatherer.GathererMeta} */ @@ -83,7 +83,7 @@ class WebAppManifest extends FRGatherer { log.time(status); const response = await WebAppManifest.fetchAppManifest(session); if (!response) return null; - const manifest = manifestParser(response.data, response.url, pageUrl); + const manifest = parseManifest(response.data, response.url, pageUrl); log.timeEnd(status); return manifest; } @@ -99,4 +99,4 @@ class WebAppManifest extends FRGatherer { } } -module.exports = WebAppManifest; +export default WebAppManifest; diff --git a/lighthouse-core/index.cjs b/lighthouse-core/index.cjs new file mode 100644 index 000000000000..33fa7357601a --- /dev/null +++ b/lighthouse-core/index.cjs @@ -0,0 +1,21 @@ +/** + * @license Copyright 2022 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'; + +/** @type {import('./index.js')['default']} */ +const lighthouse = async function lighthouse(...args) { + const {default: lighthouse} = await import('./index.js'); + return lighthouse(...args); +}; + +/** @type {import('./index.js')['legacyNavigation']} */ +const legacyNavigation = async function legacyNavigation(...args) { + const {legacyNavigation} = await import('./index.js'); + return legacyNavigation(...args); +}; + +module.exports = lighthouse; +module.exports.legacyNavigation = legacyNavigation; diff --git a/lighthouse-core/index.js b/lighthouse-core/index.js index 372ddf094eea..3baac58f3abf 100644 --- a/lighthouse-core/index.js +++ b/lighthouse-core/index.js @@ -5,16 +5,17 @@ */ 'use strict'; -const Runner = require('./runner.js'); -const log = require('lighthouse-logger'); -const ChromeProtocol = require('./gather/connections/cri.js'); -const Config = require('./config/config.js'); -const URL = require('./lib/url-shim.js'); -const fraggleRock = require('./fraggle-rock/api.js'); -const {initializeConfig} = require('./fraggle-rock/config/config.js'); -const {flagsToFRContext} = require('./config/config-helpers.js'); +import {Runner} from './runner.js'; +import log from 'lighthouse-logger'; +import {CriConnection} from './gather/connections/cri.js'; +import {Config} from './config/config.js'; +import URL from './lib/url-shim.js'; +import * as fraggleRock from './fraggle-rock/api.js'; +import {Driver} from './gather/driver.js'; +import {flagsToFRContext} from './config/config-helpers.js'; +import {initializeConfig} from './fraggle-rock/config/config.js'; -/** @typedef {import('./gather/connections/connection.js')} Connection */ +/** @typedef {import('./gather/connections/connection.js').Connection} Connection */ /* * The relationship between these root modules: @@ -64,7 +65,7 @@ async function legacyNavigation(url, flags = {}, configJSON, userConnection) { const config = await generateLegacyConfig(configJSON, flags); const computedCache = new Map(); const options = {config, computedCache}; - const connection = userConnection || new ChromeProtocol(flags.port, flags.hostname); + const connection = userConnection || new CriConnection(flags.port, flags.hostname); // kick off a lighthouse run const artifacts = await Runner.gather(() => { @@ -103,17 +104,18 @@ function generateLegacyConfig(configJson, flags) { return Config.fromJson(configJson, flags); } -lighthouse.legacyNavigation = legacyNavigation; -lighthouse.generateConfig = generateConfig; -lighthouse.generateLegacyConfig = generateLegacyConfig; -lighthouse.getAuditList = Runner.getAuditList; -lighthouse.traceCategories = require('./gather/driver.js').traceCategories; -lighthouse.Audit = require('./audits/audit.js'); -lighthouse.Gatherer = require('./fraggle-rock/gather/base-gatherer.js'); - -// Explicit type reference (hidden by makeComputedArtifact) for d.ts export. -// TODO(esmodules): should be a workaround for module.export and can be removed when in esm. -/** @type {typeof import('./computed/network-records.js')} */ -lighthouse.NetworkRecords = require('./computed/network-records.js'); +function getAuditList() { + return Runner.getAuditList(); +} -module.exports = lighthouse; +export default lighthouse; +export {Audit} from './audits/audit.js'; +export {default as Gatherer} from './fraggle-rock/gather/base-gatherer.js'; +export {default as NetworkRecords} from './computed/network-records.js'; +export { + legacyNavigation, + generateConfig, + generateLegacyConfig, + getAuditList, +}; +export const traceCategories = Driver.traceCategories; diff --git a/lighthouse-core/lib/arbitrary-equality-map.js b/lighthouse-core/lib/arbitrary-equality-map.js index 3386153ca2d5..1b9682fc2e75 100644 --- a/lighthouse-core/lib/arbitrary-equality-map.js +++ b/lighthouse-core/lib/arbitrary-equality-map.js @@ -5,7 +5,7 @@ */ 'use strict'; -const isDeepEqual = require('lodash/isEqual.js'); +import isDeepEqual from 'lodash/isEqual.js'; /** * @fileoverview This class is designed to allow maps with arbitrary equality functions. @@ -78,4 +78,4 @@ class ArbitraryEqualityMap { } } -module.exports = ArbitraryEqualityMap; +export {ArbitraryEqualityMap}; diff --git a/lighthouse-core/lib/asset-saver.js b/lighthouse-core/lib/asset-saver.js index e4ca58d44c4d..299ce9b29419 100644 --- a/lighthouse-core/lib/asset-saver.js +++ b/lighthouse-core/lib/asset-saver.js @@ -5,17 +5,20 @@ */ 'use strict'; -const fs = require('fs'); -const path = require('path'); -const log = require('lighthouse-logger'); -const stream = require('stream'); -const {promisify} = require('util'); -const Simulator = require('./dependency-graph/simulator/simulator.js'); -const lanternTraceSaver = require('./lantern-trace-saver.js'); -const Metrics = require('./traces/pwmetrics-events.js'); -const NetworkAnalysisComputed = require('../computed/network-analysis.js'); -const LoadSimulatorComputed = require('../computed/load-simulator.js'); -const LighthouseError = require('../lib/lh-error.js'); +import fs from 'fs'; +import path from 'path'; +import log from 'lighthouse-logger'; +import stream from 'stream'; +import util from 'util'; +import {Simulator} from './dependency-graph/simulator/simulator.js'; +import lanternTraceSaver from './lantern-trace-saver.js'; +import {Metrics} from './traces/pwmetrics-events.js'; +import NetworkAnalysisComputed from '../computed/network-analysis.js'; +import LoadSimulatorComputed from '../computed/load-simulator.js'; +import {LighthouseError} from '../lib/lh-error.js'; + +const {promisify} = util; + // TODO(esmodules): Rollup does not support `promisfy` or `stream.pipeline`. Bundled files // don't need anything in this file except for `stringifyReplacer`, so a check for // truthiness before using is enough. @@ -326,7 +329,7 @@ function normalizeTimingEntries(timings) { } } -module.exports = { +export { saveArtifacts, saveLhr, loadArtifacts, diff --git a/lighthouse-core/lib/axe.js b/lighthouse-core/lib/axe.js index aae144e037fd..e82182e570e5 100644 --- a/lighthouse-core/lib/axe.js +++ b/lighthouse-core/lib/axe.js @@ -5,9 +5,14 @@ */ 'use strict'; -const fs = require('fs'); -const source = fs.readFileSync(require.resolve('axe-core/axe.min.js'), 'utf8'); +import fs from 'fs'; +import {createRequire} from 'module'; -module.exports = { - source, +// This is removed by rollup, because the only usage is to resolve a module path +// but that is replaced by the inline-fs plugin, leaving `require` unused. +const require = /* #__PURE__ */ createRequire(import.meta.url); +const axeSource = fs.readFileSync(require.resolve('axe-core/axe.min.js'), 'utf8'); + +export { + axeSource, }; diff --git a/lighthouse-core/lib/cdt/package.json b/lighthouse-core/lib/cdt/package.json new file mode 100644 index 000000000000..99fdb9bc7c52 --- /dev/null +++ b/lighthouse-core/lib/cdt/package.json @@ -0,0 +1,4 @@ +{ + "type": "commonjs", + "//": "Temporary file until made esm" +} \ No newline at end of file diff --git a/lighthouse-core/lib/csp-evaluator.js b/lighthouse-core/lib/csp-evaluator.js index 5ca26bdbdd29..3bc4b7f50f0d 100644 --- a/lighthouse-core/lib/csp-evaluator.js +++ b/lighthouse-core/lib/csp-evaluator.js @@ -7,18 +7,16 @@ /** @typedef {import('csp_evaluator/finding').Finding} Finding */ -const { - evaluateForFailure, - evaluateForSyntaxErrors, - evaluateForWarnings, -} = require('csp_evaluator/dist/lighthouse/lighthouse_checks.js'); -const {Type} = require('csp_evaluator/dist/finding.js'); -const {CspParser} = require('csp_evaluator/dist/parser.js'); -const {Directive} = require('csp_evaluator/dist/csp.js'); +import { + evaluateForFailure, evaluateForSyntaxErrors, evaluateForWarnings, +} from 'csp_evaluator/dist/lighthouse/lighthouse_checks.js'; -const log = require('lighthouse-logger'); -const i18n = require('../lib/i18n/i18n.js'); -const {isIcuMessage} = require('../../shared/localization/format.js'); +import {Type} from 'csp_evaluator/dist/finding.js'; +import {CspParser} from 'csp_evaluator/dist/parser.js'; +import {Directive} from 'csp_evaluator/dist/csp.js'; +import log from 'lighthouse-logger'; +import * as i18n from '../lib/i18n/i18n.js'; +import {isIcuMessage} from '../../shared/localization/format.js'; const UIStrings = { /** Message shown when a CSP does not have a base-uri directive. Shown in a table with a list of other CSP vulnerabilities and suggestions. "CSP" stands for "Content Security Policy". "base-uri", "'none'", and "'self'" do not need to be translated. */ @@ -90,7 +88,7 @@ const UIStrings = { 'Plain URL schemes allow scripts to be sourced from an unsafe domain.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @type {Record<number, string|LH.IcuMessage|Record<string, LH.IcuMessage>>} */ const FINDING_TO_UI_STRING = { @@ -165,7 +163,7 @@ function evaluateRawCspsForXss(rawCsps) { return {bypasses, warnings, syntax}; } -module.exports = { +export { getTranslatedDescription, evaluateRawCspsForXss, parseCsp, diff --git a/lighthouse-core/lib/dependency-graph/base-node.js b/lighthouse-core/lib/dependency-graph/base-node.js index 18fbb2a0cfba..90ce1923a6ae 100644 --- a/lighthouse-core/lib/dependency-graph/base-node.js +++ b/lighthouse-core/lib/dependency-graph/base-node.js @@ -8,7 +8,7 @@ /** * A union of all types derived from BaseNode, allowing type check discrimination * based on `node.type`. If a new node type is created, it should be added here. - * @typedef {import('./cpu-node.js') | import('./network-node.js')} Node + * @typedef {import('./cpu-node.js').CPUNode | import('./network-node.js').NetworkNode} Node */ /** @@ -360,4 +360,4 @@ BaseNode.TYPES = /** @type {{NETWORK: 'network', CPU: 'cpu'}} */({ CPU: 'cpu', }); -module.exports = BaseNode; +export {BaseNode}; diff --git a/lighthouse-core/lib/dependency-graph/cpu-node.js b/lighthouse-core/lib/dependency-graph/cpu-node.js index 10c5afbde4c8..3e034a961e4f 100644 --- a/lighthouse-core/lib/dependency-graph/cpu-node.js +++ b/lighthouse-core/lib/dependency-graph/cpu-node.js @@ -5,7 +5,7 @@ */ 'use strict'; -const BaseNode = require('./base-node.js'); +import {BaseNode} from './base-node.js'; class CPUNode extends BaseNode { /** @@ -83,4 +83,4 @@ class CPUNode extends BaseNode { } } -module.exports = CPUNode; +export {CPUNode}; diff --git a/lighthouse-core/lib/dependency-graph/network-node.js b/lighthouse-core/lib/dependency-graph/network-node.js index f2de8d8e9ea8..a53938a0bccc 100644 --- a/lighthouse-core/lib/dependency-graph/network-node.js +++ b/lighthouse-core/lib/dependency-graph/network-node.js @@ -5,8 +5,8 @@ */ 'use strict'; -const BaseNode = require('./base-node.js'); -const NetworkRequest = require('../network-request.js'); +import {BaseNode} from './base-node.js'; +import {NetworkRequest} from '../network-request.js'; class NetworkNode extends BaseNode { /** @@ -96,4 +96,4 @@ class NetworkNode extends BaseNode { } } -module.exports = NetworkNode; +export {NetworkNode}; diff --git a/lighthouse-core/lib/dependency-graph/simulator/connection-pool.js b/lighthouse-core/lib/dependency-graph/simulator/connection-pool.js index e9594f93d194..15954aff1a9f 100644 --- a/lighthouse-core/lib/dependency-graph/simulator/connection-pool.js +++ b/lighthouse-core/lib/dependency-graph/simulator/connection-pool.js @@ -5,8 +5,8 @@ */ 'use strict'; -const NetworkAnalyzer = require('./network-analyzer.js'); -const TcpConnection = require('./tcp-connection.js'); +import {NetworkAnalyzer} from './network-analyzer.js'; +import {TcpConnection} from './tcp-connection.js'; const DEFAULT_SERVER_RESPONSE_TIME = 30; const TLS_SCHEMES = ['https', 'wss']; @@ -15,7 +15,7 @@ const TLS_SCHEMES = ['https', 'wss']; // https://cs.chromium.org/chromium/src/net/socket/client_socket_pool_manager.cc?type=cs&q="int+g_max_sockets_per_group" const CONNECTIONS_PER_ORIGIN = 6; -module.exports = class ConnectionPool { +export class ConnectionPool { /** * @param {LH.Artifacts.NetworkRequest[]} records * @param {Required<LH.Gatherer.Simulation.Options>} options @@ -168,4 +168,4 @@ module.exports = class ConnectionPool { this._connectionsByRecord.delete(record); this._connectionsInUse.delete(connection); } -}; +} diff --git a/lighthouse-core/lib/dependency-graph/simulator/dns-cache.js b/lighthouse-core/lib/dependency-graph/simulator/dns-cache.js index 5a03336f23b1..2e1528ffb078 100644 --- a/lighthouse-core/lib/dependency-graph/simulator/dns-cache.js +++ b/lighthouse-core/lib/dependency-graph/simulator/dns-cache.js @@ -70,4 +70,4 @@ class DNSCache { DNSCache.RTT_MULTIPLIER = DNS_RESOLUTION_RTT_MULTIPLIER; -module.exports = DNSCache; +export {DNSCache}; diff --git a/lighthouse-core/lib/dependency-graph/simulator/network-analyzer.js b/lighthouse-core/lib/dependency-graph/simulator/network-analyzer.js index 30055c9d06fb..bf66ad4064c5 100644 --- a/lighthouse-core/lib/dependency-graph/simulator/network-analyzer.js +++ b/lighthouse-core/lib/dependency-graph/simulator/network-analyzer.js @@ -5,8 +5,9 @@ */ 'use strict'; +import URL from '../../url-shim.js'; + const INITIAL_CWD = 14 * 1024; -const URL = require('../../url-shim.js'); // Assume that 40% of TTFB was server response time by default for static assets const DEFAULT_SERVER_RESPONSE_PERCENTAGE = 0.4; @@ -47,7 +48,7 @@ class NetworkAnalyzer { /** * @param {number[]} values - * @return {NetworkAnalyzer.Summary} + * @return {Summary} */ static getSummary(values) { values.sort((a, b) => a - b); @@ -62,7 +63,7 @@ class NetworkAnalyzer { /** * @param {Map<string,number[]>} values - * @return {Map<string, NetworkAnalyzer.Summary>} + * @return {Map<string, Summary>} */ static summarize(values) { const summaryByKey = new Map(); @@ -302,8 +303,8 @@ class NetworkAnalyzer { * is unavailable. * * @param {LH.Artifacts.NetworkRequest[]} records - * @param {NetworkAnalyzer.RTTEstimateOptions} [options] - * @return {Map<string, NetworkAnalyzer.Summary>} + * @param {RTTEstimateOptions} [options] + * @return {Map<string, Summary>} */ static estimateRTTByOrigin(records, options) { const { @@ -354,8 +355,8 @@ class NetworkAnalyzer { * estimated automatically if not provided. * * @param {LH.Artifacts.NetworkRequest[]} records - * @param {NetworkAnalyzer.RTTEstimateOptions & {rttByOrigin?: Map<string, number>}} [options] - * @return {Map<string, NetworkAnalyzer.Summary>} + * @param {RTTEstimateOptions & {rttByOrigin?: Map<string, number>}} [options] + * @return {Map<string, Summary>} */ static estimateServerResponseTimeByOrigin(records, options) { let rttByOrigin = (options || {}).rttByOrigin; @@ -457,10 +458,10 @@ class NetworkAnalyzer { } } -module.exports = NetworkAnalyzer; +export {NetworkAnalyzer}; /** - * @typedef NetworkAnalyzer.Summary + * @typedef Summary * @property {number} min * @property {number} max * @property {number} avg @@ -468,7 +469,7 @@ module.exports = NetworkAnalyzer; */ /** - * @typedef NetworkAnalyzer.RTTEstimateOptions + * @typedef RTTEstimateOptions * @property {boolean} [forceCoarseEstimates] TCP connection handshake information will be used when available, but in some circumstances this data can be unreliable. This flag exposes an option to ignore the handshake data and use the coarse download/TTFB timing data. * @property {number} [coarseEstimateMultiplier] Coarse estimates include lots of extra time and noise multiply by some factor to deflate the estimates a bit. * @property {boolean} [useDownloadEstimates] Useful for testing to isolate the different methods of estimation. diff --git a/lighthouse-core/lib/dependency-graph/simulator/simulator-timing-map.js b/lighthouse-core/lib/dependency-graph/simulator/simulator-timing-map.js index 0a1e8cfdd59a..4d9a0d641224 100644 --- a/lighthouse-core/lib/dependency-graph/simulator/simulator-timing-map.js +++ b/lighthouse-core/lib/dependency-graph/simulator/simulator-timing-map.js @@ -5,7 +5,7 @@ */ 'use strict'; -const BaseNode = require('../base-node.js'); +import {BaseNode} from '../base-node.js'; /** * @fileoverview @@ -16,9 +16,9 @@ const BaseNode = require('../base-node.js'); */ -/** @typedef {BaseNode.Node} Node */ -/** @typedef {import('../network-node')} NetworkNode */ -/** @typedef {import('../cpu-node')} CpuNode */ +/** @typedef {import('../base-node.js').Node} Node */ +/** @typedef {import('../network-node').NetworkNode} NetworkNode */ +/** @typedef {import('../cpu-node').CPUNode} CpuNode */ /** * @typedef NodeTimingComplete @@ -209,4 +209,4 @@ class SimulatorTimingMap { } } -module.exports = SimulatorTimingMap; +export {SimulatorTimingMap}; diff --git a/lighthouse-core/lib/dependency-graph/simulator/simulator.js b/lighthouse-core/lib/dependency-graph/simulator/simulator.js index 881345eab3fc..bf8ad017300a 100644 --- a/lighthouse-core/lib/dependency-graph/simulator/simulator.js +++ b/lighthouse-core/lib/dependency-graph/simulator/simulator.js @@ -5,16 +5,18 @@ */ 'use strict'; -const BaseNode = require('../base-node.js'); -const TcpConnection = require('./tcp-connection.js'); -const ConnectionPool = require('./connection-pool.js'); -const DNSCache = require('./dns-cache.js'); -const mobileSlow4G = require('../../../config/constants.js').throttling.mobileSlow4G; -const SimulatorTimingMap = require('./simulator-timing-map.js'); +import {BaseNode} from '../base-node.js'; +import {TcpConnection} from './tcp-connection.js'; +import {ConnectionPool} from './connection-pool.js'; +import {DNSCache} from './dns-cache.js'; +import {SimulatorTimingMap} from './simulator-timing-map.js'; +import * as constants from '../../../config/constants.js'; -/** @typedef {BaseNode.Node} Node */ -/** @typedef {import('../network-node')} NetworkNode */ -/** @typedef {import('../cpu-node')} CpuNode */ +const mobileSlow4G = constants.throttling.mobileSlow4G; + +/** @typedef {import('../base-node.js').Node} Node */ +/** @typedef {import('../network-node').NetworkNode} NetworkNode */ +/** @typedef {import('../cpu-node').CPUNode} CpuNode */ // see https://cs.chromium.org/search/?q=kDefaultMaxNumDelayableRequestsPerClient&sq=package:chromium&type=cs const DEFAULT_MAXIMUM_CONCURRENT_REQUESTS = 10; @@ -520,4 +522,4 @@ class Simulator { } } -module.exports = Simulator; +export {Simulator}; diff --git a/lighthouse-core/lib/dependency-graph/simulator/tcp-connection.js b/lighthouse-core/lib/dependency-graph/simulator/tcp-connection.js index b8812c88b6ec..a2734d7c5505 100644 --- a/lighthouse-core/lib/dependency-graph/simulator/tcp-connection.js +++ b/lighthouse-core/lib/dependency-graph/simulator/tcp-connection.js @@ -187,7 +187,7 @@ class TcpConnection { } } -module.exports = TcpConnection; +export {TcpConnection}; /** * @typedef DownloadOptions diff --git a/lighthouse-core/lib/emulation.js b/lighthouse-core/lib/emulation.js index 59ca17afd174..316e32bdddd3 100644 --- a/lighthouse-core/lib/emulation.js +++ b/lighthouse-core/lib/emulation.js @@ -5,7 +5,7 @@ */ 'use strict'; -const {version: lighthouseVersion} = require('../../package.json'); +import {lighthouseVersion} from '../../root.js'; const NO_THROTTLING_METRICS = { latency: 0, @@ -153,7 +153,7 @@ function clearCPUThrottling(session) { return session.sendCommand('Emulation.setCPUThrottlingRate', NO_CPU_THROTTLE_METRICS); } -module.exports = { +export { emulate, throttle, clearThrottling, diff --git a/lighthouse-core/lib/i18n/README.md b/lighthouse-core/lib/i18n/README.md index 09aee90feb4e..aaaea6245ec3 100644 --- a/lighthouse-core/lib/i18n/README.md +++ b/lighthouse-core/lib/i18n/README.md @@ -232,7 +232,7 @@ CTC is a name that is distinct and identifies this as the Chrome translation for }; // Init the strings in this file with the i18n system. - const str_ = i18n.createIcuMessageFn(__filename, UIStrings); + const str_ = i18n.createIcuMessageFn(import.meta.url, UIStrings); // Create an IcuMessage instance with a replacement value for our localizable string. const icuMessage = str_(UIStrings.totalSize, {totalBytes: 10240}); diff --git a/lighthouse-core/lib/i18n/i18n.js b/lighthouse-core/lib/i18n/i18n.js index 4abdad25f405..743af1a6f227 100644 --- a/lighthouse-core/lib/i18n/i18n.js +++ b/lighthouse-core/lib/i18n/i18n.js @@ -7,16 +7,14 @@ /** @typedef {import('../../../shared/localization/locales').LhlMessages} LhlMessages */ -const path = require('path'); -const lookupClosestLocale = require('lookup-closest-locale'); -const {getAvailableLocales} = require('../../../shared/localization/format.js'); -const log = require('lighthouse-logger'); -const {LH_ROOT} = require('../../../root.js'); -const { - isIcuMessage, - formatMessage, - DEFAULT_LOCALE, -} = require('../../../shared/localization/format.js'); +import path from 'path'; + +import lookupClosestLocale from 'lookup-closest-locale'; +import {getAvailableLocales} from '../../../shared/localization/format.js'; +import log from 'lighthouse-logger'; +import {LH_ROOT} from '../../../root.js'; +import {isIcuMessage, formatMessage, DEFAULT_LOCALE} from '../../../shared/localization/format.js'; +import {getModulePath} from '../../../esm-utils.js'; const UIStrings = { /** Used to show the duration in milliseconds that something lasted. The `{timeInMs}` placeholder will be replaced with the time duration, shown in milliseconds (e.g. 63 ms) */ @@ -172,6 +170,8 @@ function lookupLocale(locales, possibleLocales) { * @param {Record<string, string>} fileStrings */ function createIcuMessageFn(filename, fileStrings) { + filename = filename.replace('file://', ''); + /** * Combined so fn can access both caller's strings and i18n.UIStrings shared across LH. * @type {Record<string, string>} @@ -188,7 +188,7 @@ function createIcuMessageFn(filename, fileStrings) { const keyname = Object.keys(mergedStrings).find(key => mergedStrings[key] === message); if (!keyname) throw new Error(`Could not locate: ${message}`); - const filenameToLookup = keyname in fileStrings ? filename : __filename; + const filenameToLookup = keyname in fileStrings ? filename : getModulePath(import.meta); const unixStyleFilename = path.relative(LH_ROOT, filenameToLookup).replace(/\\/g, '/'); const i18nId = `${unixStyleFilename} | ${keyname}`; @@ -211,11 +211,11 @@ function isStringOrIcuMessage(value) { return typeof value === 'string' || isIcuMessage(value); } -module.exports = { +export { UIStrings, lookupLocale, createIcuMessageFn, isStringOrIcuMessage, // TODO: exported for backwards compatibility. Consider removing on future breaking change. - createMessageInstanceIdFn: createIcuMessageFn, + createIcuMessageFn as createMessageInstanceIdFn, }; diff --git a/lighthouse-core/lib/icons.js b/lighthouse-core/lib/icons.js index fb38a7b7c0ac..ae245bf4e982 100644 --- a/lighthouse-core/lib/icons.js +++ b/lighthouse-core/lib/icons.js @@ -5,7 +5,7 @@ */ 'use strict'; -const URL = require('./url-shim.js'); +import URL from './url-shim.js'; /** * @param {NonNullable<LH.Artifacts.Manifest['value']>} manifest @@ -78,7 +78,7 @@ function containsMaskableIcon(manifest) { }); } -module.exports = { +export { doExist, pngSizedAtLeast, containsMaskableIcon, diff --git a/lighthouse-core/lib/lantern-trace-saver.js b/lighthouse-core/lib/lantern-trace-saver.js index 6ed5dd27ef64..bfd8a5a2bc76 100644 --- a/lighthouse-core/lib/lantern-trace-saver.js +++ b/lighthouse-core/lib/lantern-trace-saver.js @@ -186,7 +186,7 @@ function convertNodeTimingsToTrace(nodeTimings) { } } -module.exports = { +export default { simulationNamesToIgnore: [ 'unlabeled', // These node timings should be nearly identical to the ones produced for Interactive diff --git a/lighthouse-core/lib/lh-env.js b/lighthouse-core/lib/lh-env.js index 8f01cacbc3d5..342be3cd24c8 100644 --- a/lighthouse-core/lib/lh-env.js +++ b/lighthouse-core/lib/lh-env.js @@ -5,10 +5,12 @@ */ 'use strict'; -const process = require('process'); +import process from 'process'; -module.exports = { - // NODE_ENV is set to test by mocha-setup.js and the smokehouse CLI runner - // CI as a catchall for everything we do in GitHub Actions - isUnderTest: !!process.env.CI || process.env.NODE_ENV === 'test', +// NODE_ENV is set to test by mocha-setup.js and the smokehouse CLI runner +// CI as a catchall for everything we do in GitHub Actions +const isUnderTest = !!process.env.CI || process.env.NODE_ENV === 'test'; + +export { + isUnderTest, }; diff --git a/lighthouse-core/lib/lh-error.js b/lighthouse-core/lib/lh-error.js index 31bcd78f6cfa..1ac98caec585 100644 --- a/lighthouse-core/lib/lh-error.js +++ b/lighthouse-core/lib/lh-error.js @@ -5,7 +5,7 @@ */ 'use strict'; -const i18n = require('./i18n/i18n.js'); +import * as i18n from './i18n/i18n.js'; /* eslint-disable max-len */ const UIStrings = { @@ -89,7 +89,7 @@ const UIStrings = { oldChromeDoesNotSupportFeature: 'This version of Chrome is too old to support \'{featureName}\'. Use a newer version to see full results.', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); /** @@ -417,5 +417,5 @@ const ERRORS = { LighthouseError.errors = ERRORS; LighthouseError.NO_ERROR = 'NO_ERROR'; LighthouseError.UNKNOWN_ERROR = 'UNKNOWN_ERROR'; -module.exports = LighthouseError; -module.exports.UIStrings = UIStrings; + +export {LighthouseError, UIStrings}; diff --git a/lighthouse-core/lib/lh-trace-processor.js b/lighthouse-core/lib/lh-trace-processor.js index e7a7c4dac825..4cbf2ae9420f 100644 --- a/lighthouse-core/lib/lh-trace-processor.js +++ b/lighthouse-core/lib/lh-trace-processor.js @@ -5,8 +5,8 @@ */ 'use strict'; -const LighthouseError = require('../lib/lh-error.js'); -const TraceProcessor = require('../lib/tracehouse/trace-processor.js'); +import {LighthouseError} from '../lib/lh-error.js'; +import {TraceProcessor} from '../lib/tracehouse/trace-processor.js'; // TraceProcessor throws generic errors, but we'd like our special localized and code-specific LighthouseError // objects to be thrown instead. @@ -43,4 +43,4 @@ class LHTraceProcessor extends TraceProcessor { } } -module.exports = LHTraceProcessor; +export default LHTraceProcessor; diff --git a/lighthouse-core/lib/manifest-parser.js b/lighthouse-core/lib/manifest-parser.js index 01f1cba9e08d..d79173fa29b7 100644 --- a/lighthouse-core/lib/manifest-parser.js +++ b/lighthouse-core/lib/manifest-parser.js @@ -5,8 +5,8 @@ */ 'use strict'; -const URL = require('./url-shim.js'); -const cssParsers = require('cssstyle/lib/parsers'); +import URL from './url-shim.js'; +import cssParsers from 'cssstyle/lib/parsers.js'; const ALLOWED_DISPLAY_VALUES = [ 'fullscreen', @@ -458,7 +458,7 @@ function parseBackgroundColor(jsonInput) { * @param {string} manifestUrl URL of manifest file. * @param {string} documentUrl URL of document containing manifest link element. */ -function parse(string, manifestUrl, documentUrl) { +function parseManifest(string, manifestUrl, documentUrl) { if (manifestUrl === undefined || documentUrl === undefined) { throw new Error('Manifest and document URLs required for manifest parsing.'); } @@ -510,4 +510,4 @@ function parse(string, manifestUrl, documentUrl) { }; } -module.exports = parse; +export {parseManifest}; diff --git a/lighthouse-core/lib/median-run.js b/lighthouse-core/lib/median-run.js index 3cb91cc43ee3..6832fc9fdeeb 100644 --- a/lighthouse-core/lib/median-run.js +++ b/lighthouse-core/lib/median-run.js @@ -89,4 +89,4 @@ function filterToValidRuns(runs) { .filter(run => Number.isFinite(getNumericValue(run, 'interactive'))); } -module.exports = {computeMedianRun, filterToValidRuns}; +export {computeMedianRun, filterToValidRuns}; diff --git a/lighthouse-core/lib/minification-estimator.js b/lighthouse-core/lib/minification-estimator.js index 4deed7d81e39..0389946f01c9 100644 --- a/lighthouse-core/lib/minification-estimator.js +++ b/lighthouse-core/lib/minification-estimator.js @@ -190,4 +190,4 @@ function computeCSSTokenLength(content) { return computeTokenLength(content, {singlelineComments: false, regex: false}); } -module.exports = {computeJSTokenLength, computeCSSTokenLength}; +export {computeJSTokenLength, computeCSSTokenLength}; diff --git a/lighthouse-core/lib/minify-devtoolslog.js b/lighthouse-core/lib/minify-devtoolslog.js index 629bd20fbfc7..c472edc92a03 100644 --- a/lighthouse-core/lib/minify-devtoolslog.js +++ b/lighthouse-core/lib/minify-devtoolslog.js @@ -84,4 +84,4 @@ function minifyDevtoolsLog(log) { }); } -module.exports = {minifyDevtoolsLog}; +export {minifyDevtoolsLog}; diff --git a/lighthouse-core/lib/minify-trace.js b/lighthouse-core/lib/minify-trace.js index a01111225dab..3773c61da0d6 100644 --- a/lighthouse-core/lib/minify-trace.js +++ b/lighthouse-core/lib/minify-trace.js @@ -15,7 +15,7 @@ * - lighthouse-core/lib/tracehouse/trace-processor.js */ -const TracingProcessor = require('./tracehouse/trace-processor.js'); +import {TraceProcessor} from './tracehouse/trace-processor.js'; const toplevelTaskNames = new Set([ 'RunTask', // m71+ @@ -94,7 +94,7 @@ const traceEventsToKeepInProcess = new Set([ * @param {LH.TraceEvent[]} events */ function filterOutUnnecessaryTasksByNameAndDuration(events) { - const {pid} = TracingProcessor.findMainFrameIds(events); + const {pid} = TraceProcessor.findMainFrameIds(events); return events.filter(evt => { if (toplevelTaskNames.has(evt.name) && evt.dur < 1000) return false; @@ -170,4 +170,4 @@ function minifyTrace(inputTrace) { return {traceEvents: filterTraceEvents(inputTrace.traceEvents)}; } -module.exports = {minifyTrace}; +export {minifyTrace}; diff --git a/lighthouse-core/lib/navigation-error.js b/lighthouse-core/lib/navigation-error.js index 70397f7777b8..c7217007c6bb 100644 --- a/lighthouse-core/lib/navigation-error.js +++ b/lighthouse-core/lib/navigation-error.js @@ -5,10 +5,10 @@ */ 'use strict'; -const LighthouseError = require('./lh-error.js'); -const NetworkAnalyzer = require('./dependency-graph/simulator/network-analyzer.js'); -const NetworkRequest = require('./network-request.js'); -const i18n = require('./i18n/i18n.js'); +import {LighthouseError} from './lh-error.js'; +import {NetworkAnalyzer} from './dependency-graph/simulator/network-analyzer.js'; +import {NetworkRequest} from './network-request.js'; +import * as i18n from '../lib/i18n/i18n.js'; const UIStrings = { /** @@ -19,7 +19,7 @@ const UIStrings = { 'The page MIME type is XHTML: Lighthouse does not explicitly support this document type', }; -const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); +const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); // MIME types are case-insensitive but Chrome normalizes MIME types to be lowercase. const HTML_MIME_TYPE = 'text/html'; @@ -165,7 +165,7 @@ function getPageLoadError(navigationError, context) { return navigationError; } -module.exports = { +export { getNetworkError, getInterstitialError, getPageLoadError, diff --git a/lighthouse-core/lib/network-recorder.js b/lighthouse-core/lib/network-recorder.js index d3a9cfb4c47f..c5502839b78f 100644 --- a/lighthouse-core/lib/network-recorder.js +++ b/lighthouse-core/lib/network-recorder.js @@ -5,9 +5,9 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const NetworkRequest = require('./network-request.js'); -const EventEmitter = require('events').EventEmitter; +import log from 'lighthouse-logger'; +import {NetworkRequest} from './network-request.js'; +import {EventEmitter} from 'events'; /** * @typedef {{ @@ -325,4 +325,4 @@ class NetworkRecorder extends RequestEventEmitter { } } -module.exports = NetworkRecorder; +export {NetworkRecorder}; diff --git a/lighthouse-core/lib/network-request.js b/lighthouse-core/lib/network-request.js index 223592de15a0..6dd6cc9d255a 100644 --- a/lighthouse-core/lib/network-request.js +++ b/lighthouse-core/lib/network-request.js @@ -11,8 +11,7 @@ * @see https://cs.chromium.org/chromium/src/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js */ -const URL = require('./url-shim.js'); - +import URL from './url-shim.js'; // Lightrider X-Header names for timing information. // See: _updateTransferSizeForLightrider and _updateTimingsForLightrider. @@ -537,4 +536,4 @@ NetworkRequest.HEADER_TOTAL = HEADER_TOTAL; NetworkRequest.HEADER_FETCHED_SIZE = HEADER_FETCHED_SIZE; NetworkRequest.HEADER_PROTOCOL_IS_H2 = HEADER_PROTOCOL_IS_H2; -module.exports = NetworkRequest; +export {NetworkRequest}; diff --git a/lighthouse-core/lib/page-functions.js b/lighthouse-core/lib/page-functions.js index 7b81f688abb5..9fcb877ee016 100644 --- a/lighthouse-core/lib/page-functions.js +++ b/lighthouse-core/lib/page-functions.js @@ -537,7 +537,8 @@ const getNodeDetailsString = `function getNodeDetails(element) { return (${getNodeDetails.toString()})(element); }`; -module.exports = { +// TODO(esmodules): should this be refactored to export each function individually? +export const pageFunctions = { wrapRuntimeEvalErrorInBrowserString: wrapRuntimeEvalErrorInBrowser.toString(), wrapRuntimeEvalErrorInBrowser, getElementsInDocument, diff --git a/lighthouse-core/lib/proto-preprocessor.js b/lighthouse-core/lib/proto-preprocessor.js index bb465c2dd1bb..4f44f68a7921 100644 --- a/lighthouse-core/lib/proto-preprocessor.js +++ b/lighthouse-core/lib/proto-preprocessor.js @@ -6,7 +6,8 @@ 'use strict'; -const fs = require('fs'); +import fs from 'fs'; +import esMain from 'es-main'; /** * @fileoverview Helper functions to transform an LHR into a proto-ready LHR. @@ -108,7 +109,7 @@ function processForProto(lhr) { } // Test if called from the CLI or as a module. -if (require.main === module) { +if (esMain(import.meta)) { // read in the argv for the input & output const args = process.argv.slice(2); let input; @@ -126,8 +127,8 @@ if (require.main === module) { // write to output from argv fs.writeFileSync(output, JSON.stringify(report), 'utf-8'); } -} else { - module.exports = { - processForProto, - }; } + +export { + processForProto, +}; diff --git a/lighthouse-core/lib/rect-helpers.js b/lighthouse-core/lib/rect-helpers.js index cffcb7919a6e..f82ad31a6c8b 100644 --- a/lighthouse-core/lib/rect-helpers.js +++ b/lighthouse-core/lib/rect-helpers.js @@ -233,7 +233,7 @@ function allRectsContainedWithinEachOther(rectListA, rectListB) { return true; } -module.exports = { +export { rectContainsPoint, rectContains, addRectWidthAndHeight, diff --git a/lighthouse-core/lib/script-helpers.js b/lighthouse-core/lib/script-helpers.js index 506ed60a2821..e6be1acc2f55 100644 --- a/lighthouse-core/lib/script-helpers.js +++ b/lighthouse-core/lib/script-helpers.js @@ -26,4 +26,7 @@ function getRequestForScript(networkRecords, script) { return networkRequest; } -module.exports = {getRequestForScript, isInline}; +export { + getRequestForScript, + isInline, +}; diff --git a/lighthouse-core/lib/sd-validation/helpers/walk-object.js b/lighthouse-core/lib/sd-validation/helpers/walk-object.js index 6eab98a7836a..dc1eac195fb6 100644 --- a/lighthouse-core/lib/sd-validation/helpers/walk-object.js +++ b/lighthouse-core/lib/sd-validation/helpers/walk-object.js @@ -12,7 +12,7 @@ * @param {function(string, any, Array<string>, any): void} callback * @param {Array<string>} path */ -module.exports = function walkObject(obj, callback, path = []) { +export default function walkObject(obj, callback, path = []) { if (obj === null) { return; } @@ -27,4 +27,4 @@ module.exports = function walkObject(obj, callback, path = []) { walkObject(fieldValue, callback, newPath); } }); -}; +} diff --git a/lighthouse-core/lib/sd-validation/json-expander.js b/lighthouse-core/lib/sd-validation/json-expander.js index 35e60512d221..96f9011b65e3 100644 --- a/lighthouse-core/lib/sd-validation/json-expander.js +++ b/lighthouse-core/lib/sd-validation/json-expander.js @@ -5,11 +5,17 @@ */ 'use strict'; -const {URL} = require('../url-shim.js'); -const jsonld = require('jsonld'); -const schemaOrgContext = require('./assets/jsonldcontext.json'); +import fs from 'fs'; +import URL from '../url-shim.js'; +import jsonld from 'jsonld'; +import {LH_ROOT} from '../../../root.js'; + const SCHEMA_ORG_HOST = 'schema.org'; +/** @type {import('./assets/jsonldcontext.json')} */ +const schemaOrgContext = JSON.parse(fs.readFileSync( + LH_ROOT + '/lighthouse-core/lib/sd-validation/assets/jsonldcontext.json', 'utf-8')); + /** * Custom loader that prevents network calls and allows us to return local version of the * schema.org document @@ -45,7 +51,7 @@ async function documentLoader(schemaUrl) { * @param {any} inputObject * @return {Promise<LH.StructuredData.ExpandedSchemaRepresentation|null>} */ -module.exports = async function expand(inputObject) { +export default async function expand(inputObject) { try { return await jsonld.expand(inputObject, {documentLoader}); } catch (err) { @@ -53,4 +59,4 @@ module.exports = async function expand(inputObject) { if (err.details?.cause) throw err.details.cause; throw err; } -}; +} diff --git a/lighthouse-core/lib/sd-validation/json-linter.js b/lighthouse-core/lib/sd-validation/json-linter.js index ecba0b940bd0..243b1af772d8 100644 --- a/lighthouse-core/lib/sd-validation/json-linter.js +++ b/lighthouse-core/lib/sd-validation/json-linter.js @@ -5,13 +5,13 @@ */ 'use strict'; -const jsonlint = require('jsonlint-mod'); +import jsonlint from 'jsonlint-mod'; /** * @param {string} input * @return {{message: string, lineNumber: number|null}|null} */ -module.exports = function parseJSON(input) { +export default function parseJSON(input) { try { jsonlint.parse(input); } catch (error) { @@ -46,4 +46,4 @@ module.exports = function parseJSON(input) { } return null; -}; +} diff --git a/lighthouse-core/lib/sd-validation/jsonld-keyword-validator.js b/lighthouse-core/lib/sd-validation/jsonld-keyword-validator.js index 739d76aeab32..2b6feb5e62b4 100644 --- a/lighthouse-core/lib/sd-validation/jsonld-keyword-validator.js +++ b/lighthouse-core/lib/sd-validation/jsonld-keyword-validator.js @@ -5,7 +5,7 @@ */ 'use strict'; -const walkObject = require('./helpers/walk-object.js'); +import walkObject from './helpers/walk-object.js'; // This list comes from the JSON-LD 1.1 editors draft: // https://w3c.github.io/json-ld-syntax/#syntax-tokens-and-keywords @@ -33,7 +33,7 @@ const VALID_KEYWORDS = new Set([ * @param {*} json * @return {Array<{path: string, message: string}>} */ -module.exports = function validateJsonLD(json) { +export default function validateJsonLD(json) { /** @type {Array<{path: string, message: string}>} */ const errors = []; @@ -47,4 +47,4 @@ module.exports = function validateJsonLD(json) { }); return errors; -}; +} diff --git a/lighthouse-core/lib/sd-validation/line-number-from-jsonld-path.js b/lighthouse-core/lib/sd-validation/line-number-from-jsonld-path.js index dcf67bab2a23..0001bbfae9cb 100644 --- a/lighthouse-core/lib/sd-validation/line-number-from-jsonld-path.js +++ b/lighthouse-core/lib/sd-validation/line-number-from-jsonld-path.js @@ -57,4 +57,4 @@ function setValueAtJsonLDPath(obj, path, value) { }); } -module.exports = getLineNumberFromJsonLDPath; +export default getLineNumberFromJsonLDPath; diff --git a/lighthouse-core/lib/sd-validation/schema-validator.js b/lighthouse-core/lib/sd-validation/schema-validator.js index 2d93774b0213..f213d7fbd63d 100644 --- a/lighthouse-core/lib/sd-validation/schema-validator.js +++ b/lighthouse-core/lib/sd-validation/schema-validator.js @@ -5,8 +5,14 @@ */ 'use strict'; -const walkObject = require('./helpers/walk-object.js'); -const schemaStructure = require('./assets/schema-tree.json'); +import fs from 'fs'; +import walkObject from './helpers/walk-object.js'; +import {LH_ROOT} from '../../../root.js'; + +/** @type {import('./assets/schema-tree.json')} */ +const schemaStructure = JSON.parse(fs.readFileSync( + LH_ROOT + '/lighthouse-core/lib/sd-validation/assets/schema-tree.json', 'utf-8')); + const TYPE_KEYWORD = '@type'; const SCHEMA_ORG_URL_REGEX = /https?:\/\/schema\.org\//; @@ -107,7 +113,7 @@ function validateObjectKeys(typeOrTypes, keys) { * @param {LH.StructuredData.ExpandedSchemaRepresentation|null} expandedObj Valid JSON-LD object in expanded form * @return {Array<Pick<LH.StructuredData.ValidationError, "message" | "validTypes" | "path">>} */ -module.exports = function validateSchemaOrg(expandedObj) { +export default function validateSchemaOrg(expandedObj) { /** @type {Array<Pick<LH.StructuredData.ValidationError, "message" | "validTypes" | "path">>} */ const errors = []; @@ -143,4 +149,4 @@ module.exports = function validateSchemaOrg(expandedObj) { }); return errors; -}; +} diff --git a/lighthouse-core/lib/sd-validation/scripts/download-jsonldcontext.js b/lighthouse-core/lib/sd-validation/scripts/download-jsonldcontext.js index 4c5e0f944151..6d2b21cadb67 100644 --- a/lighthouse-core/lib/sd-validation/scripts/download-jsonldcontext.js +++ b/lighthouse-core/lib/sd-validation/scripts/download-jsonldcontext.js @@ -9,9 +9,10 @@ * Call this script to update assets/jsonldcontext.json with the latest schema.org spec */ -const fetch = require('node-fetch'); -const path = require('path'); -const fs = require('fs'); +import fetch from 'node-fetch'; + +import path from 'path'; +import fs from 'fs'; const SCHEMA_ORG_URL = 'https://schema.org'; const CONTEXT_FILE = path.join(__dirname, '../assets/jsonldcontext.json'); diff --git a/lighthouse-core/lib/sd-validation/scripts/generate-schema-tree.js b/lighthouse-core/lib/sd-validation/scripts/generate-schema-tree.js index 46a6e548f290..5352095976b2 100644 --- a/lighthouse-core/lib/sd-validation/scripts/generate-schema-tree.js +++ b/lighthouse-core/lib/sd-validation/scripts/generate-schema-tree.js @@ -9,9 +9,10 @@ * Call this script to update assets/schema-tree.json with the latest schema.org spec */ -const fetch = require('node-fetch'); -const path = require('path'); -const fs = require('fs'); +import fetch from 'node-fetch'; + +import path from 'path'; +import fs from 'fs'; const SCHEMA_ORG_URL = 'https://schema.org/version/latest/schema.jsonld'; const SCHEMA_TREE_FILE = path.join(__dirname, '../assets/schema-tree.json'); diff --git a/lighthouse-core/lib/sd-validation/sd-validation.js b/lighthouse-core/lib/sd-validation/sd-validation.js index 4f20145793c1..8423e14802e0 100644 --- a/lighthouse-core/lib/sd-validation/sd-validation.js +++ b/lighthouse-core/lib/sd-validation/sd-validation.js @@ -5,11 +5,11 @@ */ 'use strict'; -const parseJSON = require('./json-linter.js'); -const validateJsonLD = require('./jsonld-keyword-validator.js'); -const expandAsync = require('./json-expander.js'); -const validateSchemaOrg = require('./schema-validator.js'); -const getLineNumberFromJsonLDPath = require('./line-number-from-jsonld-path.js'); +import parseJSON from './json-linter.js'; +import validateJsonLD from './jsonld-keyword-validator.js'; +import expandAsync from './json-expander.js'; +import validateSchemaOrg from './schema-validator.js'; +import getLineNumberFromJsonLDPath from './line-number-from-jsonld-path.js'; /** * Validates JSON-LD input. Returns array of error objects. @@ -17,7 +17,7 @@ const getLineNumberFromJsonLDPath = require('./line-number-from-jsonld-path.js') * @param {string} textInput * @return {Promise<Array<LH.StructuredData.ValidationError>>} */ -module.exports = async function validate(textInput) { +export default async function validate(textInput) { // STEP 1: VALIDATE JSON const parseError = parseJSON(textInput); @@ -73,5 +73,5 @@ module.exports = async function validate(textInput) { } return []; -}; +} diff --git a/lighthouse-core/lib/sentry.js b/lighthouse-core/lib/sentry.js index 46b896cc8ea0..45b69d58c544 100644 --- a/lighthouse-core/lib/sentry.js +++ b/lighthouse-core/lib/sentry.js @@ -5,7 +5,7 @@ */ 'use strict'; -const log = require('lighthouse-logger'); +import log from 'lighthouse-logger'; /** @typedef {import('@sentry/node').Breadcrumb} Breadcrumb */ /** @typedef {import('@sentry/node').NodeClient} NodeClient */ @@ -48,7 +48,7 @@ const sentryDelegate = { * When called, replaces noops with actual Sentry implementation. * @param {{url: string, flags: LH.CliFlags, environmentData: NodeOptions}} opts */ -function init(opts) { +async function init(opts) { // If error reporting is disabled, leave the functions as a noop if (!opts.flags.enableErrorReporting) { return; @@ -60,7 +60,7 @@ function init(opts) { } try { - const Sentry = require('@sentry/node'); + const Sentry = await import('@sentry/node'); Sentry.init({ ...opts.environmentData, dsn: SENTRY_URL, @@ -141,4 +141,4 @@ function init(opts) { } } -module.exports = sentryDelegate; +export const Sentry = sentryDelegate; diff --git a/lighthouse-core/lib/stack-packs.js b/lighthouse-core/lib/stack-packs.js index 36fb3994248f..f252ea7f8e24 100644 --- a/lighthouse-core/lib/stack-packs.js +++ b/lighthouse-core/lib/stack-packs.js @@ -5,9 +5,9 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const stackPacks = require('lighthouse-stack-packs'); -const i18n = require('./i18n/i18n.js'); +import log from 'lighthouse-logger'; +import stackPacks from 'lighthouse-stack-packs'; +import * as i18n from './i18n/i18n.js'; /** * Pairs consisting of a stack pack's ID and the set of stacks needed to be @@ -114,7 +114,7 @@ function getStackPacks(pageStacks) { return packs; } -module.exports = { +export { getStackPacks, stackPacksToInclude, }; diff --git a/lighthouse-core/lib/statistics.js b/lighthouse-core/lib/statistics.js index d7b64675aa8c..6aa148092f2f 100644 --- a/lighthouse-core/lib/statistics.js +++ b/lighthouse-core/lib/statistics.js @@ -98,7 +98,7 @@ function linearInterpolation(x0, y0, x1, y1, x) { return y0 + (x - x0) * slope; } -module.exports = { +export { linearInterpolation, getLogNormalScore, }; diff --git a/lighthouse-core/lib/tappable-rects.js b/lighthouse-core/lib/tappable-rects.js index 73566ec3c830..581c0b89fad9 100644 --- a/lighthouse-core/lib/tappable-rects.js +++ b/lighthouse-core/lib/tappable-rects.js @@ -5,7 +5,7 @@ */ 'use strict'; -const RectHelpers = require('./rect-helpers.js'); +import * as RectHelpers from './rect-helpers.js'; /** * Merge client rects together and remove small ones. This may result in a larger overall @@ -94,6 +94,6 @@ function mergeTouchingClientRects(clientRects) { return clientRects; } -module.exports = { +export { getTappableRectsFromClientRects, }; diff --git a/lighthouse-core/lib/third-party-web.js b/lighthouse-core/lib/third-party-web.js index e2336cf90233..12423d60c121 100644 --- a/lighthouse-core/lib/third-party-web.js +++ b/lighthouse-core/lib/third-party-web.js @@ -5,7 +5,7 @@ */ 'use strict'; -const thirdPartyWeb = require('third-party-web/httparchive-nostats-subset'); +import thirdPartyWeb from 'third-party-web/httparchive-nostats-subset.js'; /** @typedef {import("third-party-web").IEntity} ThirdPartyEntity */ /** @typedef {import("third-party-web").IProduct} ThirdPartyProduct */ @@ -45,7 +45,7 @@ function isFirstParty(url, mainDocumentEntity) { return !isThirdParty(url, mainDocumentEntity); } -module.exports = { +export default { getEntity, getProduct, isThirdParty, diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js index 3a40fae526b6..8c7ac32656f6 100644 --- a/lighthouse-core/lib/timing-trace-saver.js +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -94,4 +94,4 @@ ${events.map(evt => JSON.stringify(evt)).join(',\n')} return jsonStr; } -module.exports = {generateTraceEvents, createTraceString}; +export {generateTraceEvents, createTraceString}; diff --git a/lighthouse-core/lib/tracehouse/cpu-profile-model.js b/lighthouse-core/lib/tracehouse/cpu-profile-model.js index 1f9639e9d363..b860179e3ac5 100644 --- a/lighthouse-core/lib/tracehouse/cpu-profile-model.js +++ b/lighthouse-core/lib/tracehouse/cpu-profile-model.js @@ -5,7 +5,7 @@ */ 'use strict'; -const MainThreadTasks = require('./main-thread-tasks.js'); +import {MainThreadTasks} from './main-thread-tasks.js'; const SAMPLER_TRACE_EVENT_NAME = 'FunctionCall-SynthesizedByProfilerModel'; @@ -48,7 +48,7 @@ const SAMPLER_TRACE_EVENT_NAME = 'FunctionCall-SynthesizedByProfilerModel'; /** @typedef {LH.TraceEvent & {args: {data: {_syntheticProfilerRange: ProfilerRange}}}} SynthethicEvent */ /** @typedef {Omit<LH.Artifacts.TaskNode, 'event'> & {event: SynthethicEvent, endEvent: SynthethicEvent}} SynthethicTaskNode */ -class CpuProfilerModel { +class CpuProfileModel { /** * @param {CpuProfile} profile */ @@ -193,8 +193,8 @@ class CpuProfilerModel { * @return {task is SynthethicTaskNode} */ static isSyntheticTask(task) { - return CpuProfilerModel.isSyntheticEvent(task.event) && - CpuProfilerModel.isSyntheticEvent(task.endEvent); + return CpuProfileModel.isSyntheticEvent(task.event) && + CpuProfileModel.isSyntheticEvent(task.endEvent); } /** @@ -474,7 +474,7 @@ class CpuProfilerModel { const allEventsAtTs = syntheticEventsByTs.get(event.ts); if (!allEventsAtTs) throw new Error('Impossible - we just mapped every event'); - const effectiveTimestampData = CpuProfilerModel._findEffectiveTimestamp({ + const effectiveTimestampData = CpuProfileModel._findEffectiveTimestamp({ eventType: event.ph === 'B' ? 'start' : 'end', syntheticTask, allEventsAtTs, @@ -524,7 +524,7 @@ class CpuProfilerModel { // We'll also create tasks for our naive events so we have the B/E pairs readily available. const naiveProfilerTasks = MainThreadTasks.getMainThreadTasks(naiveEvents, [], Infinity) .map(rebaseTaskTime(naiveEvents[0].ts)) - .filter(CpuProfilerModel.isSyntheticTask); + .filter(CpuProfileModel.isSyntheticTask); if (!naiveProfilerTasks.length) throw new Error('Failed to create naive profiler tasks'); finalEvents = this._refineTraceEventsWithTasks(knownTasks, naiveProfilerTasks, naiveEvents); @@ -541,7 +541,7 @@ class CpuProfilerModel { * @return {Array<LH.TraceEvent>} */ static synthesizeTraceEvents(profile, tasks) { - const model = new CpuProfilerModel(profile); + const model = new CpuProfileModel(profile); return model.synthesizeTraceEvents(tasks); } @@ -589,4 +589,4 @@ class CpuProfilerModel { } } -module.exports = CpuProfilerModel; +export {CpuProfileModel}; diff --git a/lighthouse-core/lib/tracehouse/main-thread-tasks.js b/lighthouse-core/lib/tracehouse/main-thread-tasks.js index c63619f0ad96..de406fef4152 100644 --- a/lighthouse-core/lib/tracehouse/main-thread-tasks.js +++ b/lighthouse-core/lib/tracehouse/main-thread-tasks.js @@ -5,7 +5,7 @@ */ 'use strict'; -const {taskGroups, taskNameToGroup} = require('./task-groups.js'); +import {taskGroups, taskNameToGroup} from './task-groups.js'; /** * @fileoverview @@ -684,4 +684,4 @@ class MainThreadTasks { } } -module.exports = MainThreadTasks; +export {MainThreadTasks}; diff --git a/lighthouse-core/lib/tracehouse/task-groups.js b/lighthouse-core/lib/tracehouse/task-groups.js index 72bc92176066..0ef5d3daba74 100644 --- a/lighthouse-core/lib/tracehouse/task-groups.js +++ b/lighthouse-core/lib/tracehouse/task-groups.js @@ -106,7 +106,7 @@ for (const group of Object.values(taskGroups)) { } } -module.exports = { +export { taskGroups, taskNameToGroup, }; diff --git a/lighthouse-core/lib/tracehouse/task-summary.js b/lighthouse-core/lib/tracehouse/task-summary.js index d457606eb549..9be0cf7e721d 100644 --- a/lighthouse-core/lib/tracehouse/task-summary.js +++ b/lighthouse-core/lib/tracehouse/task-summary.js @@ -9,7 +9,7 @@ * @fileoverview Utility functions for grouping and summarizing tasks. */ -const NetworkRequest = require('../network-request.js'); +import {NetworkRequest} from '../network-request.js'; // These trace events, when not triggered by a script inside a particular task, are just general Chrome overhead. const BROWSER_TASK_NAMES_SET = new Set([ @@ -80,7 +80,7 @@ function getExecutionTimingsByURL(tasks, networkRecords) { return result; } -module.exports = { +export { getJavaScriptURLs, getAttributableURLForTask, getExecutionTimingsByURL, diff --git a/lighthouse-core/lib/tracehouse/trace-processor.js b/lighthouse-core/lib/tracehouse/trace-processor.js index 434bab1f16aa..a300309565d2 100644 --- a/lighthouse-core/lib/tracehouse/trace-processor.js +++ b/lighthouse-core/lib/tracehouse/trace-processor.js @@ -22,7 +22,7 @@ /** @typedef {Omit<LH.TraceEvent, 'name'|'args'> & {name: 'largestContentfulPaint::Invalidate'|'largestContentfulPaint::Candidate', args: {data?: {size?: number}, frame: string}}} LCPEvent */ /** @typedef {Omit<LH.TraceEvent, 'name'|'args'> & {name: 'largestContentfulPaint::Candidate', args: {data: {size: number}, frame: string}}} LCPCandidateEvent */ -const log = require('lighthouse-logger'); +import log from 'lighthouse-logger'; const ACCEPTABLE_NAVIGATION_URL_REGEX = /^(chrome|https?):/; @@ -951,8 +951,7 @@ class TraceProcessor { } } -module.exports = TraceProcessor; - +export {TraceProcessor}; /** * @typedef ToplevelEvent diff --git a/lighthouse-core/lib/traces/pwmetrics-events.js b/lighthouse-core/lib/traces/pwmetrics-events.js index f1ccb7543c1a..3e552e2acc2c 100644 --- a/lighthouse-core/lib/traces/pwmetrics-events.js +++ b/lighthouse-core/lib/traces/pwmetrics-events.js @@ -5,8 +5,8 @@ */ 'use strict'; -const log = require('lighthouse-logger'); -const TraceProcessor = require('../tracehouse/trace-processor.js'); +import log from 'lighthouse-logger'; +import {TraceProcessor} from '../tracehouse/trace-processor.js'; /** * @param {LH.Result['audits']} auditResults @@ -197,4 +197,5 @@ class Metrics { } } -module.exports = Metrics; +// TODO(esmodule): rename? +export {Metrics}; diff --git a/lighthouse-core/lib/url-shim.js b/lighthouse-core/lib/url-shim.js index 60a6cfe14993..38edb18b6907 100644 --- a/lighthouse-core/lib/url-shim.js +++ b/lighthouse-core/lib/url-shim.js @@ -9,10 +9,11 @@ * URL shim so we keep our code DRY */ -const {Util} = require('../util-commonjs.js'); -const LighthouseError = require('../lib/lh-error.js'); +import {Util} from '../util.cjs'; -/** @typedef {import('./network-request.js')} NetworkRequest */ +import {LighthouseError} from '../lib/lh-error.js'; + +/** @typedef {import('./network-request.js').NetworkRequest} NetworkRequest */ const allowedProtocols = [ 'https:', 'http:', 'chrome:', 'chrome-extension:', @@ -271,4 +272,5 @@ URLShim.INVALID_URL_DEBUG_STRING = 'Lighthouse was unable to determine the URL of some script executions. ' + 'It\'s possible a Chrome extension or other eval\'d code is the source.'; -module.exports = URLShim; +// TODO(esmodules): don't use default export +export default URLShim; diff --git a/lighthouse-core/package.json b/lighthouse-core/package.json new file mode 100644 index 000000000000..bd346284783c --- /dev/null +++ b/lighthouse-core/package.json @@ -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" +} \ No newline at end of file diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index bf5ff808b0ae..659e3f19b67e 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -5,24 +5,27 @@ */ 'use strict'; -const isDeepEqual = require('lodash/isEqual.js'); -const Driver = require('./gather/driver.js'); -const GatherRunner = require('./gather/gather-runner.js'); -const ReportScoring = require('./scoring.js'); -const Audit = require('./audits/audit.js'); -const log = require('lighthouse-logger'); -const format = require('../shared/localization/format.js'); -const stackPacks = require('./lib/stack-packs.js'); -const assetSaver = require('./lib/asset-saver.js'); -const fs = require('fs'); -const path = require('path'); -const Sentry = require('./lib/sentry.js'); -const generateReport = require('../report/generator/report-generator.js').generateReport; -const LighthouseError = require('./lib/lh-error.js'); -const {version: lighthouseVersion} = require('../package.json'); - -/** @typedef {import('./gather/connections/connection.js')} Connection */ -/** @typedef {import('./lib/arbitrary-equality-map.js')} ArbitraryEqualityMap */ +import isDeepEqual from 'lodash/isEqual.js'; +import {Driver} from './gather/driver.js'; +import {GatherRunner} from './gather/gather-runner.js'; +import {ReportScoring} from './scoring.js'; +import {Audit} from './audits/audit.js'; +import log from 'lighthouse-logger'; +import format from '../shared/localization/format.js'; +import * as stackPacks from './lib/stack-packs.js'; +import * as assetSaver from './lib/asset-saver.js'; +import fs from 'fs'; +import path from 'path'; +import {Sentry} from './lib/sentry.js'; +import ReportGenerator from '../report/generator/report-generator.js'; +import {LighthouseError} from './lib/lh-error.js'; +import {lighthouseVersion} from '../root.js'; +import {getModuleDirectory} from '../esm-utils.js'; + +const moduleDir = getModuleDirectory(import.meta); + +/** @typedef {import('./gather/connections/connection.js').Connection} Connection */ +/** @typedef {import('./lib/arbitrary-equality-map.js').ArbitraryEqualityMap} ArbitraryEqualityMap */ /** @typedef {LH.Config.Config} Config */ class Runner { @@ -123,7 +126,7 @@ class Runner { } // Create the HTML, JSON, and/or CSV string - const report = generateReport(lhr, settings.output); + const report = ReportGenerator.generateReport(lhr, settings.output); return {lhr, artifacts, report}; } catch (err) { @@ -364,7 +367,7 @@ class Runner { // If artifact was an error, output error result on behalf of audit. if (artifacts[artifactName] instanceof Error) { /** @type {Error} */ - // @ts-expect-error An artifact *could* be an Error, but caught here, so ignore elsewhere. + // @ts-expect-error: TODO why is this a type error now? const artifactError = artifacts[artifactName]; Sentry.captureException(artifactError, { @@ -436,8 +439,10 @@ class Runner { ]; for (const possibleErrorArtifact of possibleErrorArtifacts) { + const isError = possibleErrorArtifact instanceof LighthouseError; + // eslint-disable-next-line max-len - if (possibleErrorArtifact instanceof LighthouseError && possibleErrorArtifact.lhrRuntimeError) { + if (isError && possibleErrorArtifact.lhrRuntimeError) { const errorMessage = possibleErrorArtifact.friendlyMessage || possibleErrorArtifact.message; return { @@ -465,18 +470,18 @@ class Runner { ]; const fileList = [ - ...fs.readdirSync(path.join(__dirname, './audits')), - ...fs.readdirSync(path.join(__dirname, './audits/dobetterweb')).map(f => `dobetterweb/${f}`), - ...fs.readdirSync(path.join(__dirname, './audits/metrics')).map(f => `metrics/${f}`), - ...fs.readdirSync(path.join(__dirname, './audits/seo')).map(f => `seo/${f}`), - ...fs.readdirSync(path.join(__dirname, './audits/seo/manual')).map(f => `seo/manual/${f}`), - ...fs.readdirSync(path.join(__dirname, './audits/accessibility')) + ...fs.readdirSync(path.join(moduleDir, './audits')), + ...fs.readdirSync(path.join(moduleDir, './audits/dobetterweb')).map(f => `dobetterweb/${f}`), + ...fs.readdirSync(path.join(moduleDir, './audits/metrics')).map(f => `metrics/${f}`), + ...fs.readdirSync(path.join(moduleDir, './audits/seo')).map(f => `seo/${f}`), + ...fs.readdirSync(path.join(moduleDir, './audits/seo/manual')).map(f => `seo/manual/${f}`), + ...fs.readdirSync(path.join(moduleDir, './audits/accessibility')) .map(f => `accessibility/${f}`), - ...fs.readdirSync(path.join(__dirname, './audits/accessibility/manual')) + ...fs.readdirSync(path.join(moduleDir, './audits/accessibility/manual')) .map(f => `accessibility/manual/${f}`), - ...fs.readdirSync(path.join(__dirname, './audits/byte-efficiency')) + ...fs.readdirSync(path.join(moduleDir, './audits/byte-efficiency')) .map(f => `byte-efficiency/${f}`), - ...fs.readdirSync(path.join(__dirname, './audits/manual')).map(f => `manual/${f}`), + ...fs.readdirSync(path.join(moduleDir, './audits/manual')).map(f => `manual/${f}`), ]; return fileList.filter(f => { return /\.js$/.test(f) && !ignoredFiles.includes(f); @@ -489,9 +494,9 @@ class Runner { */ static getGathererList() { const fileList = [ - ...fs.readdirSync(path.join(__dirname, './gather/gatherers')), - ...fs.readdirSync(path.join(__dirname, './gather/gatherers/seo')).map(f => `seo/${f}`), - ...fs.readdirSync(path.join(__dirname, './gather/gatherers/dobetterweb')) + ...fs.readdirSync(path.join(moduleDir, './gather/gatherers')), + ...fs.readdirSync(path.join(moduleDir, './gather/gatherers/seo')).map(f => `seo/${f}`), + ...fs.readdirSync(path.join(moduleDir, './gather/gatherers/dobetterweb')) .map(f => `dobetterweb/${f}`), ]; return fileList.filter(f => /\.js$/.test(f) && f !== 'gatherer.js').sort(); @@ -513,4 +518,5 @@ class Runner { } } -module.exports = Runner; +// TODO(esmodules): make this not a class. +export {Runner}; diff --git a/lighthouse-core/scoring.js b/lighthouse-core/scoring.js index c410e69aed44..a66abcb6979f 100644 --- a/lighthouse-core/scoring.js +++ b/lighthouse-core/scoring.js @@ -6,7 +6,7 @@ 'use strict'; -const Audit = require('./audits/audit.js'); +import {Audit} from './audits/audit.js'; /** * Clamp figure to 2 decimal places @@ -90,4 +90,4 @@ class ReportScoring { } } -module.exports = ReportScoring; +export {ReportScoring}; diff --git a/lighthouse-core/scripts/benchmark-plus-extras.js b/lighthouse-core/scripts/benchmark-plus-extras.js index b9a5eecb340d..d0c97d191401 100644 --- a/lighthouse-core/scripts/benchmark-plus-extras.js +++ b/lighthouse-core/scripts/benchmark-plus-extras.js @@ -14,7 +14,7 @@ import puppeteer from 'puppeteer-core'; import {getChromePath} from 'chrome-launcher'; -import pageFunctions from '../lib/page-functions.js'; +import {pageFunctions} from '../lib/page-functions.js'; /** @param {LH.Puppeteer.Page} page */ async function runOctane(page) { diff --git a/lighthouse-core/scripts/benchmark.js b/lighthouse-core/scripts/benchmark.js index 701923e08217..38dc8b11ded9 100755 --- a/lighthouse-core/scripts/benchmark.js +++ b/lighthouse-core/scripts/benchmark.js @@ -10,7 +10,7 @@ // node lighthouse-core/scripts/benchmark.js -import pageFunctions from '../lib/page-functions.js'; +import {pageFunctions} from '../lib/page-functions.js'; console.log('Computing BenchmarkIndex 10 times...'); diff --git a/lighthouse-core/scripts/cleanup-vuln-snapshot.js b/lighthouse-core/scripts/cleanup-vuln-snapshot.js index 0edcef4b7e72..9100ac9c6153 100755 --- a/lighthouse-core/scripts/cleanup-vuln-snapshot.js +++ b/lighthouse-core/scripts/cleanup-vuln-snapshot.js @@ -12,7 +12,7 @@ import {readFileSync, writeFileSync} from 'fs'; import prettyJSONStringify from 'pretty-json-stringify'; -import {resolveModulePath} from '../../esm-utils.mjs'; +import {resolveModulePath} from '../../esm-utils.js'; const libDetectorSource = readFileSync( resolveModulePath('js-library-detector/library/libraries.js'), diff --git a/lighthouse-core/scripts/copy-util-commonjs.sh b/lighthouse-core/scripts/copy-util-commonjs.sh index c57b9e06d23a..5ee4f5d720c6 100644 --- a/lighthouse-core/scripts/copy-util-commonjs.sh +++ b/lighthouse-core/scripts/copy-util-commonjs.sh @@ -11,7 +11,7 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" LH_ROOT_DIR="$SCRIPT_DIR/../.." -OUT_FILE="$LH_ROOT_DIR"/lighthouse-core/util-commonjs.js +OUT_FILE="$LH_ROOT_DIR"/lighthouse-core/util.cjs echo '// @ts-nocheck' > "$OUT_FILE" echo '// Auto-generated by lighthouse-core/scripts/copy-util-commonjs.sh' >> "$OUT_FILE" diff --git a/lighthouse-core/scripts/i18n/collect-strings.js b/lighthouse-core/scripts/i18n/collect-strings.js index ee05c338b4bf..144c66ba2281 100644 --- a/lighthouse-core/scripts/i18n/collect-strings.js +++ b/lighthouse-core/scripts/i18n/collect-strings.js @@ -17,12 +17,12 @@ import tsc from 'typescript'; import MessageParser from 'intl-messageformat-parser'; import esMain from 'es-main'; -import {Util} from '../../../lighthouse-core/util-commonjs.js'; +import {Util} from '../../util.cjs'; import {collectAndBakeCtcStrings} from './bake-ctc-to-lhl.js'; import {pruneObsoleteLhlMessages} from './prune-obsolete-lhl-messages.js'; import {countTranslatedMessages} from './count-translated.js'; import {LH_ROOT} from '../../../root.js'; -import {resolveModulePath} from '../../../esm-utils.mjs'; +import {resolveModulePath} from '../../../esm-utils.js'; // Match declarations of UIStrings, terminating in either a `};\n` (very likely to always be right) // or `}\n\n` (allowing semicolon to be optional, but insisting on a double newline so that an diff --git a/lighthouse-core/scripts/lantern/constants.js b/lighthouse-core/scripts/lantern/constants.js index 40eb20e20da6..7af5a5ac17b8 100644 --- a/lighthouse-core/scripts/lantern/constants.js +++ b/lighthouse-core/scripts/lantern/constants.js @@ -72,6 +72,7 @@ import {LH_ROOT} from '../../../root.js'; /** @type {Array<string>} */ const WARNINGS = []; +// TODO(esmodules): make non-default export default { WARNINGS, // prettier-ignore diff --git a/lighthouse-core/scripts/lantern/run-once.js b/lighthouse-core/scripts/lantern/run-once.js index 678d0be82e47..0e53c8cb2a7d 100755 --- a/lighthouse-core/scripts/lantern/run-once.js +++ b/lighthouse-core/scripts/lantern/run-once.js @@ -9,7 +9,7 @@ import fs from 'fs'; import path from 'path'; import PredictivePerf from '../../audits/predictive-perf.js'; -import Simulator from '../../lib/dependency-graph/simulator/simulator.js'; +import {Simulator} from '../../lib/dependency-graph/simulator/simulator.js'; import traceSaver from '../../lib/lantern-trace-saver.js'; import {LH_ROOT} from '../../../root.js'; import {readJson} from '../../test/test-utils.js'; diff --git a/lighthouse-core/scripts/legacy-javascript/run.js b/lighthouse-core/scripts/legacy-javascript/run.js index c1fe7ee3f50e..fb1bb1d2aee7 100644 --- a/lighthouse-core/scripts/legacy-javascript/run.js +++ b/lighthouse-core/scripts/legacy-javascript/run.js @@ -14,7 +14,7 @@ import glob from 'glob'; import {makeHash} from './hash.js'; import LegacyJavascript from '../../audits/byte-efficiency/legacy-javascript.js'; -import networkRecordsToDevtoolsLog from '../../test/network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../test/network-records-to-devtools-log.js'; import {LH_ROOT} from '../../../root.js'; import {readJson} from '../../test/test-utils.js'; diff --git a/lighthouse-core/scripts/print-a11y-scoring.js b/lighthouse-core/scripts/print-a11y-scoring.js index f179eb4f417f..334dbdf18180 100644 --- a/lighthouse-core/scripts/print-a11y-scoring.js +++ b/lighthouse-core/scripts/print-a11y-scoring.js @@ -6,7 +6,7 @@ // node lighthouse-core/scripts/print-a11y-scoring.js -import Config from '../config/config.js'; +import {Config} from '../config/config.js'; const config = await Config.fromJson(); if (!config.categories || !config.audits) throw new Error('wut'); diff --git a/lighthouse-core/scripts/run-jest.sh b/lighthouse-core/scripts/run-jest.sh new file mode 100644 index 000000000000..3a08f18271d5 --- /dev/null +++ b/lighthouse-core/scripts/run-jest.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash + +## +# @license Copyright 2022 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. +## + +# This wrapper around jest is only meant to help avoid the "Test environment has been torn down" error +# caused by a bug in v8's compilation cache. In short, due to that bug Jest will randomly use the wrong +# test environment for dynamic imports. It happens less often when fewer tests run, so a hacky workaround +# for now is to re-run the failed tests when this error occurs. +# See https://github.com/facebook/jest/issues/11438#issuecomment-923835189 +# and https://bugs.chromium.org/p/v8/issues/detail?id=10284 + +set -o pipefail + +DIRNAME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +LH_ROOT="$DIRNAME/../.." + +EXTRA_FLAGS=() + +mkdir -p .tmp + +# Repeating once is typically enough, but just in case... +count=5 +for i in $(seq $count); do + # Copy jest stderr to file, while keeping the output in the terminal and not messing up carriage returns. + # https://unix.stackexchange.com/a/333204 + # https://superuser.com/a/1124144 + exec 3>&1 + node --experimental-vm-modules ./node_modules/jest/bin/jest.js ${EXTRA_FLAGS[*]} $* 2>&1 >&3 | tee >(sed 's/.*\r//' >.tmp/jest-stderr.txt) + jest_status=$? + echo "$jest_status" + if [ $jest_status -eq 0 ]; + then + exit 0 + fi + + if grep -Fq "Test environment has been torn down" .tmp/jest-stderr.txt + then + echo "=====================================================" + echo "Noticed a v8 bug, so re-running just the failed tests" + echo "=====================================================" + EXTRA_FLAGS=(-f) + else + exit $jest_status + fi +done diff --git a/lighthouse-core/scripts/update-flow-fixtures.js b/lighthouse-core/scripts/update-flow-fixtures.js index d35fa9c90786..dae563df6be7 100644 --- a/lighthouse-core/scripts/update-flow-fixtures.js +++ b/lighthouse-core/scripts/update-flow-fixtures.js @@ -16,8 +16,8 @@ import yargs from 'yargs'; import {getChromePath} from 'chrome-launcher'; import {LH_ROOT} from '../../root.js'; -import api from '../fraggle-rock/api.js'; -import assetSaver from '../lib/asset-saver.js'; +import * as api from '../fraggle-rock/api.js'; +import * as assetSaver from '../lib/asset-saver.js'; const ARTIFACTS_PATH = `${LH_ROOT}/lighthouse-core/test/fixtures/fraggle-rock/artifacts/sample-flow-artifacts.json`; diff --git a/lighthouse-core/scripts/update-report-fixtures.js b/lighthouse-core/scripts/update-report-fixtures.js index 74ab00f72040..ec16b325715d 100644 --- a/lighthouse-core/scripts/update-report-fixtures.js +++ b/lighthouse-core/scripts/update-report-fixtures.js @@ -6,7 +6,7 @@ import * as cli from '../../lighthouse-cli/run.js'; import * as cliFlags from '../../lighthouse-cli/cli-flags.js'; -import assetSaver from '../lib/asset-saver.js'; +import * as assetSaver from '../lib/asset-saver.js'; import {server} from '../../lighthouse-cli/test/fixtures/static-server.js'; import budgetedConfig from '../test/results/sample-config.js'; diff --git a/lighthouse-core/test/audits/audit-test.js b/lighthouse-core/test/audits/audit-test.js index 3509ab07bbd8..1dbf800d3aa2 100644 --- a/lighthouse-core/test/audits/audit-test.js +++ b/lighthouse-core/test/audits/audit-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import Audit from '../../audits/audit.js'; +import {Audit} from '../../audits/audit.js'; // Extend the Audit class but fail to implement meta. It should throw errors. class A extends Audit {} diff --git a/lighthouse-core/test/audits/byte-efficiency/byte-efficiency-audit-test.js b/lighthouse-core/test/audits/byte-efficiency/byte-efficiency-audit-test.js index 812f256ac788..7965ebcb5233 100644 --- a/lighthouse-core/test/audits/byte-efficiency/byte-efficiency-audit-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/byte-efficiency-audit-test.js @@ -6,10 +6,10 @@ import {strict as assert} from 'assert'; -import ByteEfficiencyAudit_ from '../../../audits/byte-efficiency/byte-efficiency-audit.js'; -import NetworkNode from '../../../lib/dependency-graph/network-node.js'; -import CPUNode from '../../../lib/dependency-graph/cpu-node.js'; -import Simulator from '../../../lib/dependency-graph/simulator/simulator.js'; +import {ByteEfficiencyAudit as ByteEfficiencyAudit_} from '../../../audits/byte-efficiency/byte-efficiency-audit.js'; +import {NetworkNode} from '../../../lib/dependency-graph/network-node.js'; +import {CPUNode} from '../../../lib/dependency-graph/cpu-node.js'; +import {Simulator} from '../../../lib/dependency-graph/simulator/simulator.js'; import PageDependencyGraph from '../../../computed/page-dependency-graph.js'; import LoadSimulator from '../../../computed/load-simulator.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../../test-utils.js'; diff --git a/lighthouse-core/test/audits/byte-efficiency/efficient-animated-content-test.js b/lighthouse-core/test/audits/byte-efficiency/efficient-animated-content-test.js index fa5e973d4d79..6c3f758b19e2 100644 --- a/lighthouse-core/test/audits/byte-efficiency/efficient-animated-content-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/efficient-animated-content-test.js @@ -8,7 +8,7 @@ import {strict as assert} from 'assert'; import EfficientAnimatedContent from '../../../audits/byte-efficiency/efficient-animated-content.js'; -import NetworkRequest from '../../../lib/network-request.js'; +import {NetworkRequest} from '../../../lib/network-request.js'; describe('Page uses videos for animated GIFs', () => { it('should flag gifs above 100kb as unoptimized', async () => { diff --git a/lighthouse-core/test/audits/byte-efficiency/legacy-javascript-test.js b/lighthouse-core/test/audits/byte-efficiency/legacy-javascript-test.js index 343acec37389..cf0bcca6556f 100644 --- a/lighthouse-core/test/audits/byte-efficiency/legacy-javascript-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/legacy-javascript-test.js @@ -5,7 +5,7 @@ */ import LegacyJavascript from '../../../audits/byte-efficiency/legacy-javascript.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; import {readJson} from '../../test-utils.js'; /** diff --git a/lighthouse-core/test/audits/byte-efficiency/offscreen-images-test.js b/lighthouse-core/test/audits/byte-efficiency/offscreen-images-test.js index 9ce1b979747a..fdcbe74cb487 100644 --- a/lighthouse-core/test/audits/byte-efficiency/offscreen-images-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/offscreen-images-test.js @@ -7,8 +7,8 @@ import {strict as assert} from 'assert'; import UnusedImages from '../../../audits/byte-efficiency/offscreen-images.js'; -import createTestTrace from '../../create-test-trace.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {createTestTrace} from '../../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; function generateRecord({ resourceSizeInKb, diff --git a/lighthouse-core/test/audits/byte-efficiency/render-blocking-resources-test.js b/lighthouse-core/test/audits/byte-efficiency/render-blocking-resources-test.js index 11a8de327f08..1082e11d0987 100644 --- a/lighthouse-core/test/audits/byte-efficiency/render-blocking-resources-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/render-blocking-resources-test.js @@ -7,11 +7,11 @@ import {strict as assert} from 'assert'; import RenderBlockingResourcesAudit from '../../../audits/byte-efficiency/render-blocking-resources.js'; // eslint-disable-line max-len -import constants from '../../../config/constants.js'; -import NetworkNode from '../../../lib/dependency-graph/network-node.js'; -import CPUNode from '../../../lib/dependency-graph/cpu-node.js'; -import Simulator from '../../../lib/dependency-graph/simulator/simulator.js'; -import NetworkRequest from '../../../lib/network-request.js'; +import * as constants from '../../../config/constants.js'; +import {NetworkNode} from '../../../lib/dependency-graph/network-node.js'; +import {CPUNode} from '../../../lib/dependency-graph/cpu-node.js'; +import {Simulator} from '../../../lib/dependency-graph/simulator/simulator.js'; +import {NetworkRequest} from '../../../lib/network-request.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../../test-utils.js'; const trace = readJson('../../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/byte-efficiency/total-byte-weight-test.js b/lighthouse-core/test/audits/byte-efficiency/total-byte-weight-test.js index 4c1e751d52d9..64372ceba024 100644 --- a/lighthouse-core/test/audits/byte-efficiency/total-byte-weight-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/total-byte-weight-test.js @@ -8,7 +8,7 @@ import {strict as assert} from 'assert'; import {URL} from 'url'; import TotalByteWeight from '../../../audits/byte-efficiency/total-byte-weight.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; const options = TotalByteWeight.defaultOptions; diff --git a/lighthouse-core/test/audits/byte-efficiency/unused-css-rules-test.js b/lighthouse-core/test/audits/byte-efficiency/unused-css-rules-test.js index fcdc4cd34b93..45faf842d228 100644 --- a/lighthouse-core/test/audits/byte-efficiency/unused-css-rules-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/unused-css-rules-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import UnusedCSSAudit from '../../../audits/byte-efficiency/unused-css-rules.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; describe('Best Practices: unused css rules audit', () => { function generate(content, length) { diff --git a/lighthouse-core/test/audits/byte-efficiency/unused-javascript-test.js b/lighthouse-core/test/audits/byte-efficiency/unused-javascript-test.js index 7199aef39dfa..43d58ad4bf64 100644 --- a/lighthouse-core/test/audits/byte-efficiency/unused-javascript-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/unused-javascript-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import UnusedJavaScript from '../../../audits/byte-efficiency/unused-javascript.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; import {createScript, loadSourceMapAndUsageFixture} from '../../test-utils.js'; const scriptUrlToId = new Map(); diff --git a/lighthouse-core/test/audits/byte-efficiency/uses-long-cache-ttl-test.js b/lighthouse-core/test/audits/byte-efficiency/uses-long-cache-ttl-test.js index c5a4efb372c3..97de4a737ffe 100644 --- a/lighthouse-core/test/audits/byte-efficiency/uses-long-cache-ttl-test.js +++ b/lighthouse-core/test/audits/byte-efficiency/uses-long-cache-ttl-test.js @@ -7,8 +7,8 @@ import {strict as assert} from 'assert'; import CacheHeadersAudit from '../../../audits/byte-efficiency/uses-long-cache-ttl.js'; -import NetworkRequest from '../../../lib/network-request.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {NetworkRequest} from '../../../lib/network-request.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; const options = CacheHeadersAudit.defaultOptions; diff --git a/lighthouse-core/test/audits/content-width-test.js b/lighthouse-core/test/audits/content-width-test.js index d4919ba6b54a..4f3cf77f89da 100644 --- a/lighthouse-core/test/audits/content-width-test.js +++ b/lighthouse-core/test/audits/content-width-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import Audit from '../../audits/content-width.js'; -import constants from '../../config/constants.js'; +import * as constants from '../../config/constants.js'; /** @param {LH.SharedFlagsSettings['formFactor']} formFactor */ const getFakeContext = (formFactor = 'mobile') => ({ diff --git a/lighthouse-core/test/audits/critical-request-chains-test.js b/lighthouse-core/test/audits/critical-request-chains-test.js index 3ccd7dce9337..e8ecaead1d2b 100644 --- a/lighthouse-core/test/audits/critical-request-chains-test.js +++ b/lighthouse-core/test/audits/critical-request-chains-test.js @@ -7,8 +7,8 @@ import {strict as assert} from 'assert'; import CriticalRequestChains from '../../audits/critical-request-chains.js'; -import createTestTrace from '../create-test-trace.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {createTestTrace} from '../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; import {readJson} from '../test-utils.js'; const redditDevtoolsLog = readJson('../fixtures/artifacts/perflog/defaultPass.devtoolslog.json', import.meta); diff --git a/lighthouse-core/test/audits/csp-xss-test.js b/lighthouse-core/test/audits/csp-xss-test.js index 5a1d306a2880..82fff4ceb9e6 100644 --- a/lighthouse-core/test/audits/csp-xss-test.js +++ b/lighthouse-core/test/audits/csp-xss-test.js @@ -7,7 +7,7 @@ import {Type} from 'csp_evaluator/dist/finding.js'; import CspXss from '../../audits/csp-xss.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; const SEVERITY = { syntax: { diff --git a/lighthouse-core/test/audits/dobetterweb/charset-test.js b/lighthouse-core/test/audits/dobetterweb/charset-test.js index 742b4322f25b..0fbe21787f18 100644 --- a/lighthouse-core/test/audits/dobetterweb/charset-test.js +++ b/lighthouse-core/test/audits/dobetterweb/charset-test.js @@ -6,8 +6,10 @@ import {strict as assert} from 'assert'; -import CharsetDefinedAudit from '../../../audits/dobetterweb/charset.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import CharsetDefinedAudit, { + CHARSET_HTML_REGEX, CHARSET_HTTP_REGEX, IANA_REGEX, +} from '../../../audits/dobetterweb/charset.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; const HTML_PRE = '<!doctype html><head>'; const HTML_POST = '</head><body><h1>hello'; @@ -113,9 +115,8 @@ describe('Charset defined audit', () => { }); describe('Charset regex check', () => { - const HTML_REGEX = CharsetDefinedAudit.CHARSET_HTML_REGEX; - const HTTP_REGEX = CharsetDefinedAudit.CHARSET_HTTP_REGEX; - const IANA_REGEX = CharsetDefinedAudit.IANA_REGEX; + const HTML_REGEX = CHARSET_HTML_REGEX; + const HTTP_REGEX = CHARSET_HTTP_REGEX; it('handles html correctly', () => { // Positive cases diff --git a/lighthouse-core/test/audits/dobetterweb/uses-http2-test.js b/lighthouse-core/test/audits/dobetterweb/uses-http2-test.js index 7ea5c3be8804..d12218ef03d6 100644 --- a/lighthouse-core/test/audits/dobetterweb/uses-http2-test.js +++ b/lighthouse-core/test/audits/dobetterweb/uses-http2-test.js @@ -6,7 +6,7 @@ import UsesHTTP2Audit from '../../../audits/dobetterweb/uses-http2.js'; import NetworkRecords from '../../../computed/network-records.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../../test-utils.js'; const trace = readJson('../../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/font-display-test.js b/lighthouse-core/test/audits/font-display-test.js index 8b4849e9f42d..a844d9c2425b 100644 --- a/lighthouse-core/test/audits/font-display-test.js +++ b/lighthouse-core/test/audits/font-display-test.js @@ -5,7 +5,7 @@ */ import FontDisplayAudit from '../../audits/font-display.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; describe('Performance: Font Display audit', () => { let networkRecords; diff --git a/lighthouse-core/test/audits/installable-manifest-test.js b/lighthouse-core/test/audits/installable-manifest-test.js index 80d73fd75dcd..fceb8aeae8d1 100644 --- a/lighthouse-core/test/audits/installable-manifest-test.js +++ b/lighthouse-core/test/audits/installable-manifest-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import InstallableManifestAudit from '../../audits/installable-manifest.js'; -import manifestParser from '../../lib/manifest-parser.js'; +import {parseManifest} from '../../lib/manifest-parser.js'; import {readJson} from '../test-utils.js'; const manifest = readJson('../fixtures/manifest.json', import.meta); @@ -19,7 +19,7 @@ const EXAMPLE_MANIFEST_URL = 'https://example.com/manifest.json'; const EXAMPLE_DOC_URL = 'https://example.com/index.html'; function generateMockArtifacts(src = manifestSrc) { - const exampleManifest = manifestParser(src, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const exampleManifest = parseManifest(src, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); const clonedArtifacts = JSON.parse(JSON.stringify({ WebAppManifest: exampleManifest, diff --git a/lighthouse-core/test/audits/is-on-https-test.js b/lighthouse-core/test/audits/is-on-https-test.js index 8b43e1fcd0a6..c52b2ab3ece2 100644 --- a/lighthouse-core/test/audits/is-on-https-test.js +++ b/lighthouse-core/test/audits/is-on-https-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import Audit from '../../audits/is-on-https.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; describe('Security: HTTPS audit', () => { function getArtifacts(networkRecords, mixedContentIssues) { diff --git a/lighthouse-core/test/audits/long-tasks-test.js b/lighthouse-core/test/audits/long-tasks-test.js index be5c54132bf0..f4288294ad0a 100644 --- a/lighthouse-core/test/audits/long-tasks-test.js +++ b/lighthouse-core/test/audits/long-tasks-test.js @@ -5,8 +5,8 @@ */ import LongTasks from '../../audits/long-tasks.js'; -import createTestTrace from '../create-test-trace.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {createTestTrace} from '../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; const BASE_TS = 12345e3; const TASK_URL = 'https://pwa.rocks'; diff --git a/lighthouse-core/test/audits/maskable-icon-test.js b/lighthouse-core/test/audits/maskable-icon-test.js index 18158602989a..aaaa0dd5e162 100644 --- a/lighthouse-core/test/audits/maskable-icon-test.js +++ b/lighthouse-core/test/audits/maskable-icon-test.js @@ -5,7 +5,7 @@ */ import MaskableIconAudit from '../../audits/maskable-icon.js'; -import manifestParser from '../../lib/manifest-parser.js'; +import {parseManifest} from '../../lib/manifest-parser.js'; import {readJson} from '../test-utils.js'; const manifest = readJson('../fixtures/manifest.json', import.meta); @@ -20,7 +20,7 @@ const EXAMPLE_DOC_URL = 'https://example.com/index.html'; * @param {string} */ function generateMockArtifacts(src = manifestSrc) { - const exampleManifest = manifestParser(src, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const exampleManifest = parseManifest(src, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); return { WebAppManifest: exampleManifest, diff --git a/lighthouse-core/test/audits/metrics/first-contentful-paint-test.js b/lighthouse-core/test/audits/metrics/first-contentful-paint-test.js index 3c71c5624a33..865f5ad160dd 100644 --- a/lighthouse-core/test/audits/metrics/first-contentful-paint-test.js +++ b/lighthouse-core/test/audits/metrics/first-contentful-paint-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import FcpAudit from '../../../audits/metrics/first-contentful-paint.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; import {readJson} from '../../test-utils.js'; const pwaTrace = readJson('../../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/metrics/first-meaningful-paint-test.js b/lighthouse-core/test/audits/metrics/first-meaningful-paint-test.js index a2134a20afd2..71b1cf9cc847 100644 --- a/lighthouse-core/test/audits/metrics/first-meaningful-paint-test.js +++ b/lighthouse-core/test/audits/metrics/first-meaningful-paint-test.js @@ -7,8 +7,8 @@ import {strict as assert} from 'assert'; import FMPAudit from '../../../audits/metrics/first-meaningful-paint.js'; -import Audit from '../../../audits/audit.js'; -import constants from '../../../config/constants.js'; +import {Audit} from '../../../audits/audit.js'; +import * as constants from '../../../config/constants.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../../test-utils.js'; const trace = readJson('../../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/metrics/interactive-test.js b/lighthouse-core/test/audits/metrics/interactive-test.js index 475ed9952ca8..cef595dd52ba 100644 --- a/lighthouse-core/test/audits/metrics/interactive-test.js +++ b/lighthouse-core/test/audits/metrics/interactive-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import Interactive from '../../../audits/metrics/interactive.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; import {readJson} from '../../test-utils.js'; const acceptableTrace = readJson('../../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/metrics/largest-contentful-paint-test.js b/lighthouse-core/test/audits/metrics/largest-contentful-paint-test.js index 72d2f3a83ebb..7484c8613086 100644 --- a/lighthouse-core/test/audits/metrics/largest-contentful-paint-test.js +++ b/lighthouse-core/test/audits/metrics/largest-contentful-paint-test.js @@ -5,7 +5,7 @@ */ import LCPAudit from '../../../audits/metrics/largest-contentful-paint.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; import {readJson} from '../../test-utils.js'; const trace = readJson('../../fixtures/traces/lcp-m78.json', import.meta); diff --git a/lighthouse-core/test/audits/metrics/speed-index-test.js b/lighthouse-core/test/audits/metrics/speed-index-test.js index 5ab2d1ed0525..e09158c569de 100644 --- a/lighthouse-core/test/audits/metrics/speed-index-test.js +++ b/lighthouse-core/test/audits/metrics/speed-index-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import Audit from '../../../audits/metrics/speed-index.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; import {readJson} from '../../test-utils.js'; const pwaTrace = readJson('../../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/metrics/total-blocking-time-test.js b/lighthouse-core/test/audits/metrics/total-blocking-time-test.js index 054ca69f1b44..264163125a38 100644 --- a/lighthouse-core/test/audits/metrics/total-blocking-time-test.js +++ b/lighthouse-core/test/audits/metrics/total-blocking-time-test.js @@ -5,7 +5,7 @@ */ import TBTAudit from '../../../audits/metrics/total-blocking-time.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../../test-utils.js'; const trace = readJson('../../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/network-requests-test.js b/lighthouse-core/test/audits/network-requests-test.js index e157cb387dca..82b4b9d7feec 100644 --- a/lighthouse-core/test/audits/network-requests-test.js +++ b/lighthouse-core/test/audits/network-requests-test.js @@ -5,7 +5,7 @@ */ import NetworkRequests from '../../audits/network-requests.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; import {readJson} from '../test-utils.js'; const cutoffLoadDevtoolsLog = readJson('../fixtures/traces/cutoff-load-m83.devtoolslog.json', import.meta); diff --git a/lighthouse-core/test/audits/performance-budget-test.js b/lighthouse-core/test/audits/performance-budget-test.js index cf0782a0a95b..592bf13afe7f 100644 --- a/lighthouse-core/test/audits/performance-budget-test.js +++ b/lighthouse-core/test/audits/performance-budget-test.js @@ -5,7 +5,7 @@ */ import ResourceBudgetAudit from '../../audits/performance-budget.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; describe('Performance: Resource budgets audit', () => { let artifacts; diff --git a/lighthouse-core/test/audits/preload-fonts-test.js b/lighthouse-core/test/audits/preload-fonts-test.js index 9436d7788cd8..2549b107f915 100644 --- a/lighthouse-core/test/audits/preload-fonts-test.js +++ b/lighthouse-core/test/audits/preload-fonts-test.js @@ -5,7 +5,7 @@ */ import PreloadFontsAudit from '../../audits/preload-fonts.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; describe('Preload Fonts Audit', () => { let networkRecords; diff --git a/lighthouse-core/test/audits/preload-lcp-image-test.js b/lighthouse-core/test/audits/preload-lcp-image-test.js index dd9b76cda1c0..34f68a80682f 100644 --- a/lighthouse-core/test/audits/preload-lcp-image-test.js +++ b/lighthouse-core/test/audits/preload-lcp-image-test.js @@ -5,8 +5,8 @@ */ import PreloadLCPImage from '../../audits/preload-lcp-image.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; -import createTestTrace from '../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; +import {createTestTrace} from '../create-test-trace.js'; const rootNodeUrl = 'http://example.com:3000'; const mainDocumentNodeUrl = 'http://www.example.com:3000'; diff --git a/lighthouse-core/test/audits/redirects-test.js b/lighthouse-core/test/audits/redirects-test.js index 8dcecac5e4b2..8806b711b6d1 100644 --- a/lighthouse-core/test/audits/redirects-test.js +++ b/lighthouse-core/test/audits/redirects-test.js @@ -7,8 +7,8 @@ import {strict as assert} from 'assert'; import RedirectsAudit from '../../audits/redirects.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; -import createTestTrace from '../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; +import {createTestTrace} from '../create-test-trace.js'; const FAILING_THREE_REDIRECTS = [{ requestId: '1', diff --git a/lighthouse-core/test/audits/resource-summary-test.js b/lighthouse-core/test/audits/resource-summary-test.js index cdca244ede8b..8a2e30fad26b 100644 --- a/lighthouse-core/test/audits/resource-summary-test.js +++ b/lighthouse-core/test/audits/resource-summary-test.js @@ -5,7 +5,7 @@ */ import ResourceSummaryAudit from '../../audits/resource-summary.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; describe('Performance: Resource summary audit', () => { let artifacts; diff --git a/lighthouse-core/test/audits/script-treemap-data-test.js b/lighthouse-core/test/audits/script-treemap-data-test.js index 02ce6f2b0dc4..3fb5d0e06703 100644 --- a/lighthouse-core/test/audits/script-treemap-data-test.js +++ b/lighthouse-core/test/audits/script-treemap-data-test.js @@ -5,7 +5,7 @@ */ import ScriptTreemapData_ from '../../audits/script-treemap-data.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; import { createScript, loadSourceMapAndUsageFixture, diff --git a/lighthouse-core/test/audits/seo/canonical-test.js b/lighthouse-core/test/audits/seo/canonical-test.js index 9336585df296..57d0d9f0141f 100644 --- a/lighthouse-core/test/audits/seo/canonical-test.js +++ b/lighthouse-core/test/audits/seo/canonical-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import CanonicalAudit from '../../../audits/seo/canonical.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; describe('SEO: Document has valid canonical link', () => { /** diff --git a/lighthouse-core/test/audits/seo/font-size-test.js b/lighthouse-core/test/audits/seo/font-size-test.js index a08457f01f25..21c043e220be 100644 --- a/lighthouse-core/test/audits/seo/font-size-test.js +++ b/lighthouse-core/test/audits/seo/font-size-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import FontSizeAudit from '../../../audits/seo/font-size.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; const URL = { requestedUrl: 'https://example.com', diff --git a/lighthouse-core/test/audits/seo/http-status-code-test.js b/lighthouse-core/test/audits/seo/http-status-code-test.js index 37d552be200c..8e010c91d659 100644 --- a/lighthouse-core/test/audits/seo/http-status-code-test.js +++ b/lighthouse-core/test/audits/seo/http-status-code-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import HTTPStatusCodeAudit from '../../../audits/seo/http-status-code.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; describe('SEO: HTTP code audit', () => { it('fails when status code is unsuccesfull', () => { diff --git a/lighthouse-core/test/audits/seo/is-crawlable-test.js b/lighthouse-core/test/audits/seo/is-crawlable-test.js index 2538d022c39e..ea7c2d937040 100644 --- a/lighthouse-core/test/audits/seo/is-crawlable-test.js +++ b/lighthouse-core/test/audits/seo/is-crawlable-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import IsCrawlableAudit from '../../../audits/seo/is-crawlable.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; describe('SEO: Is page crawlable audit', () => { const makeMetaElements = content => [{name: 'robots', content, node: {}}]; diff --git a/lighthouse-core/test/audits/seo/tap-targets-test.js b/lighthouse-core/test/audits/seo/tap-targets-test.js index 54e49fd5e6e2..303b20979e02 100644 --- a/lighthouse-core/test/audits/seo/tap-targets-test.js +++ b/lighthouse-core/test/audits/seo/tap-targets-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import TapTargetsAudit from '../../../audits/seo/tap-targets.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; /** @param {LH.SharedFlagsSettings['formFactor']} formFactor */ const getFakeContext = (formFactor = 'mobile') => ({ diff --git a/lighthouse-core/test/audits/server-response-time-test.js b/lighthouse-core/test/audits/server-response-time-test.js index d028ad32abb3..c89c1cee70d0 100644 --- a/lighthouse-core/test/audits/server-response-time-test.js +++ b/lighthouse-core/test/audits/server-response-time-test.js @@ -5,7 +5,7 @@ */ import ServerResponseTime from '../../audits/server-response-time.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; describe('Performance: server-response-time audit', () => { it('fails when response time of root document is higher than 600ms', async () => { const mainResource = { diff --git a/lighthouse-core/test/audits/service-worker-test.js b/lighthouse-core/test/audits/service-worker-test.js index 4ad5f684e3f4..cf7e65dd4554 100644 --- a/lighthouse-core/test/audits/service-worker-test.js +++ b/lighthouse-core/test/audits/service-worker-test.js @@ -8,7 +8,7 @@ import {strict as assert} from 'assert'; import ServiceWorker from '../../audits/service-worker.js'; import URL from '../../lib/url-shim.js'; -import manifestParser from '../../lib/manifest-parser.js'; +import {parseManifest} from '../../lib/manifest-parser.js'; function getBaseDirectory(urlStr) { const url = new URL(urlStr); @@ -54,7 +54,7 @@ function createArtifacts(swOpts, mainDocumentUrl, manifestJsonOrObject) { } else { const manifestJson = typeof manifestJsonOrObject === 'object' ? JSON.stringify(manifestJsonOrObject) : manifestJsonOrObject; - WebAppManifest = manifestParser(manifestJson, manifestUrl, mainDocumentUrl); + WebAppManifest = parseManifest(manifestJson, manifestUrl, mainDocumentUrl); } return { diff --git a/lighthouse-core/test/audits/splash-screen-test.js b/lighthouse-core/test/audits/splash-screen-test.js index 963c1159eb93..6ca3f727ea7f 100644 --- a/lighthouse-core/test/audits/splash-screen-test.js +++ b/lighthouse-core/test/audits/splash-screen-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import SplashScreenAudit from '../../audits/splash-screen.js'; -import manifestParser from '../../lib/manifest-parser.js'; +import {parseManifest} from '../../lib/manifest-parser.js'; import {readJson} from '../test-utils.js'; const manifest = readJson('../fixtures/manifest.json', import.meta); @@ -22,7 +22,7 @@ const EXAMPLE_DOC_URL = 'https://example.com/index.html'; * @param {string} src */ function generateMockArtifacts(src = manifestSrc) { - const exampleManifest = manifestParser(src, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const exampleManifest = parseManifest(src, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); return { WebAppManifest: exampleManifest, diff --git a/lighthouse-core/test/audits/themed-omnibox-test.js b/lighthouse-core/test/audits/themed-omnibox-test.js index be363ce25ab5..ece24e709ddd 100644 --- a/lighthouse-core/test/audits/themed-omnibox-test.js +++ b/lighthouse-core/test/audits/themed-omnibox-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import ThemedOmniboxAudit from '../../audits/themed-omnibox.js'; -import manifestParser from '../../lib/manifest-parser.js'; +import {parseManifest} from '../../lib/manifest-parser.js'; import {readJson} from '../test-utils.js'; const manifest = readJson('../fixtures/manifest.json', import.meta); @@ -20,7 +20,7 @@ const EXAMPLE_DOC_URL = 'https://example.com/index.html'; * @param {string} src */ function generateMockArtifacts(src = manifestSrc) { - const exampleManifest = manifestParser(src, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const exampleManifest = parseManifest(src, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); return { WebAppManifest: exampleManifest, diff --git a/lighthouse-core/test/audits/third-party-facades-test.js b/lighthouse-core/test/audits/third-party-facades-test.js index 277fac6d2b85..4b5c36df37ce 100644 --- a/lighthouse-core/test/audits/third-party-facades-test.js +++ b/lighthouse-core/test/audits/third-party-facades-test.js @@ -5,8 +5,8 @@ */ import ThirdPartyFacades from '../../audits/third-party-facades.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; -import createTestTrace from '../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; +import {createTestTrace} from '../create-test-trace.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../test-utils.js'; const pwaTrace = readJson('../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/third-party-summary-test.js b/lighthouse-core/test/audits/third-party-summary-test.js index d9132c957399..f727caede97b 100644 --- a/lighthouse-core/test/audits/third-party-summary-test.js +++ b/lighthouse-core/test/audits/third-party-summary-test.js @@ -5,7 +5,7 @@ */ import ThirdPartySummary from '../../audits/third-party-summary.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; import {readJson} from '../test-utils.js'; const pwaTrace = readJson('../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/audits/uses-rel-preconnect-test.js b/lighthouse-core/test/audits/uses-rel-preconnect-test.js index 7f2b22d6925a..fc462086d3bb 100644 --- a/lighthouse-core/test/audits/uses-rel-preconnect-test.js +++ b/lighthouse-core/test/audits/uses-rel-preconnect-test.js @@ -7,8 +7,8 @@ import {strict as assert} from 'assert'; import UsesRelPreconnect from '../../audits/uses-rel-preconnect.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; -import createTestTrace from '../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; +import {createTestTrace} from '../create-test-trace.js'; const mainResource = { url: 'https://www.example.com/', diff --git a/lighthouse-core/test/audits/uses-rel-preload-test.js b/lighthouse-core/test/audits/uses-rel-preload-test.js index 73a2525ebc50..6e4093290b21 100644 --- a/lighthouse-core/test/audits/uses-rel-preload-test.js +++ b/lighthouse-core/test/audits/uses-rel-preload-test.js @@ -7,8 +7,8 @@ import {strict as assert} from 'assert'; import UsesRelPreload from '../../audits/uses-rel-preload.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; -import createTestTrace from '../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; +import {createTestTrace} from '../create-test-trace.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../test-utils.js'; const pwaTrace = readJson('../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/computed/computed-artifact-test.js b/lighthouse-core/test/computed/computed-artifact-test.js index df80634f8d68..92361abe4cde 100644 --- a/lighthouse-core/test/computed/computed-artifact-test.js +++ b/lighthouse-core/test/computed/computed-artifact-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import makeComputedArtifact from '../../computed/computed-artifact.js'; +import {makeComputedArtifact} from '../../computed/computed-artifact.js'; describe('ComputedArtifact base class', () => { it('caches computed artifacts by strict equality', async () => { diff --git a/lighthouse-core/test/computed/critical-request-chains-test.js b/lighthouse-core/test/computed/critical-request-chains-test.js index 07392b8b33d8..155e61982ea2 100644 --- a/lighthouse-core/test/computed/critical-request-chains-test.js +++ b/lighthouse-core/test/computed/critical-request-chains-test.js @@ -7,9 +7,9 @@ import {strict as assert} from 'assert'; import CriticalRequestChains from '../../computed/critical-request-chains.js'; -import NetworkRequest from '../../lib/network-request.js'; -import createTestTrace from '../create-test-trace.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import {createTestTrace} from '../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../test-utils.js'; const wikipediaDevtoolsLog = readJson('../fixtures/wikipedia-redirect.devtoolslog.json', import.meta); diff --git a/lighthouse-core/test/computed/image-records-test.js b/lighthouse-core/test/computed/image-records-test.js index 07a9385df9ec..95938a23a900 100644 --- a/lighthouse-core/test/computed/image-records-test.js +++ b/lighthouse-core/test/computed/image-records-test.js @@ -5,7 +5,7 @@ */ import ImageRecords from '../../computed/image-records.js'; -import NetworkRequest from '../../lib/network-request.js'; +import {NetworkRequest} from '../../lib/network-request.js'; /** * @param {Partial<LH.Artifacts.NetworkRequest>=} partial diff --git a/lighthouse-core/test/computed/load-simulator-test.js b/lighthouse-core/test/computed/load-simulator-test.js index caf0d418e5e5..c0499b5568c1 100644 --- a/lighthouse-core/test/computed/load-simulator-test.js +++ b/lighthouse-core/test/computed/load-simulator-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import LoadSimulator from '../../computed/load-simulator.js'; -import NetworkNode from '../../lib/dependency-graph/network-node.js'; +import {NetworkNode} from '../../lib/dependency-graph/network-node.js'; import {readJson} from '../test-utils.js'; const devtoolsLog = readJson('../fixtures/traces/progressive-app-m60.devtools.log.json', import.meta); diff --git a/lighthouse-core/test/computed/main-resource-test.js b/lighthouse-core/test/computed/main-resource-test.js index bda8714768e7..7383fc2f97d7 100644 --- a/lighthouse-core/test/computed/main-resource-test.js +++ b/lighthouse-core/test/computed/main-resource-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import MainResource from '../../computed/main-resource.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; import {readJson} from '../test-utils.js'; const wikipediaDevtoolsLog = readJson('../fixtures/wikipedia-redirect.devtoolslog.json', import.meta); diff --git a/lighthouse-core/test/computed/manifest-values-test.js b/lighthouse-core/test/computed/manifest-values-test.js index 4966f5b3e469..aeeeff94955c 100644 --- a/lighthouse-core/test/computed/manifest-values-test.js +++ b/lighthouse-core/test/computed/manifest-values-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import ManifestValues from '../../computed/manifest-values.js'; -import manifestParser from '../../lib/manifest-parser.js'; +import {parseManifest} from '../../lib/manifest-parser.js'; import {readJson} from '../test-utils.js'; const manifest = readJson('../fixtures/manifest.json', import.meta); @@ -29,7 +29,7 @@ function getMockContext() { function noUrlManifestParser(manifestSrc) { const EXAMPLE_MANIFEST_URL = 'https://example.com/manifest.json'; const EXAMPLE_DOC_URL = 'https://example.com/index.html'; - return manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + return parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); } describe('ManifestValues computed artifact', () => { diff --git a/lighthouse-core/test/computed/metrics/cumulative-layout-shift-test.js b/lighthouse-core/test/computed/metrics/cumulative-layout-shift-test.js index df7d83420efa..8a4ba82a0555 100644 --- a/lighthouse-core/test/computed/metrics/cumulative-layout-shift-test.js +++ b/lighthouse-core/test/computed/metrics/cumulative-layout-shift-test.js @@ -5,7 +5,7 @@ */ import CumulativeLayoutShift from '../../../computed/metrics/cumulative-layout-shift.js'; -import createTestTrace from '../../create-test-trace.js'; +import {createTestTrace} from '../../create-test-trace.js'; import {readJson} from '../../test-utils.js'; const jumpyClsTrace = readJson('../../fixtures/traces/jumpy-cls-m90.json', import.meta); diff --git a/lighthouse-core/test/computed/metrics/lantern-first-contentful-paint-test.js b/lighthouse-core/test/computed/metrics/lantern-first-contentful-paint-test.js index 4574eec8a9fc..a3eb237d6434 100644 --- a/lighthouse-core/test/computed/metrics/lantern-first-contentful-paint-test.js +++ b/lighthouse-core/test/computed/metrics/lantern-first-contentful-paint-test.js @@ -8,8 +8,8 @@ import {strict as assert} from 'assert'; import LanternFirstContentfulPaint from '../../../computed/metrics/lantern-first-contentful-paint.js'; // eslint-disable-line max-len import {getURLArtifactFromDevtoolsLog, readJson} from '../../test-utils.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; -import createTestTrace from '../../create-test-trace.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; +import {createTestTrace} from '../../create-test-trace.js'; const trace = readJson('../../fixtures/traces/progressive-app-m60.json', import.meta); const devtoolsLog = readJson('../../fixtures/traces/progressive-app-m60.devtools.log.json', import.meta); diff --git a/lighthouse-core/test/computed/metrics/lantern-speed-index-test.js b/lighthouse-core/test/computed/metrics/lantern-speed-index-test.js index f2fbece762e8..9dc47ffead47 100644 --- a/lighthouse-core/test/computed/metrics/lantern-speed-index-test.js +++ b/lighthouse-core/test/computed/metrics/lantern-speed-index-test.js @@ -4,7 +4,7 @@ * 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. */ -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; import LanternSpeedIndex from '../../../computed/metrics/lantern-speed-index.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../../test-utils.js'; @@ -13,6 +13,7 @@ const devtoolsLog = readJson('../../fixtures/traces/progressive-app-m60.devtools const defaultThrottling = constants.throttling.mobileSlow4G; const URL = getURLArtifactFromDevtoolsLog(devtoolsLog); + describe('Metrics: Lantern Speed Index', () => { const gatherContext = {gatherMode: 'navigation'}; it('should compute predicted value', async () => { diff --git a/lighthouse-core/test/computed/metrics/responsiveness-test.js b/lighthouse-core/test/computed/metrics/responsiveness-test.js index 31638ca3e047..82795db99745 100644 --- a/lighthouse-core/test/computed/metrics/responsiveness-test.js +++ b/lighthouse-core/test/computed/metrics/responsiveness-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import Responsiveness from '../../../computed/metrics/responsiveness.js'; -import createTestTrace from '../../create-test-trace.js'; +import {createTestTrace} from '../../create-test-trace.js'; import {readJson} from '../../test-utils.js'; const interactionTrace = readJson('../../fixtures/traces/timespan-responsiveness-m103.trace.json', import.meta); diff --git a/lighthouse-core/test/computed/page-dependency-graph-test.js b/lighthouse-core/test/computed/page-dependency-graph-test.js index a829b99824b2..ae10b53e0f87 100644 --- a/lighthouse-core/test/computed/page-dependency-graph-test.js +++ b/lighthouse-core/test/computed/page-dependency-graph-test.js @@ -7,11 +7,11 @@ import {strict as assert} from 'assert'; import PageDependencyGraph from '../../computed/page-dependency-graph.js'; -import BaseNode from '../../lib/dependency-graph/base-node.js'; -import NetworkRequest from '../../lib/network-request.js'; +import {BaseNode} from '../../lib/dependency-graph/base-node.js'; +import {NetworkRequest} from '../../lib/network-request.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../test-utils.js'; -import NetworkRecorder from '../../lib/network-recorder.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {NetworkRecorder} from '../../lib/network-recorder.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; const sampleTrace = readJson('../fixtures/traces/iframe-m79.trace.json', import.meta); const sampleDevtoolsLog = readJson('../fixtures/traces/iframe-m79.devtoolslog.json', import.meta); diff --git a/lighthouse-core/test/computed/resource-summary-test.js b/lighthouse-core/test/computed/resource-summary-test.js index cea9f138c5e9..0dc6a0b7adcf 100644 --- a/lighthouse-core/test/computed/resource-summary-test.js +++ b/lighthouse-core/test/computed/resource-summary-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import ComputedResourceSummary from '../../computed/resource-summary.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; function mockArtifacts(networkRecords) { return { diff --git a/lighthouse-core/test/config/budget-test.js b/lighthouse-core/test/config/budget-test.js index 7b45bd38c26e..d051d16f5bce 100644 --- a/lighthouse-core/test/config/budget-test.js +++ b/lighthouse-core/test/config/budget-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import Budget from '../../config/budget.js'; +import {Budget} from '../../config/budget.js'; describe('Budget', () => { let budgets; diff --git a/lighthouse-core/test/config/config-helpers-test.js b/lighthouse-core/test/config/config-helpers-test.js index 9ed845829eb2..9f24d9c6c995 100644 --- a/lighthouse-core/test/config/config-helpers-test.js +++ b/lighthouse-core/test/config/config-helpers-test.js @@ -20,12 +20,12 @@ import { mergeConfigFragment, mergeConfigFragmentArrayByKey, } from '../../config/config-helpers.js'; -import Runner from '../../runner.js'; -import Gatherer from '../../gather/gatherers/gatherer.js'; +import {Runner} from '../../runner.js'; +import {Gatherer} from '../../gather/gatherers/gatherer.js'; import ImageElementsGatherer from '../../gather/gatherers/image-elements.js'; import UserTimingsAudit from '../../audits/user-timings.js'; import {LH_ROOT} from '../../../root.js'; -import {getModuleDirectory} from '../../../esm-utils.mjs'; +import {getModuleDirectory} from '../../../esm-utils.js'; const require = createRequire(import.meta.url); const moduleDir = getModuleDirectory(import.meta); diff --git a/lighthouse-core/test/config/config-plugin-test.js b/lighthouse-core/test/config/config-plugin-test.js index dec82301b447..e14fcaa92c64 100644 --- a/lighthouse-core/test/config/config-plugin-test.js +++ b/lighthouse-core/test/config/config-plugin-test.js @@ -6,11 +6,8 @@ import {strict as assert} from 'assert'; -import {getModulePath} from '../../../esm-utils.mjs'; import ConfigPlugin from '../../config/config-plugin.js'; -import i18n from '../../lib/i18n/i18n.js'; - -const modulePath = getModulePath(import.meta); +import * as i18n from '../../lib/i18n/i18n.js'; /** * @param {any} val @@ -73,7 +70,7 @@ describe('ConfigPlugin', () => { title: 'this is a title', description: 'this is a description', }; - const str_ = i18n.createMessageInstanceIdFn(modulePath, UIStrings); + const str_ = i18n.createMessageInstanceIdFn(import.meta.url, UIStrings); const localizedPlugin = { groups: { diff --git a/lighthouse-core/test/config/config-test.js b/lighthouse-core/test/config/config-test.js index 3d26f87c259a..93e1f1a4ad01 100644 --- a/lighthouse-core/test/config/config-test.js +++ b/lighthouse-core/test/config/config-test.js @@ -10,18 +10,18 @@ import {createRequire} from 'module'; import log from 'lighthouse-logger'; -import Config from '../../config/config.js'; +import {Config} from '../../config/config.js'; import defaultConfig from '../../config/default-config.js'; -import constants from '../../config/constants.js'; -import Gatherer from '../../gather/gatherers/gatherer.js'; -import Audit from '../../audits/audit.js'; -import i18n from '../../lib/i18n/i18n.js'; +import * as constants from '../../config/constants.js'; +import {Gatherer} from '../../gather/gatherers/gatherer.js'; +import {Audit} from '../../audits/audit.js'; +import * as i18n from '../../lib/i18n/i18n.js'; import format from '../../../shared/localization/format.js'; -import {getModuleDirectory, getModulePath} from '../../../esm-utils.mjs'; +import {getModuleDirectory, getModulePath} from '../../../esm-utils.js'; const require = createRequire(import.meta.url); -const modulePath = getModulePath(import.meta); const moduleDir = getModuleDirectory(import.meta); +const modulePath = getModulePath(import.meta); describe('Config', () => { let origConfig; @@ -368,12 +368,29 @@ describe('Config', () => { }, {configPath}), /absolute path/); }); - it('loads an audit relative to a config path', () => { - const configPath = modulePath; + ['', '.js', '.cjs'].forEach(variant => { + describe(`loads an audit (${variant})`, () => { + it('loads an audit relative to a config path', async () => { + const configPath = modulePath; - return assert.doesNotThrow(_ => Config.fromJson({ - audits: ['../fixtures/valid-custom-audit'], - }, {configPath})); + return assert.doesNotReject(Config.fromJson({ + audits: ['../fixtures/valid-custom-audit' + variant], + }, {configPath})); + }); + + it('loads an audit relative to the working directory', async () => { + // Construct an audit URL relative to current working directory, regardless + // of where test was started from. + const absoluteAuditPath = + path.resolve(moduleDir, '../fixtures/valid-custom-audit' + variant); + assert.doesNotThrow(() => require.resolve(absoluteAuditPath)); + const relativePath = path.relative(process.cwd(), absoluteAuditPath); + + return assert.doesNotReject(Config.fromJson({ + audits: [relativePath], + })); + }); + }); }); it('loads an audit from node_modules/', async () => { @@ -386,25 +403,16 @@ describe('Config', () => { }); }); - it('loads an audit relative to the working directory', async () => { - // Construct an audit URL relative to current working directory, regardless - // of where test was started from. - const absoluteAuditPath = path.resolve(moduleDir, '../fixtures/valid-custom-audit'); - assert.doesNotThrow(_ => require.resolve(absoluteAuditPath)); - const relativePath = path.relative(process.cwd(), absoluteAuditPath); - - return assert.doesNotThrow(_ => Config.fromJson({ - audits: [relativePath], - })); - }); - it('throws but not for missing audit when audit has a dependency error', async () => { await assert.rejects(Config.fromJson({ audits: [path.resolve(moduleDir, '../fixtures/invalid-audits/require-error.js')], }), function(err) { // We're expecting not to find parent class Audit, so only reject on our // own custom locate audit error, not the usual MODULE_NOT_FOUND. - return !/locate audit/.test(err) && err.code === 'MODULE_NOT_FOUND'; + // TODO(esmodules): Test migration note: + // "custom locate audit error" ??? But this is just a normal Error... + // comment is 4 yr old maybe just stale? we refactoring config require code a lot since then + return !/locate audit/.test(err) && err.code === 'ERR_MODULE_NOT_FOUND'; }); }); @@ -1346,21 +1354,25 @@ describe('Config', () => { assert.equal(typeof gatherer.instance.beforePass, 'function'); }); - it('loads gatherers from custom paths', async () => { - const customPath = path.resolve(moduleDir, '../fixtures/valid-custom-gatherer'); - const gatherer = await loadGatherer(customPath); - assert.equal(gatherer.instance.name, 'CustomGatherer'); - assert.equal(typeof gatherer.instance.beforePass, 'function'); - }); - - it('loads a gatherer relative to a config path', async () => { - const config = await Config.fromJson({ - passes: [{gatherers: ['../fixtures/valid-custom-gatherer']}], - }, {configPath: modulePath}); - const gatherer = config.passes[0].gatherers[0]; - - assert.equal(gatherer.instance.name, 'CustomGatherer'); - assert.equal(typeof gatherer.instance.beforePass, 'function'); + ['', '.js', '.cjs'].forEach(variant => { + describe(`loads custom gatherer (variant: "${variant}")`, () => { + it('loads gatherers from custom paths', async () => { + const customPath = path.resolve(moduleDir, '../fixtures/valid-custom-gatherer' + variant); + const gatherer = await loadGatherer(customPath); + assert.equal(gatherer.instance.name, 'CustomGatherer'); + assert.equal(typeof gatherer.instance.beforePass, 'function'); + }); + + it('loads a gatherer relative to a config path', async () => { + const config = await Config.fromJson({ + passes: [{gatherers: ['../fixtures/valid-custom-gatherer' + variant]}], + }, {configPath: modulePath}); + const gatherer = config.passes[0].gatherers[0]; + + assert.equal(gatherer.instance.name, 'CustomGatherer'); + assert.equal(typeof gatherer.instance.beforePass, 'function'); + }); + }); }); it('returns gatherer when gatherer class, not package-name string, is provided', async () => { @@ -1415,7 +1427,7 @@ describe('Config', () => { function(err) { // We're expecting not to find parent class Gatherer, so only reject on // our own custom locate gatherer error, not the usual MODULE_NOT_FOUND. - return !/locate gatherer/.test(err) && err.code === 'MODULE_NOT_FOUND'; + return !/locate gatherer/.test(err) && err.code === 'ERR_MODULE_NOT_FOUND'; }); }); diff --git a/lighthouse-core/test/create-test-trace.js b/lighthouse-core/test/create-test-trace.js index 7b085da75477..d91b01bf7490 100644 --- a/lighthouse-core/test/create-test-trace.js +++ b/lighthouse-core/test/create-test-trace.js @@ -4,7 +4,6 @@ * 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. */ - const pid = 1111; const tid = 222; const browserPid = 13725; @@ -199,4 +198,4 @@ function createTestTrace(options) { return {traceEvents}; } -export default createTestTrace; +export {createTestTrace}; diff --git a/lighthouse-core/test/fixtures/invalid-audits/missing-audit.js b/lighthouse-core/test/fixtures/invalid-audits/missing-audit.js index 594b1d1b10ae..443e279688f9 100644 --- a/lighthouse-core/test/fixtures/invalid-audits/missing-audit.js +++ b/lighthouse-core/test/fixtures/invalid-audits/missing-audit.js @@ -4,10 +4,9 @@ * 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. */ +import {Audit} from '../../../audits/audit.js'; -const LighthouseAudit = require('../../../audits/audit.js'); - -class MissingAuditFn extends LighthouseAudit { +class MissingAuditFn extends Audit { static get meta() { return { id: 'missing-audit-fn', @@ -18,4 +17,4 @@ class MissingAuditFn extends LighthouseAudit { } } -module.exports = MissingAuditFn; +export default MissingAuditFn; diff --git a/lighthouse-core/test/fixtures/invalid-audits/missing-description.js b/lighthouse-core/test/fixtures/invalid-audits/missing-description.js index 87e8c5d2e3c4..5423acb8f398 100644 --- a/lighthouse-core/test/fixtures/invalid-audits/missing-description.js +++ b/lighthouse-core/test/fixtures/invalid-audits/missing-description.js @@ -4,10 +4,9 @@ * 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. */ +import {Audit} from '../../../audits/audit.js'; -const LighthouseAudit = require('../../../audits/audit.js'); - -class MissingDescription extends LighthouseAudit { +class MissingDescription extends Audit { static get meta() { return { id: 'missing-description', @@ -24,4 +23,4 @@ class MissingDescription extends LighthouseAudit { } } -module.exports = MissingDescription; +export default MissingDescription; diff --git a/lighthouse-core/test/fixtures/invalid-audits/missing-generate-audit-result.js b/lighthouse-core/test/fixtures/invalid-audits/missing-generate-audit-result.js index fba5f82ff8de..017b7cd587c7 100644 --- a/lighthouse-core/test/fixtures/invalid-audits/missing-generate-audit-result.js +++ b/lighthouse-core/test/fixtures/invalid-audits/missing-generate-audit-result.js @@ -4,7 +4,6 @@ * 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. */ - class MissingGenerateAuditResult { static get meta() { return { @@ -22,4 +21,4 @@ class MissingGenerateAuditResult { } } -module.exports = MissingGenerateAuditResult; +export default MissingGenerateAuditResult; diff --git a/lighthouse-core/test/fixtures/invalid-audits/missing-id.js b/lighthouse-core/test/fixtures/invalid-audits/missing-id.js index 01e554f28690..e13fd3c785fc 100644 --- a/lighthouse-core/test/fixtures/invalid-audits/missing-id.js +++ b/lighthouse-core/test/fixtures/invalid-audits/missing-id.js @@ -4,10 +4,9 @@ * 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. */ +import {Audit} from '../../../audits/audit.js'; -const LighthouseAudit = require('../../../audits/audit.js'); - -class MissingID extends LighthouseAudit { +class MissingID extends Audit { static get meta() { return { title: 'Missing id', @@ -23,4 +22,4 @@ class MissingID extends LighthouseAudit { } } -module.exports = MissingID; +export default MissingID; diff --git a/lighthouse-core/test/fixtures/invalid-audits/missing-meta.js b/lighthouse-core/test/fixtures/invalid-audits/missing-meta.js index 0f76a720f7fb..59b23623ea63 100644 --- a/lighthouse-core/test/fixtures/invalid-audits/missing-meta.js +++ b/lighthouse-core/test/fixtures/invalid-audits/missing-meta.js @@ -4,10 +4,9 @@ * 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. */ +import {Audit} from '../../../audits/audit.js'; -const LighthouseAudit = require('../../../audits/audit.js'); - -class MissingMeta extends LighthouseAudit { +class MissingMeta extends Audit { static audit(_) { return { score: 1, @@ -15,4 +14,4 @@ class MissingMeta extends LighthouseAudit { } } -module.exports = MissingMeta; +export default MissingMeta; diff --git a/lighthouse-core/test/fixtures/invalid-audits/missing-required-artifacts.js b/lighthouse-core/test/fixtures/invalid-audits/missing-required-artifacts.js index 01206d2c8d3d..e49b71c2b9d7 100644 --- a/lighthouse-core/test/fixtures/invalid-audits/missing-required-artifacts.js +++ b/lighthouse-core/test/fixtures/invalid-audits/missing-required-artifacts.js @@ -4,10 +4,9 @@ * 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. */ +import {Audit} from '../../../audits/audit.js'; -const LighthouseAudit = require('../../../audits/audit.js'); - -class MissingRequiredArtifacts extends LighthouseAudit { +class MissingRequiredArtifacts extends Audit { static get meta() { return { id: 'missing-required-artifacts', @@ -24,4 +23,4 @@ class MissingRequiredArtifacts extends LighthouseAudit { } } -module.exports = MissingRequiredArtifacts; +export default MissingRequiredArtifacts; diff --git a/lighthouse-core/test/fixtures/invalid-audits/missing-title.js b/lighthouse-core/test/fixtures/invalid-audits/missing-title.js index 0e27948cc263..35d44c291a6d 100644 --- a/lighthouse-core/test/fixtures/invalid-audits/missing-title.js +++ b/lighthouse-core/test/fixtures/invalid-audits/missing-title.js @@ -4,10 +4,9 @@ * 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. */ +import {Audit} from '../../../audits/audit.js'; -const LighthouseAudit = require('../../../audits/audit.js'); - -class MissingTitle extends LighthouseAudit { +class MissingTitle extends Audit { static get meta() { return { id: 'missing-title', @@ -23,4 +22,4 @@ class MissingTitle extends LighthouseAudit { } } -module.exports = MissingTitle; +export default MissingTitle; diff --git a/lighthouse-core/test/fixtures/invalid-audits/require-error.js b/lighthouse-core/test/fixtures/invalid-audits/require-error.js index 7b256520f7db..13b29b96c4ab 100644 --- a/lighthouse-core/test/fixtures/invalid-audits/require-error.js +++ b/lighthouse-core/test/fixtures/invalid-audits/require-error.js @@ -4,10 +4,9 @@ * 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. */ - // NOTE: this require path does not resolve correctly. // eslint-disable-next-line local-rules/require-file-extension -const LighthouseAudit = require('../terrible/path/come/on/audit.js'); +import LighthouseAudit from '../terrible/path/come/on/audit.js'; class RequireErrorAudit extends LighthouseAudit { static get meta() { @@ -22,4 +21,4 @@ class RequireErrorAudit extends LighthouseAudit { static audit() {} } -module.exports = RequireErrorAudit; +export default RequireErrorAudit; diff --git a/lighthouse-core/test/fixtures/invalid-gatherers/missing-after-pass.js b/lighthouse-core/test/fixtures/invalid-gatherers/missing-after-pass.js index 866b723e32c1..4d0f0bec7955 100644 --- a/lighthouse-core/test/fixtures/invalid-gatherers/missing-after-pass.js +++ b/lighthouse-core/test/fixtures/invalid-gatherers/missing-after-pass.js @@ -4,10 +4,9 @@ * 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. */ - class MissingAfterPass { beforePass() {} pass() {} } -module.exports = MissingAfterPass; +export default MissingAfterPass; diff --git a/lighthouse-core/test/fixtures/invalid-gatherers/missing-before-pass.js b/lighthouse-core/test/fixtures/invalid-gatherers/missing-before-pass.js index 66319e205b3e..7d3b5345497a 100644 --- a/lighthouse-core/test/fixtures/invalid-gatherers/missing-before-pass.js +++ b/lighthouse-core/test/fixtures/invalid-gatherers/missing-before-pass.js @@ -4,10 +4,9 @@ * 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. */ - class MissingBeforePass { pass() {} afterPass() {} } -module.exports = MissingBeforePass; +export default MissingBeforePass; diff --git a/lighthouse-core/test/fixtures/invalid-gatherers/missing-pass.js b/lighthouse-core/test/fixtures/invalid-gatherers/missing-pass.js index 57de2427ccaf..8c0b13986dba 100644 --- a/lighthouse-core/test/fixtures/invalid-gatherers/missing-pass.js +++ b/lighthouse-core/test/fixtures/invalid-gatherers/missing-pass.js @@ -4,10 +4,9 @@ * 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. */ - class MissingPass { beforePass() {} afterPass() {} } -module.exports = MissingPass; +export default MissingPass; diff --git a/lighthouse-core/test/fixtures/invalid-gatherers/require-error.js b/lighthouse-core/test/fixtures/invalid-gatherers/require-error.js index a5fd487f679e..6c07fb8785b8 100644 --- a/lighthouse-core/test/fixtures/invalid-gatherers/require-error.js +++ b/lighthouse-core/test/fixtures/invalid-gatherers/require-error.js @@ -4,11 +4,10 @@ * 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. */ - // NOTE: this require path does not resolve correctly. // eslint-disable-next-line local-rules/require-file-extension -const LighthouseGatherer = require('../terrible/path/no/seriously/gatherer.js'); +import LighthouseGatherer from '../terrible/path/no/seriously/gatherer.js'; class CustomGatherer extends LighthouseGatherer {} -module.exports = CustomGatherer; +export default CustomGatherer; diff --git a/lighthouse-core/test/fixtures/package.json b/lighthouse-core/test/fixtures/package.json deleted file mode 100644 index b4c41cebcb3c..000000000000 --- a/lighthouse-core/test/fixtures/package.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "type": "commonjs", - "//": "All fixtures are commonjs until core/ is modules." -} \ No newline at end of file diff --git a/lighthouse-core/test/fixtures/valid-custom-audit.cjs b/lighthouse-core/test/fixtures/valid-custom-audit.cjs new file mode 100644 index 000000000000..61a98a10c72a --- /dev/null +++ b/lighthouse-core/test/fixtures/valid-custom-audit.cjs @@ -0,0 +1,21 @@ +/** + * @license Copyright 2022 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. + */ + +module.exports = import('../../audits/audit.js').then(({Audit}) => { + return class ValidCustomAudit extends Audit { + static get meta() { + return { + id: 'valid-audit', + title: 'Valid Audit', + failureTitle: 'Valid failing Audit', + description: 'Valid-sounding description', + requiredArtifacts: ['HTML'], + }; + } + + static audit() {} + }; +}); diff --git a/lighthouse-core/test/fixtures/valid-custom-audit.js b/lighthouse-core/test/fixtures/valid-custom-audit.js index 2bcc3133af9a..c8f4e7bae867 100644 --- a/lighthouse-core/test/fixtures/valid-custom-audit.js +++ b/lighthouse-core/test/fixtures/valid-custom-audit.js @@ -5,9 +5,9 @@ */ -const LighthouseAudit = require('../../audits/audit.js'); +import {Audit} from '../../audits/audit.js'; -class ValidCustomAudit extends LighthouseAudit { +class ValidCustomAudit extends Audit { static get meta() { return { id: 'valid-audit', @@ -21,4 +21,4 @@ class ValidCustomAudit extends LighthouseAudit { static audit() {} } -module.exports = ValidCustomAudit; +export default ValidCustomAudit; diff --git a/lighthouse-core/test/fixtures/valid-custom-gatherer.cjs b/lighthouse-core/test/fixtures/valid-custom-gatherer.cjs new file mode 100644 index 000000000000..5ed8a4bb22e6 --- /dev/null +++ b/lighthouse-core/test/fixtures/valid-custom-gatherer.cjs @@ -0,0 +1,9 @@ +/** + * @license Copyright 2022 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. + */ + +module.exports = import('../../gather/gatherers/gatherer.js').then(({Gatherer}) => { + return class CustomGatherer extends Gatherer {}; +}); diff --git a/lighthouse-core/test/fixtures/valid-custom-gatherer.js b/lighthouse-core/test/fixtures/valid-custom-gatherer.js index 4d43e67f2fea..717eabaa5484 100644 --- a/lighthouse-core/test/fixtures/valid-custom-gatherer.js +++ b/lighthouse-core/test/fixtures/valid-custom-gatherer.js @@ -4,9 +4,8 @@ * 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. */ +import {Gatherer} from '../../gather/gatherers/gatherer.js'; -const LighthouseGatherer = require('../../gather/gatherers/gatherer.js'); +class CustomGatherer extends Gatherer {} -class CustomGatherer extends LighthouseGatherer {} - -module.exports = CustomGatherer; +export default CustomGatherer; diff --git a/lighthouse-core/test/fraggle-rock/config/config-test.js b/lighthouse-core/test/fraggle-rock/config/config-test.js index f2ae9466afcc..96a9ba6bc536 100644 --- a/lighthouse-core/test/fraggle-rock/config/config-test.js +++ b/lighthouse-core/test/fraggle-rock/config/config-test.js @@ -6,8 +6,8 @@ import jestMock from 'jest-mock'; -import BaseAudit from '../../../audits/audit.js'; -import constants from '../../../config/constants.js'; +import {Audit as BaseAudit} from '../../../audits/audit.js'; +import * as constants from '../../../config/constants.js'; import BaseGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; import {initializeConfig, getConfigDisplayString} from '../../../fraggle-rock/config/config.js'; import {LH_ROOT} from '../../../../root.js'; @@ -480,8 +480,15 @@ describe('Fraggle Rock Config', () => { artifacts: [{id: 'artifact', gatherer: {instance: new BaseGatherer()}}], }; - expect(initializeConfig(extensionConfig, {gatherMode: 'navigation'})) - .rejects.toThrow(/did not support any gather modes/); + // https://github.com/facebook/jest/issues/11438 + // expect(initializeConfig(extensionConfig, {gatherMode: 'navigation'})) + // .rejects.toThrow(/did not support any gather modes/); + try { + await initializeConfig(extensionConfig, {gatherMode: 'navigation'}); + throw new Error('did not throw'); + } catch (err) { + expect(err.message).toMatch(/did not support any gather modes/); + } }); }); diff --git a/lighthouse-core/test/fraggle-rock/config/filters-test.js b/lighthouse-core/test/fraggle-rock/config/filters-test.js index 6fcc55515470..8161e43637d7 100644 --- a/lighthouse-core/test/fraggle-rock/config/filters-test.js +++ b/lighthouse-core/test/fraggle-rock/config/filters-test.js @@ -6,10 +6,10 @@ import log from 'lighthouse-logger'; -import BaseAudit from '../../../audits/audit.js'; +import {Audit as BaseAudit} from '../../../audits/audit.js'; import BaseGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; import {defaultSettings, defaultNavigationConfig} from '../../../config/constants.js'; -import filters from '../../../fraggle-rock/config/filters.js'; +import * as filters from '../../../fraggle-rock/config/filters.js'; import {initializeConfig} from '../../../fraggle-rock/config/config.js'; describe('Fraggle Rock Config Filtering', () => { diff --git a/lighthouse-core/test/fraggle-rock/config/validation-test.js b/lighthouse-core/test/fraggle-rock/config/validation-test.js index 1035e9aebeac..2124170f2a8b 100644 --- a/lighthouse-core/test/fraggle-rock/config/validation-test.js +++ b/lighthouse-core/test/fraggle-rock/config/validation-test.js @@ -6,10 +6,10 @@ import {defaultSettings, defaultNavigationConfig} from '../../../config/constants.js'; import defaultConfig from '../../../fraggle-rock/config/default-config.js'; -import BaseAudit from '../../../audits/audit.js'; +import {Audit as BaseAudit} from '../../../audits/audit.js'; import BaseFRGatherer from '../../../fraggle-rock/gather/base-gatherer.js'; -import BaseLegacyGatherer from '../../../gather/gatherers/gatherer.js'; -import validation from '../../../fraggle-rock/config/validation.js'; +import {Gatherer as BaseLegacyGatherer} from '../../../gather/gatherers/gatherer.js'; +import * as validation from '../../../fraggle-rock/config/validation.js'; /** @typedef {LH.Gatherer.GathererMeta['supportedModes']} SupportedModes */ diff --git a/lighthouse-core/test/fraggle-rock/gather/base-artifacts-test.js b/lighthouse-core/test/fraggle-rock/gather/base-artifacts-test.js index 8206255cc029..a1050ef07e7f 100644 --- a/lighthouse-core/test/fraggle-rock/gather/base-artifacts-test.js +++ b/lighthouse-core/test/fraggle-rock/gather/base-artifacts-test.js @@ -7,7 +7,7 @@ import {getBaseArtifacts, finalizeArtifacts} from '../../../fraggle-rock/gather/base-artifacts.js'; import {initializeConfig} from '../../../fraggle-rock/config/config.js'; import {createMockDriver} from './mock-driver.js'; -import LighthouseError from '../../../lib/lh-error.js'; +import {LighthouseError} from '../../../lib/lh-error.js'; function getMockDriverForArtifacts() { const driverMock = createMockDriver(); diff --git a/lighthouse-core/test/fraggle-rock/gather/driver-test.js b/lighthouse-core/test/fraggle-rock/gather/driver-test.js index 2313d8c574a8..be879bd0ce63 100644 --- a/lighthouse-core/test/fraggle-rock/gather/driver-test.js +++ b/lighthouse-core/test/fraggle-rock/gather/driver-test.js @@ -4,7 +4,7 @@ * 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. */ -import Driver from '../../../fraggle-rock/gather/driver.js'; +import {Driver} from '../../../fraggle-rock/gather/driver.js'; import {fnAny} from '../../test-utils.js'; import {createMockCdpSession} from './mock-driver.js'; diff --git a/lighthouse-core/test/fraggle-rock/gather/mock-driver.js b/lighthouse-core/test/fraggle-rock/gather/mock-driver.js index 99e05e32e2bb..d209475d9a57 100644 --- a/lighthouse-core/test/fraggle-rock/gather/mock-driver.js +++ b/lighthouse-core/test/fraggle-rock/gather/mock-driver.js @@ -16,11 +16,11 @@ import { createMockOnceFn, createMockSendCommandFn, } from '../../gather/mock-commands.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; import {fnAny} from '../../test-utils.js'; import {LH_ROOT} from '../../../../root.js'; -/** @typedef {import('../../../fraggle-rock/gather/driver.js')} Driver */ +/** @typedef {import('../../../fraggle-rock/gather/driver.js').Driver} Driver */ /** @typedef {import('../../../gather/driver/execution-context.js')} ExecutionContext */ function createMockSession() { @@ -174,29 +174,31 @@ function createMockDriver() { }; } -const runnerModule = { +const runnerMock = { getAuditList: fnAny().mockReturnValue([]), getGathererList: fnAny().mockReturnValue([]), audit: fnAny(), gather: fnAny(), reset() { - runnerModule.getGathererList.mockReturnValue([]); - runnerModule.getAuditList.mockReturnValue([]); - runnerModule.audit.mockReset(); - runnerModule.gather.mockReset(); + runnerMock.getGathererList.mockReturnValue([]); + runnerMock.getAuditList.mockReturnValue([]); + runnerMock.audit.mockReset(); + runnerMock.gather.mockReset(); }, }; -function mockRunnerModule() { - td.replace(`${LH_ROOT}/lighthouse-core/runner.js`, runnerModule); - return runnerModule; +async function mockRunnerModule() { + await td.replaceEsm(`${LH_ROOT}/lighthouse-core/runner.js`, {Runner: runnerMock}); + return runnerMock; } /** @param {() => Driver} driverProvider */ function mockDriverModule(driverProvider) { - // This must be a regular function becaues Driver is always invoked as a constructor. - // Arrow functions cannot be invoked with `new`. - return function() { - return driverProvider(); + return { + // This must be a regular function becaues Driver is always invoked as a constructor. + // Arrow functions cannot be invoked with `new`. + Driver: function() { + return driverProvider(); + }, }; } @@ -247,7 +249,7 @@ function createMockContext() { }; } -function mockDriverSubmodules() { +async function mockDriverSubmodules() { const navigationMock = {gotoURL: fnAny()}; const prepareMock = { prepareThrottlingAndNetwork: fnAny(), @@ -282,15 +284,17 @@ function mockDriverSubmodules() { * @return {(...args: any[]) => void} */ const get = (target, name) => { + // @ts-expect-error: hack? What is going on here? Should we just remove the proxy stuff? + if (name === 'then') return target; if (!target[name]) throw new Error(`Target does not have property "${name}"`); return (...args) => target[name](...args); }; - td.replace('../../../gather/driver/navigation.js', new Proxy(navigationMock, {get})); - td.replace('../../../gather/driver/prepare.js', new Proxy(prepareMock, {get})); - td.replace('../../../gather/driver/storage.js', new Proxy(storageMock, {get})); - td.replace('../../../gather/driver/network.js', new Proxy(networkMock, {get})); - td.replace('../../../lib/emulation.js', new Proxy(emulationMock, {get})); + await td.replaceEsm('../../../gather/driver/navigation.js', new Proxy(navigationMock, {get})); + await td.replaceEsm('../../../gather/driver/prepare.js', new Proxy(prepareMock, {get})); + await td.replaceEsm('../../../gather/driver/storage.js', new Proxy(storageMock, {get})); + await td.replaceEsm('../../../gather/driver/network.js', new Proxy(networkMock, {get})); + await td.replaceEsm('../../../lib/emulation.js', new Proxy(emulationMock, {get})); reset(); diff --git a/lighthouse-core/test/fraggle-rock/gather/navigation-runner-test.js b/lighthouse-core/test/fraggle-rock/gather/navigation-runner-test.js index 53080df32611..c424c44db538 100644 --- a/lighthouse-core/test/fraggle-rock/gather/navigation-runner-test.js +++ b/lighthouse-core/test/fraggle-rock/gather/navigation-runner-test.js @@ -4,7 +4,6 @@ * 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. */ -import * as td from 'testdouble'; import jestMock from 'jest-mock'; import { @@ -15,12 +14,12 @@ import { } from './mock-driver.js'; import {initializeConfig} from '../../../fraggle-rock/config/config.js'; import {defaultNavigationConfig} from '../../../config/constants.js'; -import LighthouseError from '../../../lib/lh-error.js'; +import {LighthouseError} from '../../../lib/lh-error.js'; import DevtoolsLogGatherer from '../../../gather/gatherers/devtools-log.js'; import TraceGatherer from '../../../gather/gatherers/trace.js'; -import toDevtoolsLog from '../../network-records-to-devtools-log.js'; import {fnAny} from '../../test-utils.js'; -// import runner from '../../../fraggle-rock/gather/navigation-runner.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; +import {Runner as runnerActual} from '../../../runner.js'; // Some imports needs to be done dynamically, so that their dependencies will be mocked. // See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs @@ -28,17 +27,15 @@ import {fnAny} from '../../test-utils.js'; /** @type {import('../../../fraggle-rock/gather/navigation-runner.js')} */ let runner; -before(async () => { +const mocks = await mockDriverSubmodules(); +const mockRunner = await mockRunnerModule(); +beforeEach(async () => { + mockRunner.reset(); + mockRunner.getGathererList.mockImplementation(runnerActual.getGathererList); + mockRunner.getAuditList.mockImplementation(runnerActual.getAuditList); runner = (await import('../../../fraggle-rock/gather/navigation-runner.js')); }); -const mocks = mockDriverSubmodules(); - -const mockRunner = mockRunnerModule(); - -// Establish the mocks before we import the file under test. -td.replace('../../../runner.js', mockRunner); - /** @typedef {{meta: LH.Gatherer.GathererMeta<'Accessibility'>, getArtifact: Mock<any, any>, startInstrumentation: Mock<any, any>, stopInstrumentation: Mock<any, any>, startSensitiveInstrumentation: Mock<any, any>, stopSensitiveInstrumentation: Mock<any, any>}} MockGatherer */ describe('NavigationRunner', () => { @@ -47,7 +44,7 @@ describe('NavigationRunner', () => { let requestor; /** @type {ReturnType<typeof createMockDriver>} */ let mockDriver; - /** @type {import('../../../fraggle-rock/gather/driver.js')} */ + /** @type {import('../../../fraggle-rock/gather/driver.js').Driver} */ let driver; /** @type {LH.Config.FRConfig} */ let config; @@ -107,7 +104,6 @@ describe('NavigationRunner', () => { beforeEach(async () => { requestedUrl = 'http://example.com'; requestor = requestedUrl; - mockRunner.reset(); config = (await initializeConfig(undefined, {gatherMode: 'navigation'})).config; navigation = createNavigation().navigation; computedCache = new Map(); @@ -428,7 +424,7 @@ describe('NavigationRunner', () => { it('finds page load errors in network records when available', async () => { const {navigation, gatherers} = createNavigation(); mocks.navigationMock.gotoURL.mockResolvedValue({mainDocumentUrl: requestedUrl, warnings: []}); - const devtoolsLog = toDevtoolsLog([{url: requestedUrl, failed: true}]); + const devtoolsLog = networkRecordsToDevtoolsLog([{url: requestedUrl, failed: true}]); gatherers.timespan.meta.symbol = DevtoolsLogGatherer.symbol; gatherers.timespan.getArtifact = fnAny().mockResolvedValue(devtoolsLog); gatherers.navigation.meta.symbol = TraceGatherer.symbol; @@ -560,7 +556,6 @@ describe('NavigationRunner', () => { describe('navigation', () => { it('should throw on invalid URL', async () => { - const {default: runnerActual} = await import('../../../runner.js'); mockRunner.gather.mockImplementation(runnerActual.gather); const navigatePromise = runner.navigationGather( diff --git a/lighthouse-core/test/fraggle-rock/gather/runner-helpers-test.js b/lighthouse-core/test/fraggle-rock/gather/runner-helpers-test.js index 893f6aa47013..aeff082cae7b 100644 --- a/lighthouse-core/test/fraggle-rock/gather/runner-helpers-test.js +++ b/lighthouse-core/test/fraggle-rock/gather/runner-helpers-test.js @@ -4,7 +4,7 @@ * 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. */ -import helpers from '../../../fraggle-rock/gather/runner-helpers.js'; +import * as helpers from '../../../fraggle-rock/gather/runner-helpers.js'; import Gatherer from '../../../fraggle-rock/gather/base-gatherer.js'; import {defaultSettings} from '../../../config/constants.js'; import {createMockDriver, createMockGathererInstance, createMockBaseArtifacts} from './mock-driver.js'; // eslint-disable-line max-len diff --git a/lighthouse-core/test/fraggle-rock/gather/session-test.js b/lighthouse-core/test/fraggle-rock/gather/session-test.js index 7b50dd567592..72cbac64ec8d 100644 --- a/lighthouse-core/test/fraggle-rock/gather/session-test.js +++ b/lighthouse-core/test/fraggle-rock/gather/session-test.js @@ -8,7 +8,7 @@ import {EventEmitter} from 'events'; import {CDPSession} from 'puppeteer/lib/cjs/puppeteer/common/Connection.js'; -import ProtocolSession from '../../../fraggle-rock/gather/session.js'; +import {ProtocolSession} from '../../../fraggle-rock/gather/session.js'; import { flushAllTimersAndMicrotasks, makePromiseInspectable, diff --git a/lighthouse-core/test/fraggle-rock/gather/snapshot-runner-test.js b/lighthouse-core/test/fraggle-rock/gather/snapshot-runner-test.js index ca4f609aa725..753cf0baa983 100644 --- a/lighthouse-core/test/fraggle-rock/gather/snapshot-runner-test.js +++ b/lighthouse-core/test/fraggle-rock/gather/snapshot-runner-test.js @@ -25,13 +25,13 @@ before(async () => { snapshotGather = (await import('../../../fraggle-rock/gather/snapshot-runner.js')).snapshotGather; }); -const mockRunner = mockRunnerModule(); +const mockRunner = await mockRunnerModule(); // Establish the mocks before we import the file under test. /** @type {ReturnType<typeof createMockDriver>} */ let mockDriver; -td.replace('../../../fraggle-rock/gather/driver.js', +await td.replaceEsm('../../../fraggle-rock/gather/driver.js', mockDriverModule(() => mockDriver.asDriver())); describe('Snapshot Runner', () => { diff --git a/lighthouse-core/test/fraggle-rock/gather/timespan-runner-test.js b/lighthouse-core/test/fraggle-rock/gather/timespan-runner-test.js index fd55acaa0956..57dfd89e506c 100644 --- a/lighthouse-core/test/fraggle-rock/gather/timespan-runner-test.js +++ b/lighthouse-core/test/fraggle-rock/gather/timespan-runner-test.js @@ -27,13 +27,13 @@ before(async () => { (await import('../../../fraggle-rock/gather/timespan-runner.js')).startTimespanGather; }); -const mockSubmodules = mockDriverSubmodules(); -const mockRunner = mockRunnerModule(); +const mockSubmodules = await mockDriverSubmodules(); +const mockRunner = await mockRunnerModule(); // Establish the mocks before we import the file under test. /** @type {ReturnType<typeof createMockDriver>} */ let mockDriver; -td.replace('../../../fraggle-rock/gather/driver.js', +await td.replaceEsm('../../../fraggle-rock/gather/driver.js', mockDriverModule(() => mockDriver.asDriver())); describe('Timespan Runner', () => { diff --git a/lighthouse-core/test/fraggle-rock/user-flow-test.js b/lighthouse-core/test/fraggle-rock/user-flow-test.js index d465d85921c1..03d0b7b35a7e 100644 --- a/lighthouse-core/test/fraggle-rock/user-flow-test.js +++ b/lighthouse-core/test/fraggle-rock/user-flow-test.js @@ -7,7 +7,7 @@ import jestMock from 'jest-mock'; import * as td from 'testdouble'; -import Runner from '../../runner.js'; +import {Runner} from '../../runner.js'; import {createMockPage, mockRunnerModule} from './gather/mock-driver.js'; // import UserFlow from '../../fraggle-rock/user-flow.js'; @@ -24,13 +24,13 @@ before(async () => { }); const snapshotModule = {snapshotGather: jestMock.fn()}; -td.replace('../../fraggle-rock/gather/snapshot-runner.js', snapshotModule); +await td.replaceEsm('../../fraggle-rock/gather/snapshot-runner.js', snapshotModule); const navigationModule = {navigationGather: jestMock.fn()}; -td.replace('../../fraggle-rock/gather/navigation-runner.js', navigationModule); +await td.replaceEsm('../../fraggle-rock/gather/navigation-runner.js', navigationModule); const timespanModule = {startTimespanGather: jestMock.fn()}; -td.replace('../../fraggle-rock/gather/timespan-runner.js', timespanModule); +await td.replaceEsm('../../fraggle-rock/gather/timespan-runner.js', timespanModule); -const mockRunner = mockRunnerModule(); +const mockRunner = await mockRunnerModule(); describe('UserFlow', () => { let mockPage = createMockPage(); diff --git a/lighthouse-core/test/gather/driver-test.js b/lighthouse-core/test/gather/driver-test.js index 593920c11368..13f95ea42a46 100644 --- a/lighthouse-core/test/gather/driver-test.js +++ b/lighthouse-core/test/gather/driver-test.js @@ -4,9 +4,9 @@ * 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. */ -import Driver from '../../gather/driver.js'; -import Connection from '../../gather/connections/connection.js'; -import FakeDriver from './fake-driver.js'; +import {Driver} from '../../gather/driver.js'; +import {Connection} from '../../gather/connections/connection.js'; +import {fakeDriver} from './fake-driver.js'; import { mockCommands, makePromiseInspectable, @@ -15,7 +15,6 @@ import { timers, } from '../test-utils.js'; -const {protocolGetVersionResponse} = FakeDriver; const {createMockSendCommandFn} = mockCommands; timers.useFakeTimers(); @@ -120,7 +119,7 @@ describe('.sendCommand', () => { describe('.beginTrace', () => { beforeEach(() => { connectionStub.sendCommand = createMockSendCommandFn() - .mockResponse('Browser.getVersion', protocolGetVersionResponse) + .mockResponse('Browser.getVersion', fakeDriver.protocolGetVersionResponse) .mockResponse('Page.enable') .mockResponse('Tracing.start'); }); diff --git a/lighthouse-core/test/gather/driver/dom-test.js b/lighthouse-core/test/gather/driver/dom-test.js index 7f8d4545f96a..b630e4382d30 100644 --- a/lighthouse-core/test/gather/driver/dom-test.js +++ b/lighthouse-core/test/gather/driver/dom-test.js @@ -5,7 +5,7 @@ */ import {createMockSession} from '../../fraggle-rock/gather/mock-driver.js'; -import dom from '../../../gather/driver/dom.js'; +import * as dom from '../../../gather/driver/dom.js'; let sessionMock = createMockSession(); diff --git a/lighthouse-core/test/gather/driver/environment-test.js b/lighthouse-core/test/gather/driver/environment-test.js index 39fc8bce4f1e..5304a36bc29c 100644 --- a/lighthouse-core/test/gather/driver/environment-test.js +++ b/lighthouse-core/test/gather/driver/environment-test.js @@ -5,7 +5,7 @@ */ import {defaultSettings} from '../../../config/constants.js'; -import environment from '../../../gather/driver/environment.js'; +import * as environment from '../../../gather/driver/environment.js'; import {createMockSession} from '../../fraggle-rock/gather/mock-driver.js'; describe('.getBrowserVersion', () => { diff --git a/lighthouse-core/test/gather/driver/execution-context-test.js b/lighthouse-core/test/gather/driver/execution-context-test.js index c7afc2faf4c8..a4c260213332 100644 --- a/lighthouse-core/test/gather/driver/execution-context-test.js +++ b/lighthouse-core/test/gather/driver/execution-context-test.js @@ -4,7 +4,7 @@ * 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. */ -import ExecutionContext from '../../../gather/driver/execution-context.js'; +import {ExecutionContext} from '../../../gather/driver/execution-context.js'; import { mockCommands, makePromiseInspectable, diff --git a/lighthouse-core/test/gather/driver/network-monitor-test.js b/lighthouse-core/test/gather/driver/network-monitor-test.js index 00df325acbc4..5f52483c55ea 100644 --- a/lighthouse-core/test/gather/driver/network-monitor-test.js +++ b/lighthouse-core/test/gather/driver/network-monitor-test.js @@ -5,10 +5,10 @@ */ import {createMockCdpSession} from '../../fraggle-rock/gather/mock-driver.js'; -import NetworkMonitor from '../../../gather/driver/network-monitor.js'; -import NetworkRequest from '../../../lib/network-request.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; -import TargetManager from '../../../gather/driver/target-manager.js'; +import {NetworkMonitor} from '../../../gather/driver/network-monitor.js'; +import {NetworkRequest} from '../../../lib/network-request.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; +import {TargetManager} from '../../../gather/driver/target-manager.js'; const tscErr = new Error('Typecheck constraint failed'); diff --git a/lighthouse-core/test/gather/driver/prepare-test.js b/lighthouse-core/test/gather/driver/prepare-test.js index 697d1742c33f..a83e59e025bd 100644 --- a/lighthouse-core/test/gather/driver/prepare-test.js +++ b/lighthouse-core/test/gather/driver/prepare-test.js @@ -9,7 +9,7 @@ import * as td from 'testdouble'; import {createMockSession, createMockDriver} from '../../fraggle-rock/gather/mock-driver.js'; import {flushAllTimersAndMicrotasks, fnAny, timers} from '../../test-utils.js'; // import prepare from '../../../gather/driver/prepare.js'; -import constants from '../../../config/constants.js'; +import * as constants from '../../../config/constants.js'; // Some imports needs to be done dynamically, so that their dependencies will be mocked. // See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs @@ -26,7 +26,7 @@ const storageMock = { clearBrowserCaches: fnAny(), getImportantStorageWarning: fnAny(), }; -td.replace('../../../gather/driver/storage.js', storageMock); +await td.replaceEsm('../../../gather/driver/storage.js', storageMock); const url = 'https://example.com'; let sessionMock = createMockSession(); @@ -38,9 +38,9 @@ beforeEach(() => { .mockResponse('Emulation.setCPUThrottlingRate') .mockResponse('Network.setBlockedURLs') .mockResponse('Network.setExtraHTTPHeaders'); - storageMock.clearBrowserCaches = fnAny(); - storageMock.clearDataForOrigin = fnAny(); - storageMock.getImportantStorageWarning = fnAny(); + storageMock.clearDataForOrigin.mockReset(); + storageMock.clearBrowserCaches.mockReset(); + storageMock.getImportantStorageWarning.mockReset(); }); afterEach(() => { diff --git a/lighthouse-core/test/gather/driver/service-workers-test.js b/lighthouse-core/test/gather/driver/service-workers-test.js index 8bd22a987258..749bb9305b1a 100644 --- a/lighthouse-core/test/gather/driver/service-workers-test.js +++ b/lighthouse-core/test/gather/driver/service-workers-test.js @@ -6,7 +6,7 @@ import {createMockSession} from '../../fraggle-rock/gather/mock-driver.js'; import {makePromiseInspectable, flushAllTimersAndMicrotasks, timers} from '../../test-utils.js'; -import serviceWorkers from '../../../gather/driver/service-workers.js'; +import * as serviceWorkers from '../../../gather/driver/service-workers.js'; let sessionMock = createMockSession(); diff --git a/lighthouse-core/test/gather/driver/storage-test.js b/lighthouse-core/test/gather/driver/storage-test.js index 8b49330fcf9a..3b8816e1e149 100644 --- a/lighthouse-core/test/gather/driver/storage-test.js +++ b/lighthouse-core/test/gather/driver/storage-test.js @@ -5,7 +5,7 @@ */ import {createMockSession} from '../../fraggle-rock/gather/mock-driver.js'; -import storage from '../../../gather/driver/storage.js'; +import * as storage from '../../../gather/driver/storage.js'; let sessionMock = createMockSession(); diff --git a/lighthouse-core/test/gather/driver/target-manager-test.js b/lighthouse-core/test/gather/driver/target-manager-test.js index 845298ae1547..9d628411607d 100644 --- a/lighthouse-core/test/gather/driver/target-manager-test.js +++ b/lighthouse-core/test/gather/driver/target-manager-test.js @@ -8,7 +8,7 @@ import {EventEmitter} from 'events'; import {CDPSession} from 'puppeteer-core/lib/cjs/puppeteer/common/Connection.js'; -import TargetManager from '../../../gather/driver/target-manager.js'; +import {TargetManager} from '../../../gather/driver/target-manager.js'; import {createMockCdpSession} from '../../fraggle-rock/gather/mock-driver.js'; import {createMockSendCommandFn} from '../../gather/mock-commands.js'; import {fnAny} from '../../test-utils.js'; diff --git a/lighthouse-core/test/gather/driver/wait-for-condition-test.js b/lighthouse-core/test/gather/driver/wait-for-condition-test.js index 298daf49c46b..409b03efe40d 100644 --- a/lighthouse-core/test/gather/driver/wait-for-condition-test.js +++ b/lighthouse-core/test/gather/driver/wait-for-condition-test.js @@ -4,7 +4,7 @@ * 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. */ -import wait from '../../../gather/driver/wait-for-condition.js'; +import * as wait from '../../../gather/driver/wait-for-condition.js'; import { mockCommands, makePromiseInspectable, diff --git a/lighthouse-core/test/gather/fake-driver.js b/lighthouse-core/test/gather/fake-driver.js index d31d1d28b5aa..36d920d86e05 100644 --- a/lighthouse-core/test/gather/fake-driver.js +++ b/lighthouse-core/test/gather/fake-driver.js @@ -94,7 +94,6 @@ const protocolGetVersionResponse = { userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3577.0 Safari/537.36', jsVersion: '7.1.314', }; -const fakeDriver = makeFakeDriver({protocolGetVersionResponse}); const fakeDriverUsingRealMobileDevice = makeFakeDriver({ protocolGetVersionResponse: { @@ -105,8 +104,8 @@ const fakeDriverUsingRealMobileDevice = makeFakeDriver({ }); // TODO(esmodules): fix awkward export. -export default { - ...fakeDriver, +export const fakeDriver = { + ...makeFakeDriver({protocolGetVersionResponse}), fakeDriverUsingRealMobileDevice, protocolGetVersionResponse, }; diff --git a/lighthouse-core/test/gather/fetcher-test.js b/lighthouse-core/test/gather/fetcher-test.js index 162d2f3f506d..fb6fb44ca1df 100644 --- a/lighthouse-core/test/gather/fetcher-test.js +++ b/lighthouse-core/test/gather/fetcher-test.js @@ -4,7 +4,7 @@ * 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. */ -import Connection from '../../gather/connections/connection.js'; +import {Connection} from '../../gather/connections/connection.js'; import {fnAny, mockCommands} from '../test-utils.js'; const {createMockSendCommandFn} = mockCommands; @@ -12,16 +12,16 @@ const {createMockSendCommandFn} = mockCommands; // Some imports needs to be done dynamically, so that their dependencies will be mocked. // See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs // https://github.com/facebook/jest/issues/10025 -/** @typedef {import('../../gather/driver.js')} Driver */ -/** @type {typeof import('../../gather/driver.js')} */ +/** @typedef {import('../../gather/driver.js').Driver} Driver */ +/** @type {typeof import('../../gather/driver.js').Driver} */ let Driver; -/** @typedef {import('../../gather/fetcher.js')} Fetcher */ -/** @type {typeof import('../../gather/fetcher.js')} */ +/** @typedef {import('../../gather/fetcher.js').Fetcher} Fetcher */ +/** @type {typeof import('../../gather/fetcher.js').Fetcher} */ let Fetcher; before(async () => { - Driver = (await import('../../gather/driver.js')).default; - Fetcher = (await import('../../gather/fetcher.js')).default; + Driver = (await import('../../gather/driver.js')).Driver; + Fetcher = (await import('../../gather/fetcher.js')).Fetcher; }); /** @type {Connection} */ diff --git a/lighthouse-core/test/gather/gather-runner-test.js b/lighthouse-core/test/gather/gather-runner-test.js index 779d64b0064f..0b66db432be7 100644 --- a/lighthouse-core/test/gather/gather-runner-test.js +++ b/lighthouse-core/test/gather/gather-runner-test.js @@ -5,17 +5,16 @@ */ import {strict as assert} from 'assert'; -import {createRequire} from 'module'; import jestMock from 'jest-mock'; -import Gatherer from '../../gather/gatherers/gatherer.js'; +import {Gatherer} from '../../gather/gatherers/gatherer.js'; // import GathererRunner_ from '../../gather/gather-runner.js'; -// import Config from '../../config/config.js'; -import LighthouseError from '../../lib/lh-error.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; -// import Driver from '../../gather/driver.js'; -import Connection from '../../gather/connections/connection.js'; +// import {Config} from '../../config/config.js'; +import {LighthouseError} from '../../lib/lh-error.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; +// import {Driver} from '../../gather/driver.js'; +import {Connection} from '../../gather/connections/connection.js'; import {createMockSendCommandFn, createMockOnceFn} from './mock-commands.js'; import { makeMocksForGatherRunner, @@ -24,14 +23,14 @@ import { flushAllTimersAndMicrotasks, fnAny, timers, - requireMock, + importMock, readJson, } from '../test-utils.js'; -import fakeDriver from './fake-driver.js'; +import {fakeDriver} from './fake-driver.js'; const unresolvedPerfLog = readJson('./../fixtures/unresolved-perflog.json', import.meta); -const require = createRequire(import.meta.url); +await makeMocksForGatherRunner(); /** @type {jestMock.SpyInstance<Promise<void>, [session: any, pageUrl: string]>} */ let assertNoSameOriginServiceWorkerClientsMock; @@ -53,22 +52,21 @@ function createTypeHackedGatherRunner() { // Some imports needs to be done dynamically, so that their dependencies will be mocked. // See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs // https://github.com/facebook/jest/issues/10025 -/** @typedef {import('../../gather/driver.js')} Driver */ -/** @type {typeof import('../../gather/driver.js')} */ +/** @typedef {import('../../gather/driver.js').Driver} Driver */ +/** @type {typeof import('../../gather/driver.js').Driver} */ let Driver; -/** @type {typeof import('../../gather/gather-runner.js')} */ +/** @type {typeof import('../../gather/gather-runner.js').GatherRunner} */ let GatherRunner_; -/** @typedef {import('../../config/config.js')} Config */ -/** @type {typeof import('../../config/config.js')} */ +/** @typedef {import('../../config/config.js').Config} Config */ +/** @type {typeof import('../../config/config.js').Config} */ let Config; /** @type {ReturnType<createTypeHackedGatherRunner>} */ let GatherRunner; before(async () => { - makeMocksForGatherRunner(); - Driver = (await import('../../gather/driver.js')).default; - GatherRunner_ = (await import('../../gather/gather-runner.js')).default; - Config = (await import('../../config/config.js')).default; + Driver = (await import('../../gather/driver.js')).Driver; + GatherRunner_ = (await import('../../gather/gather-runner.js')).GatherRunner; + Config = (await import('../../config/config.js')).Config; assertNoSameOriginServiceWorkerClientsMock = jestMock.spyOn(GatherRunner_, 'assertNoSameOriginServiceWorkerClients'); GatherRunner = createTypeHackedGatherRunner(); @@ -105,7 +103,7 @@ class TestGathererNoArtifact extends Gatherer { afterPass() {} } -/** @type {import('../../gather/driver.js')} */ +/** @type {import('../../gather/driver.js').Driver} */ let driver; /** @type {Connection & {sendCommand: ReturnType<typeof createMockSendCommandFn>}} */ let connectionStub; @@ -133,7 +131,7 @@ function resetDefaultMockResponses() { .mockResponse('ServiceWorker.enable'); } -beforeEach(() => { +beforeEach(async () => { class EmulationDriver extends Driver { registerRequestIdleCallbackWrap() { return Promise.resolve(); @@ -156,17 +154,8 @@ beforeEach(() => { driver = new EmulationDriver(connectionStub); resetDefaultMockResponses(); - const emulation = require('../../lib/emulation.js'); - emulation.emulate = fnAny(); - emulation.throttle = fnAny(); - emulation.clearThrottling = fnAny(); - - const prepare = require('../../gather/driver/prepare.js'); - prepare.prepareTargetForNavigationMode = fnAny(); - prepare.prepareTargetForIndividualNavigation = fnAny().mockResolvedValue({warnings: []}); - - const navigation = requireMock('../../gather/driver/navigation.js', import.meta); - navigation.gotoURL = fnAny().mockResolvedValue({ + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); + gotoURL.mockReset().mockResolvedValue({ mainDocumentUrl: 'https://example.com', timedOut: false, warnings: [], @@ -179,11 +168,11 @@ afterEach(() => { }); describe('GatherRunner', function() { - it('loads a page and updates passContext urls on redirect', () => { + it('loads a page and updates passContext urls on redirect', async () => { const url1 = 'https://example.com'; const url2 = 'https://example.com/interstitial'; const driver = {}; - const {gotoURL} = requireMock('../../gather/driver/navigation.js', import.meta); + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); gotoURL.mockResolvedValue({mainDocumentUrl: url2, warnings: []}); const passContext = { @@ -210,7 +199,7 @@ describe('GatherRunner', function() { const url = 'https://example.com'; const error = new LighthouseError(LighthouseError.errors.NO_FCP); const driver = {}; - const {gotoURL} = requireMock('../../gather/driver/navigation.js', import.meta); + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); gotoURL.mockRejectedValue(error); const passContext = { @@ -258,7 +247,7 @@ describe('GatherRunner', function() { it('collects requested and final URLs as an artifact', async () => { const requestedUrl = 'https://example.com'; const mainDocumentUrl = 'https://example.com/interstitial'; - const {gotoURL} = requireMock('../../gather/driver/navigation.js', import.meta); + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); gotoURL.mockResolvedValue({mainDocumentUrl, timedOut: false, warnings: []}); const config = await makeConfig({passes: [{passName: 'defaultPass'}]}); const options = { @@ -472,7 +461,7 @@ describe('GatherRunner', function() { LighthouseRunWarnings: [], }; - const prepare = requireMock('../../gather/driver/prepare.js', import.meta); + const prepare = await importMock('../../gather/driver/prepare.js', import.meta); await GatherRunner.runPass(passContext); expect(prepare.prepareTargetForIndividualNavigation).toHaveBeenCalled(); }); @@ -524,7 +513,7 @@ describe('GatherRunner', function() { }, }); - const {gotoURL} = requireMock('../../gather/driver/navigation.js', import.meta); + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); gotoURL.mockImplementation( /** @param {any} _ @param {string} url */ (_, url) => url.includes('blank') ? null : Promise.reject(navigationError) @@ -568,7 +557,7 @@ describe('GatherRunner', function() { }, }); - const {gotoURL} = requireMock('../../gather/driver/navigation.js', import.meta); + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); gotoURL.mockImplementation( /** @param {any} _ @param {string} url */ (_, url) => url.includes('blank') ? gotoUrlForAboutBlank() : gotoUrlForRealUrl() @@ -841,7 +830,7 @@ describe('GatherRunner', function() { let firstLoad = true; const driver = Object.assign({}, fakeDriver, {online: true}); - const {gotoURL} = requireMock('../../gather/driver/navigation.js', import.meta); + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); gotoURL.mockImplementation( /** @@ -1254,7 +1243,7 @@ describe('GatherRunner', function() { online: true, }); - const {gotoURL} = requireMock('../../gather/driver/navigation.js', import.meta); + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); gotoURL.mockResolvedValue({mainDocumentUrl: requestedUrl, warnings: ['It is too slow']}); return GatherRunner.run(config.passes, { @@ -1286,7 +1275,7 @@ describe('GatherRunner', function() { online: true, }); - const {gotoURL} = requireMock('../../gather/driver/navigation.js', import.meta); + const {gotoURL} = await importMock('../../gather/driver/navigation.js', import.meta); gotoURL .mockResolvedValueOnce({finalUrl: requestedUrl, warnings: []}) .mockResolvedValueOnce({finalUrl: requestedUrl, warnings: ['It is too slow']}); diff --git a/lighthouse-core/test/gather/gatherers/accessibility-test.js b/lighthouse-core/test/gather/gatherers/accessibility-test.js index 7f94faee83d5..1a54fa35eabc 100644 --- a/lighthouse-core/test/gather/gatherers/accessibility-test.js +++ b/lighthouse-core/test/gather/gatherers/accessibility-test.js @@ -11,8 +11,8 @@ import puppeteer from 'puppeteer'; import AccessibilityGather from '../../../gather/gatherers/accessibility.js'; import {LH_ROOT} from '../../../../root.js'; -import axeLib from '../../../../lighthouse-core/lib/axe.js'; -import pageFunctions from '../../../../lighthouse-core/lib/page-functions.js'; +import {axeSource} from '../../../../lighthouse-core/lib/axe.js'; +import {pageFunctions} from '../../../../lighthouse-core/lib/page-functions.js'; describe('Accessibility gatherer', () => { let accessibilityGather; @@ -51,7 +51,7 @@ describe('a11y audits + aXe', () => { it('only runs the axe rules we have audits defined for', async () => { const page = await browser.newPage(); page.setContent(`<!doctype html><meta charset="utf8"><title>hivalid.`); - await page.evaluate(axeLib.source); + await page.evaluate(axeSource); await page.evaluate(pageFunctions.getNodeDetailsString); await page.evaluate(AccessibilityGather.pageFns.runA11yChecks.toString()); await page.evaluate(AccessibilityGather.pageFns.createAxeRuleResultArtifact.toString()); diff --git a/lighthouse-core/test/gather/gatherers/dobetterweb/response-compression-test.js b/lighthouse-core/test/gather/gatherers/dobetterweb/response-compression-test.js index fcefe4a77827..b36b8a2f2c85 100644 --- a/lighthouse-core/test/gather/gatherers/dobetterweb/response-compression-test.js +++ b/lighthouse-core/test/gather/gatherers/dobetterweb/response-compression-test.js @@ -19,7 +19,7 @@ before(async () => { (await import('../../../../gather/gatherers/dobetterweb/response-compression.js')).default; }); -const mocks = mockDriverSubmodules(); +const mocks = await mockDriverSubmodules(); const networkRecords = [ { diff --git a/lighthouse-core/test/gather/gatherers/gatherer-test.js b/lighthouse-core/test/gather/gatherers/gatherer-test.js index dd50c7f672bb..0e0649e7d882 100644 --- a/lighthouse-core/test/gather/gatherers/gatherer-test.js +++ b/lighthouse-core/test/gather/gatherers/gatherer-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import Gatherer from '../../../gather/gatherers/gatherer.js'; +import {Gatherer} from '../../../gather/gatherers/gatherer.js'; describe('Gatherer', () => { it('returns its name', () => { diff --git a/lighthouse-core/test/gather/gatherers/global-listeners-test.js b/lighthouse-core/test/gather/gatherers/global-listeners-test.js index 0396e4489a44..b4e72ea156c8 100644 --- a/lighthouse-core/test/gather/gatherers/global-listeners-test.js +++ b/lighthouse-core/test/gather/gatherers/global-listeners-test.js @@ -6,8 +6,8 @@ import GlobalListenerGatherer from '../../../gather/gatherers/global-listeners.js'; import {createMockSendCommandFn} from '../mock-commands.js'; -import Connection from '../../../gather/connections/connection.js'; -import Driver from '../../../gather/driver.js'; +import {Connection} from '../../../gather/connections/connection.js'; +import {Driver} from '../../../gather/driver.js'; describe('Global Listener Gatherer', () => { it('remove duplicate listeners from artifacts', async () => { diff --git a/lighthouse-core/test/gather/gatherers/image-elements-test.js b/lighthouse-core/test/gather/gatherers/image-elements-test.js index cc7d83a375b5..cd7a160d120d 100644 --- a/lighthouse-core/test/gather/gatherers/image-elements-test.js +++ b/lighthouse-core/test/gather/gatherers/image-elements-test.js @@ -7,7 +7,7 @@ import jestMock from 'jest-mock'; import ImageElements from '../../../gather/gatherers/image-elements.js'; -import NetworkRecorder from '../../../lib/network-recorder.js'; +import {NetworkRecorder} from '../../../lib/network-recorder.js'; import {createMockContext, createMockDriver, createMockSession} from '../../fraggle-rock/gather/mock-driver.js'; import {fnAny, readJson, timers} from '../../test-utils.js'; diff --git a/lighthouse-core/test/gather/gatherers/inspector-issues-test.js b/lighthouse-core/test/gather/gatherers/inspector-issues-test.js index 119ad98398b4..3436008738af 100644 --- a/lighthouse-core/test/gather/gatherers/inspector-issues-test.js +++ b/lighthouse-core/test/gather/gatherers/inspector-issues-test.js @@ -5,10 +5,10 @@ */ import InspectorIssues from '../../../gather/gatherers/inspector-issues.js'; -import NetworkRequest from '../../../lib/network-request.js'; +import {NetworkRequest} from '../../../lib/network-request.js'; import {createMockContext} from '../../fraggle-rock/gather/mock-driver.js'; import {flushAllTimersAndMicrotasks, timers} from '../../test-utils.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; timers.useFakeTimers(); diff --git a/lighthouse-core/test/gather/gatherers/js-usage-test.js b/lighthouse-core/test/gather/gatherers/js-usage-test.js index da585a3b39e4..2c061654db3f 100644 --- a/lighthouse-core/test/gather/gatherers/js-usage-test.js +++ b/lighthouse-core/test/gather/gatherers/js-usage-test.js @@ -4,8 +4,8 @@ * 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. */ -import Driver from '../../../gather/driver.js'; -import Connection from '../../../gather/connections/connection.js'; +import {Driver} from '../../../gather/driver.js'; +import {Connection} from '../../../gather/connections/connection.js'; import JsUsage from '../../../gather/gatherers/js-usage.js'; import {createMockSendCommandFn, createMockOnFn} from '../mock-commands.js'; import {createMockContext} from '../../fraggle-rock/gather/mock-driver.js'; diff --git a/lighthouse-core/test/gather/gatherers/link-elements-test.js b/lighthouse-core/test/gather/gatherers/link-elements-test.js index 57fc3967d931..737ddb23ad74 100644 --- a/lighthouse-core/test/gather/gatherers/link-elements-test.js +++ b/lighthouse-core/test/gather/gatherers/link-elements-test.js @@ -10,8 +10,8 @@ import * as td from 'testdouble'; // Some imports needs to be done dynamically, so that their dependencies will be mocked. // See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs // https://github.com/facebook/jest/issues/10025 -/** @typedef {import('../../../gather/gatherers/link-elements.js')} LinkElements */ -/** @type {typeof import('../../../gather/gatherers/link-elements.js')} */ +/** @typedef {import('../../../gather/gatherers/link-elements.js').default} LinkElements */ +/** @type {typeof import('../../../gather/gatherers/link-elements.js').default} */ let LinkElements; before(async () => { @@ -19,7 +19,7 @@ before(async () => { }); const mockMainResource = jestMock.fn(); -td.replace('../../../computed/main-resource.js', {request: mockMainResource}); +await td.replaceEsm('../../../computed/main-resource.js', undefined, {request: mockMainResource}); beforeEach(() => { mockMainResource.mockReset(); diff --git a/lighthouse-core/test/gather/gatherers/main-document-content-test.js b/lighthouse-core/test/gather/gatherers/main-document-content-test.js index a88de740742c..b65814978512 100644 --- a/lighthouse-core/test/gather/gatherers/main-document-content-test.js +++ b/lighthouse-core/test/gather/gatherers/main-document-content-test.js @@ -5,7 +5,7 @@ */ import MainDocumentContent from '../../../gather/gatherers/main-document-content.js'; -import NetworkRecorder from '../../../lib/network-recorder.js'; +import {NetworkRecorder} from '../../../lib/network-recorder.js'; import {createMockContext} from '../../fraggle-rock/gather/mock-driver.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../../test-utils.js'; diff --git a/lighthouse-core/test/gather/gatherers/script-elements-test.js b/lighthouse-core/test/gather/gatherers/script-elements-test.js index 924dc6c6d9f9..324b51f6f23a 100644 --- a/lighthouse-core/test/gather/gatherers/script-elements-test.js +++ b/lighthouse-core/test/gather/gatherers/script-elements-test.js @@ -6,20 +6,20 @@ import {createMockContext, mockDriverSubmodules} from '../../fraggle-rock/gather/mock-driver.js'; // import ScriptElements from '../../../gather/gatherers/script-elements.js'; -import NetworkRequest from '../../../lib/network-request.js'; +import {NetworkRequest} from '../../../lib/network-request.js'; // Some imports needs to be done dynamically, so that their dependencies will be mocked. // See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs // https://github.com/facebook/jest/issues/10025 -/** @typedef {import('../../../gather/gatherers/script-elements.js')} ScriptElements */ -/** @type {typeof import('../../../gather/gatherers/script-elements.js')} */ +/** @typedef {import('../../../gather/gatherers/script-elements.js').default} ScriptElements */ +/** @type {typeof import('../../../gather/gatherers/script-elements.js').default} */ let ScriptElements; before(async () => { ScriptElements = (await import('../../../gather/gatherers/script-elements.js')).default; }); -const mocks = mockDriverSubmodules(); +const mocks = await mockDriverSubmodules(); /** * @param {Partial=} partial diff --git a/lighthouse-core/test/gather/gatherers/seo/font-size-test.js b/lighthouse-core/test/gather/gatherers/seo/font-size-test.js index 9528871e8f11..89dbfec21f98 100644 --- a/lighthouse-core/test/gather/gatherers/seo/font-size-test.js +++ b/lighthouse-core/test/gather/gatherers/seo/font-size-test.js @@ -6,7 +6,9 @@ import assert from 'assert'; -import FontSizeGather from '../../../../gather/gatherers/seo/font-size.js'; +import FontSizeGather, { + computeSelectorSpecificity, getEffectiveFontRule, +} from '../../../../gather/gatherers/seo/font-size.js'; let fontSizeGather; @@ -177,7 +179,7 @@ describe('Font size gatherer', () => { }); describe('#computeSelectorSpecificity', () => { - const compute = FontSizeGather.computeSelectorSpecificity; + const compute = computeSelectorSpecificity; it('should handle basic selectors', () => { expect(compute('h1')).toEqual(1); @@ -265,7 +267,7 @@ describe('Font size gatherer', () => { }); it('should identify inline styles', () => { - const result = FontSizeGather.getEffectiveFontRule({inlineStyle}); + const result = getEffectiveFontRule({inlineStyle}); expect(result).toEqual({ cssProperties: [ { @@ -279,7 +281,7 @@ describe('Font size gatherer', () => { }); it('should identify attributes styles', () => { - const result = FontSizeGather.getEffectiveFontRule({attributesStyle}); + const result = getEffectiveFontRule({attributesStyle}); expect(result).toEqual({ cssProperties: [ { @@ -292,7 +294,7 @@ describe('Font size gatherer', () => { }); it('should identify direct CSS rules', () => { - const result = FontSizeGather.getEffectiveFontRule({matchedCSSRules}); + const result = getEffectiveFontRule({matchedCSSRules}); expect(result).toEqual({ cssProperties: [ { @@ -317,7 +319,7 @@ describe('Font size gatherer', () => { }); it('should identify inherited CSS rules', () => { - const result = FontSizeGather.getEffectiveFontRule({inherited}); + const result = getEffectiveFontRule({inherited}); expect(result).toEqual({ cssProperties: [ { @@ -339,20 +341,20 @@ describe('Font size gatherer', () => { }); it('should respect precendence', () => { - let result = FontSizeGather.getEffectiveFontRule( + let result = getEffectiveFontRule( {attributesStyle, inlineStyle, matchedCSSRules, inherited}); expect(result).toMatchObject({type: 'Inline'}); - result = FontSizeGather.getEffectiveFontRule({attributesStyle, inherited}); + result = getEffectiveFontRule({attributesStyle, inherited}); expect(result).toMatchObject({type: 'Attributes'}); - result = FontSizeGather.getEffectiveFontRule({attributesStyle, matchedCSSRules, inherited}); + result = getEffectiveFontRule({attributesStyle, matchedCSSRules, inherited}); expect(result.parentRule).toMatchObject({origin: 'regular'}); - result = FontSizeGather.getEffectiveFontRule({inherited}); + result = getEffectiveFontRule({inherited}); expect(result.parentRule).toMatchObject({origin: 'user-agent'}); - result = FontSizeGather.getEffectiveFontRule({}); + result = getEffectiveFontRule({}); expect(result).toBe(undefined); }); @@ -384,7 +386,7 @@ describe('Font size gatherer', () => { {rule: fontRuleC, matchingSelectors: [0]}, ]; - const result = FontSizeGather.getEffectiveFontRule({matchedCSSRules}); + const result = getEffectiveFontRule({matchedCSSRules}); // fontRuleB should have one for ID + class expect(result.styleSheetId).toEqual(2); }); @@ -407,7 +409,7 @@ describe('Font size gatherer', () => { {rule: fontRuleB, matchingSelectors: [0]}, ]; - const result = FontSizeGather.getEffectiveFontRule({matchedCSSRules}); + const result = getEffectiveFontRule({matchedCSSRules}); expect(result.styleSheetId).toEqual(2); }); }); diff --git a/lighthouse-core/test/gather/gatherers/service-worker-test.js b/lighthouse-core/test/gather/gatherers/service-worker-test.js index 161dabf6ce83..ac465a29308e 100644 --- a/lighthouse-core/test/gather/gatherers/service-worker-test.js +++ b/lighthouse-core/test/gather/gatherers/service-worker-test.js @@ -15,7 +15,7 @@ import {fnAny} from '../../test-utils.js'; // Some imports needs to be done dynamically, so that their dependencies will be mocked. // See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs // https://github.com/facebook/jest/issues/10025 -/** @type {typeof import('../../../gather/gatherers/service-worker.js')} */ +/** @type {typeof import('../../../gather/gatherers/service-worker.js').default} */ let ServiceWorkerGather; before(async () => { @@ -24,7 +24,8 @@ before(async () => { const getServiceWorkerVersions = fnAny(); const getServiceWorkerRegistrations = fnAny(); -td.replace('../../../gather/driver/service-workers.js', { + +await td.replaceEsm('../../../gather/driver/service-workers.js', { getServiceWorkerVersions, getServiceWorkerRegistrations, }); diff --git a/lighthouse-core/test/gather/gatherers/source-maps-test.js b/lighthouse-core/test/gather/gatherers/source-maps-test.js index 760dd758cb72..5770afa0a4a1 100644 --- a/lighthouse-core/test/gather/gatherers/source-maps-test.js +++ b/lighthouse-core/test/gather/gatherers/source-maps-test.js @@ -5,8 +5,8 @@ */ -import Driver from '../../../gather/driver.js'; -import Connection from '../../../gather/connections/connection.js'; +import {Driver} from '../../../gather/driver.js'; +import {Connection} from '../../../gather/connections/connection.js'; import SourceMaps from '../../../gather/gatherers/source-maps.js'; import {createMockSendCommandFn, createMockOnFn} from '../mock-commands.js'; import {flushAllTimersAndMicrotasks, fnAny, timers} from '../../test-utils.js'; diff --git a/lighthouse-core/test/gather/gatherers/trace-elements-test.js b/lighthouse-core/test/gather/gatherers/trace-elements-test.js index 79355f776653..22e40c1c5824 100644 --- a/lighthouse-core/test/gather/gatherers/trace-elements-test.js +++ b/lighthouse-core/test/gather/gatherers/trace-elements-test.js @@ -5,9 +5,9 @@ */ import TraceElementsGatherer from '../../../gather/gatherers/trace-elements.js'; -import Driver from '../../../gather/driver.js'; -import Connection from '../../../gather/connections/connection.js'; -import createTestTrace from '../../create-test-trace.js'; +import {Driver} from '../../../gather/driver.js'; +import {Connection} from '../../../gather/connections/connection.js'; +import {createTestTrace} from '../../create-test-trace.js'; import {createMockSendCommandFn, createMockOnFn} from '../mock-commands.js'; import {flushAllTimersAndMicrotasks, fnAny, readJson, timers} from '../../test-utils.js'; diff --git a/lighthouse-core/test/index-test.js b/lighthouse-core/test/index-test.js index 0046e3fc5e30..5c609570d352 100644 --- a/lighthouse-core/test/index-test.js +++ b/lighthouse-core/test/index-test.js @@ -6,13 +6,12 @@ import {strict as assert} from 'assert'; -import lighthouse from '../index.js'; +import lighthouse, {getAuditList, legacyNavigation, traceCategories} from '../index.js'; import {LH_ROOT} from '../../root.js'; import {readJson} from './test-utils.js'; const pkg = readJson('package.json'); -const {legacyNavigation} = lighthouse; const TEST_DIR = `${LH_ROOT}/lighthouse-core/test`; describe('Module Tests', function() { @@ -29,11 +28,11 @@ describe('Module Tests', function() { }); it('should return a list of audits', function() { - assert.ok(Array.isArray(lighthouse.getAuditList())); + assert.ok(Array.isArray(getAuditList())); }); it('should return a list of trace categories required by the driver', function() { - const lighthouseTraceCategories = lighthouse.traceCategories; + const lighthouseTraceCategories = traceCategories; assert.ok(Array.isArray(lighthouseTraceCategories)); assert.notEqual(lighthouseTraceCategories.length, 0); }); diff --git a/lighthouse-core/test/lib/arbitrary-equality-map-test.js b/lighthouse-core/test/lib/arbitrary-equality-map-test.js index 0acc50b100c2..f780bf450ce6 100644 --- a/lighthouse-core/test/lib/arbitrary-equality-map-test.js +++ b/lighthouse-core/test/lib/arbitrary-equality-map-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import ArbitraryEqualityMap from '../../lib/arbitrary-equality-map.js'; +import {ArbitraryEqualityMap} from '../../lib/arbitrary-equality-map.js'; import {readJson} from '../test-utils.js'; const trace = readJson('../fixtures/traces/progressive-app-m60.json', import.meta); diff --git a/lighthouse-core/test/lib/asset-saver-test.js b/lighthouse-core/test/lib/asset-saver-test.js index 600700330fdb..b98f4cab9a48 100644 --- a/lighthouse-core/test/lib/asset-saver-test.js +++ b/lighthouse-core/test/lib/asset-saver-test.js @@ -7,12 +7,12 @@ import {strict as assert} from 'assert'; import fs from 'fs'; -import assetSaver from '../../lib/asset-saver.js'; -import Metrics from '../../lib/traces/pwmetrics-events.js'; -import LighthouseError from '../../lib/lh-error.js'; -import Audit from '../../audits/audit.js'; -import {getModuleDirectory} from '../../../esm-utils.mjs'; +import * as assetSaver from '../../lib/asset-saver.js'; +import {Metrics} from '../../lib/traces/pwmetrics-events.js'; +import {LighthouseError} from '../../lib/lh-error.js'; +import {Audit} from '../../audits/audit.js'; import {LH_ROOT} from '../../../root.js'; +import {getModuleDirectory} from '../../../esm-utils.js'; import {readJson} from '../test-utils.js'; const traceEvents = readJson('../fixtures/traces/progressive-app.json', import.meta); diff --git a/lighthouse-core/test/lib/dependency-graph/base-node-test.js b/lighthouse-core/test/lib/dependency-graph/base-node-test.js index 7939ff749d33..03c6ac5dd222 100644 --- a/lighthouse-core/test/lib/dependency-graph/base-node-test.js +++ b/lighthouse-core/test/lib/dependency-graph/base-node-test.js @@ -6,8 +6,8 @@ import {strict as assert} from 'assert'; -import BaseNode from '../../../lib/dependency-graph/base-node.js'; -import NetworkNode from '../../../lib/dependency-graph/network-node.js'; +import {BaseNode} from '../../../lib/dependency-graph/base-node.js'; +import {NetworkNode} from '../../../lib/dependency-graph/network-node.js'; function sortedById(nodeArray) { return nodeArray.sort((node1, node2) => node1.id.localeCompare(node2.id)); diff --git a/lighthouse-core/test/lib/dependency-graph/simulator/connection-pool-test.js b/lighthouse-core/test/lib/dependency-graph/simulator/connection-pool-test.js index 18468184ca0c..84d1d2de40e1 100644 --- a/lighthouse-core/test/lib/dependency-graph/simulator/connection-pool-test.js +++ b/lighthouse-core/test/lib/dependency-graph/simulator/connection-pool-test.js @@ -7,7 +7,7 @@ import {strict as assert} from 'assert'; import {URL} from 'url'; -import ConnectionPool from '../../../../lib/dependency-graph/simulator/connection-pool.js'; +import {ConnectionPool} from '../../../../lib/dependency-graph/simulator/connection-pool.js'; describe('DependencyGraph/Simulator/ConnectionPool', () => { const rtt = 100; diff --git a/lighthouse-core/test/lib/dependency-graph/simulator/dns-cache-test.js b/lighthouse-core/test/lib/dependency-graph/simulator/dns-cache-test.js index 9f5b515d7b81..bbfbec7f4a16 100644 --- a/lighthouse-core/test/lib/dependency-graph/simulator/dns-cache-test.js +++ b/lighthouse-core/test/lib/dependency-graph/simulator/dns-cache-test.js @@ -4,7 +4,7 @@ * 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. */ -import DNSCache from '../../../../lib/dependency-graph/simulator/dns-cache.js'; +import {DNSCache} from '../../../../lib/dependency-graph/simulator/dns-cache.js'; const MULTIPLIER = DNSCache.RTT_MULTIPLIER; diff --git a/lighthouse-core/test/lib/dependency-graph/simulator/network-analyzer-test.js b/lighthouse-core/test/lib/dependency-graph/simulator/network-analyzer-test.js index 0ac565cb8d3c..722e934c2f09 100644 --- a/lighthouse-core/test/lib/dependency-graph/simulator/network-analyzer-test.js +++ b/lighthouse-core/test/lib/dependency-graph/simulator/network-analyzer-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import NetworkAnalyzer from '../../../../lib/dependency-graph/simulator/network-analyzer.js'; +import {NetworkAnalyzer} from '../../../../lib/dependency-graph/simulator/network-analyzer.js'; import NetworkRecords from '../../../../computed/network-records.js'; import {readJson} from '../../../test-utils.js'; diff --git a/lighthouse-core/test/lib/dependency-graph/simulator/simulator-test.js b/lighthouse-core/test/lib/dependency-graph/simulator/simulator-test.js index 7ecf1dccd915..544977b2a350 100644 --- a/lighthouse-core/test/lib/dependency-graph/simulator/simulator-test.js +++ b/lighthouse-core/test/lib/dependency-graph/simulator/simulator-test.js @@ -6,10 +6,10 @@ import {strict as assert} from 'assert'; -import NetworkNode from '../../../../lib/dependency-graph/network-node.js'; -import CpuNode from '../../../../lib/dependency-graph/cpu-node.js'; -import Simulator from '../../../../lib/dependency-graph/simulator/simulator.js'; -import DNSCache from '../../../../lib/dependency-graph/simulator/dns-cache.js'; +import {NetworkNode} from '../../../../lib/dependency-graph/network-node.js'; +import {CPUNode} from '../../../../lib/dependency-graph/cpu-node.js'; +import {Simulator} from '../../../../lib/dependency-graph/simulator/simulator.js'; +import {DNSCache} from '../../../../lib/dependency-graph/simulator/dns-cache.js'; import PageDependencyGraph from '../../../../computed/page-dependency-graph.js'; import {getURLArtifactFromDevtoolsLog, readJson} from '../../../test-utils.js'; @@ -74,7 +74,7 @@ describe('DependencyGraph/Simulator', () => { it('should simulate basic mixed graphs', () => { const rootNode = new NetworkNode(request({})); - const cpuNode = new CpuNode(cpuTask({duration: 200})); + const cpuNode = new CPUNode(cpuTask({duration: 200})); cpuNode.addDependency(rootNode); const simulator = new Simulator({ @@ -141,9 +141,9 @@ describe('DependencyGraph/Simulator', () => { it('should simulate basic CPU queue graphs', () => { const nodeA = new NetworkNode(request({})); - const nodeB = new CpuNode(cpuTask({duration: 100})); - const nodeC = new CpuNode(cpuTask({duration: 600})); - const nodeD = new CpuNode(cpuTask({duration: 300})); + const nodeB = new CPUNode(cpuTask({duration: 100})); + const nodeC = new CPUNode(cpuTask({duration: 600})); + const nodeD = new CPUNode(cpuTask({duration: 300})); nodeA.addDependent(nodeB); nodeA.addDependent(nodeC); @@ -167,8 +167,8 @@ describe('DependencyGraph/Simulator', () => { const nodeB = new NetworkNode(request({})); const nodeC = new NetworkNode(request({})); const nodeD = new NetworkNode(request({})); - const nodeE = new CpuNode(cpuTask({duration: 1000})); - const nodeF = new CpuNode(cpuTask({duration: 1000})); + const nodeE = new CPUNode(cpuTask({duration: 1000})); + const nodeF = new CPUNode(cpuTask({duration: 1000})); nodeA.addDependent(nodeB); nodeB.addDependent(nodeC); diff --git a/lighthouse-core/test/lib/dependency-graph/simulator/tcp-connection-test.js b/lighthouse-core/test/lib/dependency-graph/simulator/tcp-connection-test.js index 4531f42374ef..e7318f323e8f 100644 --- a/lighthouse-core/test/lib/dependency-graph/simulator/tcp-connection-test.js +++ b/lighthouse-core/test/lib/dependency-graph/simulator/tcp-connection-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import TcpConnection from '../../../../lib/dependency-graph/simulator/tcp-connection.js'; +import {TcpConnection} from '../../../../lib/dependency-graph/simulator/tcp-connection.js'; describe('DependencyGraph/Simulator/TcpConnection', () => { describe('#constructor', () => { diff --git a/lighthouse-core/test/lib/emulation-test.js b/lighthouse-core/test/lib/emulation-test.js index b6443cdcd09e..dd7c04d8d7dc 100644 --- a/lighthouse-core/test/lib/emulation-test.js +++ b/lighthouse-core/test/lib/emulation-test.js @@ -4,10 +4,10 @@ * 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. */ -import emulation from '../../lib/emulation.js'; -import Driver from '../../gather/driver.js'; -import constants from '../../config/constants.js'; -import Connection from '../../gather/connections/connection.js'; +import * as emulation from '../../lib/emulation.js'; +import {Driver} from '../../gather/driver.js'; +import * as constants from '../../config/constants.js'; +import {Connection} from '../../gather/connections/connection.js'; import {createMockSendCommandFn} from '../gather/mock-commands.js'; describe('emulation', () => { diff --git a/lighthouse-core/test/lib/i18n/i18n-test.js b/lighthouse-core/test/lib/i18n/i18n-test.js index af19b5e61824..607fb10c1d71 100644 --- a/lighthouse-core/test/lib/i18n/i18n-test.js +++ b/lighthouse-core/test/lib/i18n/i18n-test.js @@ -9,8 +9,8 @@ import path from 'path'; import log from 'lighthouse-logger'; import jestMock from 'jest-mock'; -import i18n from '../../../lib/i18n/i18n.js'; -import {getModuleDirectory} from '../../../../esm-utils.mjs'; +import * as i18n from '../../../lib/i18n/i18n.js'; +import {getModuleDirectory} from '../../../../esm-utils.js'; const moduleDir = getModuleDirectory(import.meta); diff --git a/lighthouse-core/test/lib/icons-test.js b/lighthouse-core/test/lib/icons-test.js index 09f28ac5b7cc..52e94adc0e0a 100644 --- a/lighthouse-core/test/lib/icons-test.js +++ b/lighthouse-core/test/lib/icons-test.js @@ -6,8 +6,8 @@ import {strict as assert} from 'assert'; -import icons from '../../lib/icons.js'; -import manifestParser from '../../lib/manifest-parser.js'; +import * as icons from '../../lib/icons.js'; +import {parseManifest} from '../../lib/manifest-parser.js'; const EXAMPLE_MANIFEST_URL = 'https://example.com/manifest.json'; const EXAMPLE_DOC_URL = 'https://example.com/index.html'; @@ -22,7 +22,7 @@ describe('Icons helper', () => { const manifestSrc = JSON.stringify({ name: 'NoIconsHere', }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.doExist(manifest.value), false); }); @@ -31,7 +31,7 @@ describe('Icons helper', () => { const manifestSrc = JSON.stringify({ icons: [], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.doExist(manifest.value), false); }); @@ -41,7 +41,7 @@ describe('Icons helper', () => { src: 'icon.png', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.doExist(manifest.value), true); }); }); @@ -54,7 +54,7 @@ describe('Icons helper', () => { sizes: '192x192', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); // /* manifest looks like this: */ // { // icons: { @@ -78,7 +78,7 @@ describe('Icons helper', () => { src: 'icon-no-size.png', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 0); }); @@ -89,7 +89,7 @@ describe('Icons helper', () => { sizes: '192x192', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(144, manifest.value).length, 1); }); @@ -100,7 +100,7 @@ describe('Icons helper', () => { sizes: '192x192', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(256, manifest.value).length, 0); }); @@ -111,7 +111,7 @@ describe('Icons helper', () => { sizes: '72x72 96x96 128x128 256x256', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -124,7 +124,7 @@ describe('Icons helper', () => { sizes: '256x256', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -136,7 +136,7 @@ describe('Icons helper', () => { sizes: '200x220', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 0); }); @@ -147,7 +147,7 @@ describe('Icons helper', () => { sizes: 'any', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 0); }); @@ -158,7 +158,7 @@ describe('Icons helper', () => { sizes: '256x256', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 0); }); @@ -177,7 +177,7 @@ describe('Icons helper', () => { sizes: '256x256', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 0); }); @@ -196,7 +196,7 @@ describe('Icons helper', () => { sizes: '100x100', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -207,7 +207,7 @@ describe('Icons helper', () => { sizes: '200x200', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -218,7 +218,7 @@ describe('Icons helper', () => { sizes: '200x200', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -229,7 +229,7 @@ describe('Icons helper', () => { sizes: '200x200', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -241,7 +241,7 @@ describe('Icons helper', () => { type: 'image/png', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -262,7 +262,7 @@ describe('Icons helper', () => { sizes: '200x200', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -274,7 +274,7 @@ describe('Icons helper', () => { type: 'image/jpg', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 0); }); @@ -286,7 +286,7 @@ describe('Icons helper', () => { type: 'image/png', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -300,7 +300,7 @@ describe('Icons helper', () => { type: 'image/png', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -312,7 +312,7 @@ describe('Icons helper', () => { type: 'image/png', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); @@ -324,7 +324,7 @@ describe('Icons helper', () => { type: 'image/png', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.pngSizedAtLeast(192, manifest.value).length, 1); }); }); @@ -343,7 +343,7 @@ describe('Icons helper', () => { purpose: 'maskable', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.containsMaskableIcon(manifest.value), true); }); @@ -360,7 +360,7 @@ describe('Icons helper', () => { purpose: 'maskable', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.containsMaskableIcon(manifest.value), true); }); @@ -377,7 +377,7 @@ describe('Icons helper', () => { purpose: 'any', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.containsMaskableIcon(manifest.value), true); }); @@ -393,7 +393,7 @@ describe('Icons helper', () => { sizes: '100x100', }], }); - const manifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const manifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); assert.equal(icons.containsMaskableIcon(manifest.value), false); }); }); diff --git a/lighthouse-core/test/lib/manifest-parser-test.js b/lighthouse-core/test/lib/manifest-parser-test.js index 2d221cc1f64a..9856ac0fc278 100644 --- a/lighthouse-core/test/lib/manifest-parser-test.js +++ b/lighthouse-core/test/lib/manifest-parser-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import manifestParser from '../../lib/manifest-parser.js'; +import {parseManifest} from '../../lib/manifest-parser.js'; import {readJson} from '../test-utils.js'; const manifestStub = readJson('../fixtures/manifest.json', import.meta); @@ -22,7 +22,7 @@ const EXAMPLE_MANIFEST_BLOB_URL = 'blob:https://example.com/manifest.json'; * @return {!ManifestNode<(!Manifest|undefined)>} */ function noUrlManifestParser(manifestSrc) { - return manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + return parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); } describe('Manifest Parser', function() { @@ -49,13 +49,13 @@ describe('Manifest Parser', function() { }); it('should warn on invalid manifest parser URL', function() { - const parsedManifest = manifestParser('{}', 'not a URL', EXAMPLE_DOC_URL); + const parsedManifest = parseManifest('{}', 'not a URL', EXAMPLE_DOC_URL); expect(parsedManifest.warning) .toEqual('ERROR: invalid manifest URL: \'not a URL\''); }); it('should warn on valid but non-(HTTP|HTTPS) manifest parser URL', function() { - const parsedManifest = manifestParser('{}', EXAMPLE_MANIFEST_BLOB_URL, EXAMPLE_DOC_URL); + const parsedManifest = parseManifest('{}', EXAMPLE_MANIFEST_BLOB_URL, EXAMPLE_DOC_URL); expect(parsedManifest.warning) .toEqual('WARNING: manifest URL not available over a valid network protocol'); }); @@ -63,7 +63,7 @@ describe('Manifest Parser', function() { describe('icon parsing', function() { // 9.7 it('gives an empty array and an error for erroneous icons entry', () => { - const parsedManifest = manifestParser( + const parsedManifest = parseManifest( '{"icons": {"16": "img/icons/icon16.png"}}', EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL @@ -77,7 +77,7 @@ describe('Manifest Parser', function() { }); it('gives an empty array and no error for missing icons entry', () => { - const parsedManifest = manifestParser('{}', EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const parsedManifest = parseManifest('{}', EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); expect(parsedManifest.warning).toBeUndefined(); const icons = parsedManifest.value.icons; assert.ok(Array.isArray(icons.value)); @@ -86,7 +86,7 @@ describe('Manifest Parser', function() { }); it('parses basic string', function() { - const parsedManifest = manifestParser( + const parsedManifest = parseManifest( '{"icons": [{"src": "192.png", "sizes": "192x192"}]}', EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL @@ -100,7 +100,7 @@ describe('Manifest Parser', function() { }); it('finds four icons in the stub manifest', function() { - const parsedManifest = manifestParser( + const parsedManifest = parseManifest( JSON.stringify(manifestStub), EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL @@ -111,7 +111,7 @@ describe('Manifest Parser', function() { it('parses icons with extra whitespace', function() { const manifest = '{"icons": [{"src": "192.png", "sizes": " 192x192 256x256"}]}'; - const parsedManifest = manifestParser(manifest, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const parsedManifest = parseManifest(manifest, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); const icons = parsedManifest.value.icons; const icon192 = icons.value[0]; const icon192Sizes = icon192.value.sizes.value; @@ -127,7 +127,7 @@ describe('Manifest Parser', function() { src: 17, }], }); - const parsedManifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const parsedManifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); const icons = parsedManifest.value.icons; assert.equal(icons.value.length, 0); }); @@ -138,7 +138,7 @@ describe('Manifest Parser', function() { src: '/valid/path', }], }); - const parsedManifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_BLOB_URL, + const parsedManifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_BLOB_URL, EXAMPLE_DOC_URL); const icons = parsedManifest.value.icons; expect(icons.value).toHaveLength(0); @@ -151,7 +151,7 @@ describe('Manifest Parser', function() { src: '', }, {}], }); - const parsedManifest = manifestParser(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); + const parsedManifest = parseManifest(manifestSrc, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); const icons = parsedManifest.value.icons; assert.equal(icons.value.length, 0); }); @@ -163,7 +163,7 @@ describe('Manifest Parser', function() { }], }); const manifestUrl = 'https://example.com/resources/manifest.webmanifest'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, EXAMPLE_DOC_URL); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, EXAMPLE_DOC_URL); const icons = parsedManifest.value.icons; assert.equal(icons.value.length, 1); const icon = icons.value[0].value; @@ -232,7 +232,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/manifest.json'; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(parsedUrl.warning); assert.equal(parsedUrl.value, docUrl); @@ -245,7 +245,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/manifest.json'; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(parsedUrl.warning); assert.equal(parsedUrl.value, docUrl); @@ -258,7 +258,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/manifest.json'; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(parsedUrl.warning); assert.equal(parsedUrl.value, docUrl); @@ -269,7 +269,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/manifest.json'; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(!parsedUrl.warning); assert.equal(parsedUrl.value, docUrl); @@ -284,7 +284,7 @@ describe('Manifest Parser', function() { const manifestUrl = ''; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(parsedUrl.warning); assert.equal(parsedUrl.value, docUrl); @@ -298,7 +298,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/manifest.json'; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(parsedUrl.warning); assert.equal(parsedUrl.value, docUrl); @@ -311,7 +311,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/manifest.json'; const docUrl = 'https://example.com:8080/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(parsedUrl.warning); assert.equal(parsedUrl.value, docUrl); @@ -324,7 +324,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/manifest.json'; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(parsedUrl.warning); assert.equal(parsedUrl.value, docUrl); @@ -337,7 +337,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/manifest.json'; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(!parsedUrl.warning); assert.equal(parsedUrl.value, 'https://example.com/'); @@ -351,7 +351,7 @@ describe('Manifest Parser', function() { const manifestUrl = 'https://example.com/resources/manifest.webmanifest'; const docUrl = 'https://example.com/index.html'; - const parsedManifest = manifestParser(manifestSrc, manifestUrl, docUrl); + const parsedManifest = parseManifest(manifestSrc, manifestUrl, docUrl); const parsedUrl = parsedManifest.value.start_url; assert.ok(!parsedUrl.warning); assert.equal(parsedUrl.value, 'https://example.com/start_point.html'); @@ -455,7 +455,7 @@ describe('Manifest Parser', function() { }; /* eslint-enable camelcase */ - const parsedManifest = manifestParser(JSON.stringify(exampleManifest), EXAMPLE_MANIFEST_URL, + const parsedManifest = parseManifest(JSON.stringify(exampleManifest), EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); const applications = parsedManifest.value.related_applications.value; assert.equal(applications.length, 2); @@ -479,7 +479,7 @@ describe('Manifest Parser', function() { }; /* eslint-enable camelcase */ - const parsedManifest = manifestParser(JSON.stringify(exampleManifest), EXAMPLE_MANIFEST_URL, + const parsedManifest = parseManifest(JSON.stringify(exampleManifest), EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); const applications = parsedManifest.value.related_applications.value; // First entry's url should be discarded but entry preserved due to valid id. @@ -497,7 +497,7 @@ describe('Manifest Parser', function() { * @param {string} themeColor */ function getParsedManifest(backgroundColor, themeColor) { - return manifestParser(`{ + return parseManifest(`{ "background_color": "${backgroundColor}", "theme_color": "${themeColor}" }`, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL); @@ -567,7 +567,7 @@ describe('Manifest Parser', function() { it('warns when colors are not strings', () => { const bgColor = 15; const themeColor = false; - const parsedManifest = manifestParser(`{ + const parsedManifest = parseManifest(`{ "background_color": ${bgColor}, "theme_color": ${themeColor} }`, EXAMPLE_MANIFEST_URL, EXAMPLE_DOC_URL).value; diff --git a/lighthouse-core/test/lib/navigation-error-test.js b/lighthouse-core/test/lib/navigation-error-test.js index cc3e2473e81f..e727dc9b5d92 100644 --- a/lighthouse-core/test/lib/navigation-error-test.js +++ b/lighthouse-core/test/lib/navigation-error-test.js @@ -10,7 +10,7 @@ import { getPageLoadError, getNonHtmlError, } from '../../lib/navigation-error.js'; -import NetworkRequest from '../../lib/network-request.js'; +import {NetworkRequest} from '../../lib/network-request.js'; const LoadFailureMode = /** @type {const} */ ({ fatal: 'fatal', diff --git a/lighthouse-core/test/lib/network-recorder-test.js b/lighthouse-core/test/lib/network-recorder-test.js index 0285791ddd4e..8e5436d8fe3e 100644 --- a/lighthouse-core/test/lib/network-recorder-test.js +++ b/lighthouse-core/test/lib/network-recorder-test.js @@ -6,8 +6,8 @@ import {strict as assert} from 'assert'; -import NetworkRecorder from '../../lib/network-recorder.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {NetworkRecorder} from '../../lib/network-recorder.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; import {readJson} from '../test-utils.js'; const devtoolsLogItems = readJson('../fixtures/artifacts/perflog/defaultPass.devtoolslog.json', import.meta); diff --git a/lighthouse-core/test/lib/network-request-test.js b/lighthouse-core/test/lib/network-request-test.js index a307a1f52320..ab5514b0e4ee 100644 --- a/lighthouse-core/test/lib/network-request-test.js +++ b/lighthouse-core/test/lib/network-request-test.js @@ -4,9 +4,9 @@ * 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. */ -import NetworkRequest from '../../lib/network-request.js'; -import NetworkRecorder from '../../lib/network-recorder.js'; -import networkRecordsToDevtoolsLog from '../network-records-to-devtools-log.js'; +import {NetworkRequest} from '../../lib/network-request.js'; +import {NetworkRecorder} from '../../lib/network-recorder.js'; +import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js'; describe('NetworkRequest', () => { afterEach(() => { diff --git a/lighthouse-core/test/lib/page-functions-test.js b/lighthouse-core/test/lib/page-functions-test.js index afb8de9f3454..47001b217a68 100644 --- a/lighthouse-core/test/lib/page-functions-test.js +++ b/lighthouse-core/test/lib/page-functions-test.js @@ -8,7 +8,7 @@ import assert from 'assert'; import jsdom from 'jsdom'; -import pageFunctions from '../../lib/page-functions.js'; +import {pageFunctions} from '../../lib/page-functions.js'; /* global document */ diff --git a/lighthouse-core/test/lib/sentry-test.js b/lighthouse-core/test/lib/sentry-test.js index a5f56b7d25c5..5c04288072e4 100644 --- a/lighthouse-core/test/lib/sentry-test.js +++ b/lighthouse-core/test/lib/sentry-test.js @@ -7,22 +7,25 @@ import jestMock from 'jest-mock'; import * as td from 'testdouble'; -// import sentryNode from '@sentry/node'; -import Sentry from '../../lib/sentry.js'; - -td.replace('@sentry/node', jestMock.fn()); - -// Must mock sentry it is imported. -let sentryNode; -before(async () => { - sentryNode = (await import('@sentry/node')).default; -}); +import {Sentry} from '../../lib/sentry.js'; describe('Sentry', () => { + let sentryNodeMock; let configPayload; let originalSentry; - beforeEach(() => { + beforeEach(async () => { + await td.replaceEsm('@sentry/node', (sentryNodeMock = { + init: jestMock.fn().mockReturnValue({install: jestMock.fn()}), + setExtras: jestMock.fn(), + captureException: jestMock.fn(), + withScope: (fn) => fn({ + setLevel: () => {}, + setTags: () => {}, + setExtras: () => {}, + }), + })); + configPayload = { url: 'http://example.com', flags: {enableErrorReporting: true}, @@ -33,14 +36,6 @@ describe('Sentry', () => { // We want to have a fresh state for every test. originalSentry = {...Sentry}; - sentryNode.init = jestMock.fn().mockReturnValue({install: jestMock.fn()}); - sentryNode.setExtras = jestMock.fn(); - sentryNode.captureException = jestMock.fn(); - sentryNode.withScope = (fn) => fn({ - setLevel: () => {}, - setTags: () => {}, - setExtras: () => {}, - }); Sentry._shouldSample = jestMock.fn().mockReturnValue(true); }); @@ -50,21 +45,21 @@ describe('Sentry', () => { }); describe('.init', () => { - it('should noop when !enableErrorReporting', () => { - Sentry.init({url: 'http://example.com', flags: {}}); - expect(sentryNode.init).not.toHaveBeenCalled(); - Sentry.init({url: 'http://example.com', flags: {enableErrorReporting: false}}); - expect(sentryNode.init).not.toHaveBeenCalled(); + it('should noop when !enableErrorReporting', async () => { + await Sentry.init({url: 'http://example.com', flags: {}}); + expect(sentryNodeMock.init).not.toHaveBeenCalled(); + await Sentry.init({url: 'http://example.com', flags: {enableErrorReporting: false}}); + expect(sentryNodeMock.init).not.toHaveBeenCalled(); }); - it('should noop when not picked for sampling', () => { + it('should noop when not picked for sampling', async () => { Sentry._shouldSample.mockReturnValue(false); - Sentry.init({url: 'http://example.com', flags: {enableErrorReporting: true}}); - expect(sentryNode.init).not.toHaveBeenCalled(); + await Sentry.init({url: 'http://example.com', flags: {enableErrorReporting: true}}); + expect(sentryNodeMock.init).not.toHaveBeenCalled(); }); - it('should initialize the Sentry client when enableErrorReporting', () => { - Sentry.init({ + it('should initialize the Sentry client when enableErrorReporting', async () => { + await Sentry.init({ url: 'http://example.com', flags: { enableErrorReporting: true, @@ -74,9 +69,9 @@ describe('Sentry', () => { environmentData: {}, }); - expect(sentryNode.init).toHaveBeenCalled(); - expect(sentryNode.setExtras).toHaveBeenCalled(); - expect(sentryNode.setExtras.mock.calls[0][0]).toEqual({ + expect(sentryNodeMock.init).toHaveBeenCalled(); + expect(sentryNodeMock.setExtras).toHaveBeenCalled(); + expect(sentryNodeMock.setExtras.mock.calls[0][0]).toEqual({ channel: 'cli', url: 'http://example.com', formFactor: 'desktop', @@ -87,49 +82,49 @@ describe('Sentry', () => { describe('.captureException', () => { it('should forward exceptions to Sentry client', async () => { - Sentry.init(configPayload); + await Sentry.init(configPayload); const error = new Error('oops'); await Sentry.captureException(error); - expect(sentryNode.captureException).toHaveBeenCalled(); - expect(sentryNode.captureException.mock.calls[0][0]).toBe(error); + expect(sentryNodeMock.captureException).toHaveBeenCalled(); + expect(sentryNodeMock.captureException.mock.calls[0][0]).toBe(error); }); it('should skip expected errors', async () => { - Sentry.init(configPayload); + await Sentry.init(configPayload); const error = new Error('oops'); error.expected = true; await Sentry.captureException(error); - expect(sentryNode.captureException).not.toHaveBeenCalled(); + expect(sentryNodeMock.captureException).not.toHaveBeenCalled(); }); it('should skip duplicate audit errors', async () => { - Sentry.init(configPayload); + await Sentry.init(configPayload); const error = new Error('A'); await Sentry.captureException(error, {tags: {audit: 'my-audit'}}); await Sentry.captureException(error, {tags: {audit: 'my-audit'}}); - expect(sentryNode.captureException).toHaveBeenCalledTimes(1); + expect(sentryNodeMock.captureException).toHaveBeenCalledTimes(1); }); it('should still allow different audit errors', async () => { - Sentry.init(configPayload); + await Sentry.init(configPayload); const errorA = new Error('A'); const errorB = new Error('B'); await Sentry.captureException(errorA, {tags: {audit: 'my-audit'}}); await Sentry.captureException(errorB, {tags: {audit: 'my-audit'}}); - expect(sentryNode.captureException).toHaveBeenCalledTimes(2); + expect(sentryNodeMock.captureException).toHaveBeenCalledTimes(2); }); it('should skip duplicate gatherer errors', async () => { - Sentry.init(configPayload); + await Sentry.init(configPayload); const error = new Error('A'); await Sentry.captureException(error, {tags: {gatherer: 'my-gatherer'}}); await Sentry.captureException(error, {tags: {gatherer: 'my-gatherer'}}); - expect(sentryNode.captureException).toHaveBeenCalledTimes(1); + expect(sentryNodeMock.captureException).toHaveBeenCalledTimes(1); }); }); }); diff --git a/lighthouse-core/test/lib/stack-packs-test.js b/lighthouse-core/test/lib/stack-packs-test.js index e39c26f11e89..341843a24730 100644 --- a/lighthouse-core/test/lib/stack-packs-test.js +++ b/lighthouse-core/test/lib/stack-packs-test.js @@ -6,8 +6,8 @@ import lighthouseStackPacksDep from 'lighthouse-stack-packs'; -import stackPacksLib from '../../lib/stack-packs.js'; -import Config from '../../config/config.js'; +import {stackPacksToInclude} from '../../lib/stack-packs.js'; +import {Config} from '../../config/config.js'; async function getAuditIds() { const config = await Config.fromJson(); @@ -17,7 +17,7 @@ async function getAuditIds() { describe('stack-packs lib', () => { it('there are no packs without detectors', () => { const result = lighthouseStackPacksDep - .filter(p => !stackPacksLib.stackPacksToInclude.find(p2 => p2.packId === p.id)) + .filter(p => !stackPacksToInclude.find(p2 => p2.packId === p.id)) .map(p => p.id); expect(result).toEqual([]); }); diff --git a/lighthouse-core/test/lib/statistics-test.js b/lighthouse-core/test/lib/statistics-test.js index deb6bd42dc66..13a80c5516a5 100644 --- a/lighthouse-core/test/lib/statistics-test.js +++ b/lighthouse-core/test/lib/statistics-test.js @@ -4,7 +4,7 @@ * 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. */ -import statistics from '../../lib/statistics.js'; +import * as statistics from '../../lib/statistics.js'; describe('statistics', () => { describe('#getLogNormalScore', () => { diff --git a/lighthouse-core/test/lib/tracehouse/cpu-profile-model-test.js b/lighthouse-core/test/lib/tracehouse/cpu-profile-model-test.js index 83e100721c5d..bbb6756c6e50 100644 --- a/lighthouse-core/test/lib/tracehouse/cpu-profile-model-test.js +++ b/lighthouse-core/test/lib/tracehouse/cpu-profile-model-test.js @@ -4,15 +4,14 @@ * 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. */ -import CpuProfileModel from '../../../lib/tracehouse/cpu-profile-model.js'; -import TraceProcessor from '../../../lib/tracehouse/trace-processor.js'; -import MainThreadTasks from '../../../lib/tracehouse/main-thread-tasks.js'; -import CpuProfilerModel from '../../../lib/tracehouse/cpu-profile-model.js'; +import {CpuProfileModel} from '../../../lib/tracehouse/cpu-profile-model.js'; +import {TraceProcessor} from '../../../lib/tracehouse/trace-processor.js'; +import {MainThreadTasks} from '../../../lib/tracehouse/main-thread-tasks.js'; import {readJson} from '../../test-utils.js'; const profilerTrace = readJson('../../fixtures/traces/cpu-profiler-m86.trace.json', import.meta); -describe('CPU Profiler Model', () => { +describe('CPU Profile Model', () => { /** @type {LH.TraceCpuProfile} */ let profile; @@ -44,7 +43,7 @@ describe('CPU Profiler Model', () => { }); describe('#_findEffectiveTimestamp', () => { - const findTimestamp = CpuProfilerModel._findEffectiveTimestamp.bind(CpuProfilerModel); + const findTimestamp = CpuProfileModel._findEffectiveTimestamp.bind(CpuProfileModel); let defaultData; function createTask(startProfilerRange, endProfilerRange) { @@ -199,7 +198,7 @@ describe('CPU Profiler Model', () => { describe('#synthesizeTraceEvents', () => { it('should create events in order', () => { const ts = x => profile.startTime + x; - const events = CpuProfilerModel.synthesizeTraceEvents(profile); + const events = CpuProfileModel.synthesizeTraceEvents(profile); expect(events).toMatchObject([ {ph: 'B', ts: ts(10e3), args: {data: {callFrame: {functionName: '(root)'}}}}, @@ -233,7 +232,7 @@ describe('CPU Profiler Model', () => { {startTime: 15.7, endTime: 16.8}, ]; - const events = CpuProfilerModel.synthesizeTraceEvents(profile, tasks); + const events = CpuProfileModel.synthesizeTraceEvents(profile, tasks); expect(events).toMatchObject([ {ph: 'B', ts: ts(8.0e3), args: {data: {callFrame: {functionName: '(root)'}}}}, @@ -296,7 +295,7 @@ describe('CPU Profiler Model', () => { {startTime: 92, endTime: 103}, ]; - const events = CpuProfilerModel.synthesizeTraceEvents(profile, tasks); + const events = CpuProfileModel.synthesizeTraceEvents(profile, tasks); expect(events).toMatchObject([ {ph: 'B', ts: ts(0.5e3), args: {data: {callFrame: {functionName: '(root)'}}}}, @@ -333,7 +332,7 @@ describe('CPU Profiler Model', () => { const ts = x => profile.startTime + x; - const events = CpuProfilerModel.synthesizeTraceEvents(profile, []); + const events = CpuProfileModel.synthesizeTraceEvents(profile, []); expect(events).toMatchObject([ {ph: 'B', ts: ts(0.5e3), args: {data: {callFrame: {functionName: '(rootA)'}}}}, @@ -353,7 +352,7 @@ describe('CPU Profiler Model', () => { it('should create main-thread-task parseable events', () => { const ts = x => profile.startTime + x; - const events = CpuProfilerModel.synthesizeTraceEvents(profile); + const events = CpuProfileModel.synthesizeTraceEvents(profile); const tasks = MainThreadTasks.getMainThreadTasks(events, [], ts(19e3)); expect(tasks).toHaveLength(6); diff --git a/lighthouse-core/test/lib/tracehouse/main-thread-tasks-test.js b/lighthouse-core/test/lib/tracehouse/main-thread-tasks-test.js index 0702e9ac2335..2dcf7f7ac34e 100644 --- a/lighthouse-core/test/lib/tracehouse/main-thread-tasks-test.js +++ b/lighthouse-core/test/lib/tracehouse/main-thread-tasks-test.js @@ -6,10 +6,9 @@ import {strict as assert} from 'assert'; -import MainThreadTasks from '../../../lib/tracehouse/main-thread-tasks.js'; -import TraceProcessor from '../../../lib/tracehouse/trace-processor.js'; +import {MainThreadTasks} from '../../../lib/tracehouse/main-thread-tasks.js'; +import {TraceProcessor} from '../../../lib/tracehouse/trace-processor.js'; import {taskGroups} from '../../../lib/tracehouse/task-groups.js'; -import TracingProcessor from '../../../lib/tracehouse/trace-processor.js'; import {readJson} from '../../test-utils.js'; const pwaTrace = readJson('../../fixtures/traces/progressive-app.json', import.meta); @@ -55,7 +54,7 @@ describe('Main Thread Tasks', () => { while (queue.length) { const task = queue.shift(); totalTime += task.selfTime; - totalTopLevelTime += TracingProcessor.isScheduleableTask(task.event) ? task.duration : 0; + totalTopLevelTime += TraceProcessor.isScheduleableTask(task.event) ? task.duration : 0; allTasks.push(task); queue.push(...task.children); } diff --git a/lighthouse-core/test/lib/tracehouse/task-summary-test.js b/lighthouse-core/test/lib/tracehouse/task-summary-test.js index 61184bf3069d..153826037669 100644 --- a/lighthouse-core/test/lib/tracehouse/task-summary-test.js +++ b/lighthouse-core/test/lib/tracehouse/task-summary-test.js @@ -9,10 +9,10 @@ import { getAttributableURLForTask, getExecutionTimingsByURL, } from '../../../lib/tracehouse/task-summary.js'; -import NetworkRecorder from '../../../lib/network-recorder.js'; -import MainThreadTasks from '../../../lib/tracehouse/main-thread-tasks.js'; -import TraceProcessor from '../../../lib/tracehouse/trace-processor.js'; -import networkRecordsToDevtoolsLog from '../../network-records-to-devtools-log.js'; +import {NetworkRecorder} from '../../../lib/network-recorder.js'; +import {MainThreadTasks} from '../../../lib/tracehouse/main-thread-tasks.js'; +import {TraceProcessor} from '../../../lib/tracehouse/trace-processor.js'; +import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js'; import {taskGroups} from '../../../lib/tracehouse/task-groups.js'; import {readJson} from '../../test-utils.js'; diff --git a/lighthouse-core/test/lib/tracehouse/trace-processor-test.js b/lighthouse-core/test/lib/tracehouse/trace-processor-test.js index 7b031c4101a8..cc2877ceadd8 100644 --- a/lighthouse-core/test/lib/tracehouse/trace-processor-test.js +++ b/lighthouse-core/test/lib/tracehouse/trace-processor-test.js @@ -6,8 +6,8 @@ import {strict as assert} from 'assert'; -import TraceProcessor from '../../../lib/tracehouse/trace-processor.js'; -import createTestTrace from '../../create-test-trace.js'; +import {TraceProcessor} from '../../../lib/tracehouse/trace-processor.js'; +import {createTestTrace} from '../../create-test-trace.js'; import {readJson} from '../../test-utils.js'; const pwaTrace = readJson('../../fixtures/traces/progressive-app.json', import.meta); diff --git a/lighthouse-core/test/lib/traces/pwmetrics-events-test.js b/lighthouse-core/test/lib/traces/pwmetrics-events-test.js index 3f3a0227acb8..e8509ad0e8a4 100644 --- a/lighthouse-core/test/lib/traces/pwmetrics-events-test.js +++ b/lighthouse-core/test/lib/traces/pwmetrics-events-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import Metrics from '../../../lib/traces/pwmetrics-events.js'; +import {Metrics} from '../../../lib/traces/pwmetrics-events.js'; import {readJson} from '../../test-utils.js'; const dbwTrace = readJson('../../results/artifacts/defaultPass.trace.json', import.meta); diff --git a/lighthouse-core/test/network-records-to-devtools-log-test.js b/lighthouse-core/test/network-records-to-devtools-log-test.js index 0e3d036888bf..119707bae171 100644 --- a/lighthouse-core/test/network-records-to-devtools-log-test.js +++ b/lighthouse-core/test/network-records-to-devtools-log-test.js @@ -4,8 +4,8 @@ * 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. */ -import NetworkRecorder from '../../lighthouse-core/lib/network-recorder.js'; -import networkRecordsToDevtoolsLog from './network-records-to-devtools-log.js'; +import {NetworkRecorder} from '../../lighthouse-core/lib/network-recorder.js'; +import {networkRecordsToDevtoolsLog} from './network-records-to-devtools-log.js'; import {readJson} from './test-utils.js'; const lcpDevtoolsLog = readJson('./fixtures/traces/lcp-m78.devtools.log.json', import.meta); diff --git a/lighthouse-core/test/network-records-to-devtools-log.js b/lighthouse-core/test/network-records-to-devtools-log.js index c084a8bec6e8..8c40d8fa4844 100644 --- a/lighthouse-core/test/network-records-to-devtools-log.js +++ b/lighthouse-core/test/network-records-to-devtools-log.js @@ -5,9 +5,9 @@ * 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. */ -import NetworkRecorder from '../../lighthouse-core/lib/network-recorder.js'; +import {NetworkRecorder} from '../../lighthouse-core/lib/network-recorder.js'; -/** @typedef {import('../../lighthouse-core/lib/network-request.js')} NetworkRequest */ +/** @typedef {import('../../lighthouse-core/lib/network-request.js').NetworkRequest} NetworkRequest */ const idBase = '127122'; const exampleUrl = 'https://testingurl.com/'; @@ -257,4 +257,4 @@ function networkRecordsToDevtoolsLog(networkRecords, options = {}) { return devtoolsLog; } -export default networkRecordsToDevtoolsLog; +export {networkRecordsToDevtoolsLog}; diff --git a/lighthouse-core/test/runner-test.js b/lighthouse-core/test/runner-test.js index 6a98e98570a7..4048b93ee139 100644 --- a/lighthouse-core/test/runner-test.js +++ b/lighthouse-core/test/runner-test.js @@ -7,50 +7,77 @@ import fs from 'fs'; import {strict as assert} from 'assert'; import path from 'path'; -import {createRequire} from 'module'; import jestMock from 'jest-mock'; import * as td from 'testdouble'; // import Runner from '../runner.js'; -// import GatherRunner from '../gather/gather-runner.js'; -import driverMock from './gather/fake-driver.js'; -// import Config from '../config/config.js'; -import Audit from '../audits/audit.js'; -import Gatherer from '../gather/gatherers/gatherer.js'; -import assetSaver from '../lib/asset-saver.js'; -import LighthouseError from '../lib/lh-error.js'; -import i18n from '../lib/i18n/i18n.js'; +// import {GatherRunner} from '../gather/gather-runner.js'; +import {fakeDriver as driverMock} from './gather/fake-driver.js'; +// import {Config} from '../config/config.js'; +import {Audit} from '../audits/audit.js'; +import {Gatherer} from '../gather/gatherers/gatherer.js'; +import * as assetSaver from '../lib/asset-saver.js'; +import {LighthouseError} from '../lib/lh-error.js'; +import * as i18n from '../lib/i18n/i18n.js'; import {importMock, makeMocksForGatherRunner} from './test-utils.js'; -import {getModuleDirectory, getModulePath} from '../../esm-utils.mjs'; +import {getModuleDirectory} from '../../esm-utils.js'; -const require = createRequire(import.meta.url); -const modulePath = getModulePath(import.meta); const moduleDir = getModuleDirectory(import.meta); +await makeMocksForGatherRunner(); + // Some imports needs to be done dynamically, so that their dependencies will be mocked. // See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs // https://github.com/facebook/jest/issues/10025 -/** @type {typeof import('../runner.js')} */ +/** @type {typeof import('../runner.js').Runner} */ let Runner; -/** @type {typeof import('../gather/gather-runner.js')} */ +/** @type {typeof import('../gather/gather-runner.js').GatherRunner} */ let GatherRunner; -/** @type {typeof import('../config/config.js')} */ +/** @type {typeof import('../config/config.js').Config} */ let Config; -before(async () => { - Runner = (await import('../runner.js')).default; - GatherRunner = (await import('../gather/gather-runner.js')).default; - Config = (await import('../config/config.js')).default; +/** @type {jestMock.Mock} */ +let saveArtifactsSpy; +/** @type {jestMock.Mock} */ +let saveLhrSpy; +/** @type {jestMock.Mock} */ +let loadArtifactsSpy; +/** @type {jestMock.Mock} */ +let gatherRunnerRunSpy; +/** @type {jestMock.Mock} */ +let runAuditSpy; + +await td.replaceEsm('../lib/asset-saver.js', { + saveArtifacts: saveArtifactsSpy = jestMock.fn(assetSaver.saveArtifacts), + saveLhr: saveLhrSpy = jestMock.fn(), + loadArtifacts: loadArtifactsSpy = jestMock.fn(assetSaver.loadArtifacts), }); -makeMocksForGatherRunner(); - -td.replace('../gather/driver/service-workers.js', { +await td.replaceEsm('../gather/driver/service-workers.js', { getServiceWorkerVersions: jestMock.fn().mockResolvedValue({versions: []}), getServiceWorkerRegistrations: jestMock.fn().mockResolvedValue({registrations: []}), }); +before(async () => { + Runner = (await import('../runner.js')).Runner; + GatherRunner = (await import('../gather/gather-runner.js')).GatherRunner; + Config = (await import('../config/config.js')).Config; +}); + +beforeEach(() => { + gatherRunnerRunSpy = jestMock.spyOn(GatherRunner, 'run'); + runAuditSpy = jestMock.spyOn(Runner, '_runAudit'); +}); + +afterEach(() => { + saveArtifactsSpy.mockClear(); + saveLhrSpy.mockClear(); + loadArtifactsSpy.mockClear(); + gatherRunnerRunSpy.mockRestore(); + runAuditSpy.mockRestore(); +}); + describe('Runner', () => { const createGatherFn = url => { return opts => { @@ -67,33 +94,6 @@ describe('Runner', () => { return Runner.audit(artifacts, opts); }; - /** @type {jestMock} */ - let saveArtifactsSpy; - /** @type {jestMock} */ - let saveLhrSpy; - /** @type {jestMock} */ - let loadArtifactsSpy; - /** @type {jestMock} */ - let gatherRunnerRunSpy; - /** @type {jestMock} */ - let runAuditSpy; - - beforeEach(() => { - saveArtifactsSpy = jestMock.spyOn(assetSaver, 'saveArtifacts'); - saveLhrSpy = jestMock.spyOn(assetSaver, 'saveLhr').mockImplementation(() => {}); - loadArtifactsSpy = jestMock.spyOn(assetSaver, 'loadArtifacts'); - gatherRunnerRunSpy = jestMock.spyOn(GatherRunner, 'run'); - runAuditSpy = jestMock.spyOn(Runner, '_runAudit'); - }); - - afterEach(() => { - saveArtifactsSpy.mockRestore(); - saveLhrSpy.mockRestore(); - loadArtifactsSpy.mockRestore(); - gatherRunnerRunSpy.mockRestore(); - runAuditSpy.mockRestore(); - }); - const basicAuditMeta = { id: 'test-audit', title: 'A test audit', @@ -201,7 +201,7 @@ describe('Runner', () => { it('serializes IcuMessages in gatherMode and is able to use them in auditMode', async () => { // Can use this to access shared UIStrings in i18n.js. // For future changes: exact messages aren't important, just choose ones with replacements. - const str_ = i18n.createMessageInstanceIdFn(modulePath, {}); + const str_ = i18n.createMessageInstanceIdFn(import.meta.url, {}); // A gatherer that produces an IcuMessage runWarning and LighthouseError artifact. class WarningAndErrorGatherer extends Gatherer { @@ -489,7 +489,7 @@ describe('Runner', () => { assert.strictEqual(auditResult.scoreDisplayMode, 'error'); assert.ok(auditResult.errorMessage.includes(errorMessage)); - fs.rmSync(resolvedPath, {recursive: true, force: true}); + fs.rmSync(resolvedPath, {recursive: true}); }); it('only passes the requested artifacts to the audit (no optional artifacts)', async () => { @@ -680,15 +680,15 @@ describe('Runner', () => { }); }); - it('only supports core audits with names matching their filename', () => { + it('only supports core audits with ids matching their filename', async () => { const coreAudits = Runner.getAuditList(); - coreAudits.forEach(auditFilename => { + for (const auditFilename of coreAudits) { const auditPath = '../audits/' + auditFilename; const auditExpectedName = path.basename(auditFilename, '.js'); - const AuditClass = require(auditPath); + const {default: AuditClass} = await import(auditPath); assert.strictEqual(AuditClass.meta.id, auditExpectedName); - }); - }).timeout(40_000); + } + }); it('results include artifacts when given artifacts and audits', async () => { const config = await Config.fromJson({ @@ -830,7 +830,7 @@ describe('Runner', () => { // Loads the page successfully in the first pass, fails with PAGE_HUNG in the second. }); - const {gotoURL} = (await importMock('../gather/driver/navigation.js', import.meta)).default; + const {gotoURL} = await importMock('../gather/driver/navigation.js', import.meta); gotoURL.mockImplementation((_, url) => { if (url.includes('blank')) return {mainDocumentUrl: '', warnings: []}; if (firstLoad) { diff --git a/lighthouse-core/test/scoring-test.js b/lighthouse-core/test/scoring-test.js index 03ff46fe3c3d..68dbdcd6ffad 100644 --- a/lighthouse-core/test/scoring-test.js +++ b/lighthouse-core/test/scoring-test.js @@ -6,7 +6,7 @@ import {strict as assert} from 'assert'; -import ReportScoring from '../scoring.js'; +import {ReportScoring} from '../scoring.js'; describe('ReportScoring', () => { describe('#arithmeticMean', () => { diff --git a/lighthouse-core/test/scripts/run-mocha-tests.js b/lighthouse-core/test/scripts/run-mocha-tests.js index f4fbfdb35484..4d037e390780 100644 --- a/lighthouse-core/test/scripts/run-mocha-tests.js +++ b/lighthouse-core/test/scripts/run-mocha-tests.js @@ -47,9 +47,10 @@ function getFailedTests() { // yarn mocha --no-isolation --no-parallel lighthouse-core/test // // Because mocha workers can divide up test files that mess with global scope in a way that -// _just happens_ to not cause anything to fail, use this command works to verify that +// _just happens_ to not cause anything to fail, use this command to verify that // all necessary tests are isolated: -// yarn mocha --no-parallel lighthouse-core/test +// yarn mocha --no-parallel +// (also, just comment out the `testsToRunIsolated` below, as they won't impact this verification) const testsToIsolate = new Set([ // grep -lRE '^timers\.useFakeTimers' --include='*-test.*' --exclude-dir=node_modules 'flow-report/test/common-test.tsx', @@ -67,14 +68,12 @@ const testsToIsolate = new Set([ 'lighthouse-core/test/gather/gatherers/trace-test.js', // grep -lRE '^td\.replace' --include='*-test.*' --exclude-dir=node_modules - 'lighthouse-core/test/fraggle-rock/gather/navigation-runner-test.js', 'lighthouse-core/test/fraggle-rock/gather/snapshot-runner-test.js', 'lighthouse-core/test/fraggle-rock/gather/timespan-runner-test.js', 'lighthouse-core/test/fraggle-rock/user-flow-test.js', 'lighthouse-core/test/gather/driver/prepare-test.js', 'lighthouse-core/test/gather/gatherers/link-elements-test.js', 'lighthouse-core/test/gather/gatherers/service-worker-test.js', - 'lighthouse-core/test/lib/sentry-test.js', 'lighthouse-core/test/runner-test.js', // grep -lRE --include='-test.js' 'mockDriverSubmodules|mockRunnerModule|mockDriverModule|mockDriverSubmodules|makeMocksForGatherRunner' --include='*-test.*' --exclude-dir=node_modules @@ -95,6 +94,8 @@ const testsToIsolate = new Set([ // ? 'clients/test/lightrider/lightrider-entry-test.js', // Runner overrides. 'flow-report/test/flow-report-pptr-test.ts', + 'lighthouse-cli/test/cli/bin-test.js', + 'lighthouse-cli/test/cli/run-test.js', 'lighthouse-core/test/config/config-test.js', 'lighthouse-core/test/fraggle-rock/config/config-test.js', 'lighthouse-core/test/lib/emulation-test.js', diff --git a/lighthouse-core/test/test-utils.js b/lighthouse-core/test/test-utils.js index d71eb5eb3fc6..f424adc92708 100644 --- a/lighthouse-core/test/test-utils.js +++ b/lighthouse-core/test/test-utils.js @@ -14,9 +14,9 @@ import jestMock from 'jest-mock'; import {LH_ROOT} from '../../root.js'; import * as mockCommands from './gather/mock-commands.js'; -import NetworkRecorder from '../lib/network-recorder.js'; +import {NetworkRecorder} from '../lib/network-recorder.js'; import {timers} from './test-env/fake-timers.js'; -import {getModuleDirectory} from '../../esm-utils.mjs'; +import {getModuleDirectory} from '../../esm-utils.js'; const require = createRequire(import.meta.url); @@ -181,36 +181,36 @@ async function flushAllTimersAndMicrotasks(ms = 1000) { * Mocks gatherers for BaseArtifacts that tests for components using GatherRunner * shouldn't concern themselves about. */ -function makeMocksForGatherRunner() { - td.replace(require.resolve('../gather/driver/environment.js'), { +async function makeMocksForGatherRunner() { + await td.replaceEsm(require.resolve('../gather/driver/environment.js'), { getBenchmarkIndex: () => Promise.resolve(150), getBrowserVersion: async () => ({userAgent: 'Chrome', milestone: 80}), getEnvironmentWarnings: () => [], }); - td.replace(require.resolve('../gather/gatherers/stacks.js'), { + await td.replaceEsm(require.resolve('../gather/gatherers/stacks.js'), undefined, { collectStacks: () => Promise.resolve([]), }); - td.replace(require.resolve('../gather/gatherers/installability-errors.js'), { + await td.replaceEsm(require.resolve('../gather/gatherers/installability-errors.js'), undefined, { getInstallabilityErrors: async () => ({errors: []}), }); - td.replace(require.resolve('../gather/gatherers/web-app-manifest.js'), { + await td.replaceEsm(require.resolve('../gather/gatherers/web-app-manifest.js'), undefined, { getWebAppManifest: async () => null, }); - td.replace(require.resolve('../lib/emulation.js'), { + await td.replaceEsm(require.resolve('../lib/emulation.js'), { emulate: jestMock.fn(), throttle: jestMock.fn(), clearThrottling: jestMock.fn(), }); - td.replace(require.resolve('../gather/driver/prepare.js'), { + await td.replaceEsm(require.resolve('../gather/driver/prepare.js'), { prepareTargetForNavigationMode: jestMock.fn(), prepareTargetForIndividualNavigation: jestMock.fn().mockResolvedValue({warnings: []}), }); - td.replace(require.resolve('../gather/driver/storage.js'), { + await td.replaceEsm(require.resolve('../gather/driver/storage.js'), { clearDataForOrigin: jestMock.fn(), cleanBrowserCaches: jestMock.fn(), getImportantStorageWarning: jestMock.fn(), }); - td.replace(require.resolve('../gather/driver/navigation.js'), { + await td.replaceEsm(require.resolve('../gather/driver/navigation.js'), { gotoURL: jestMock.fn().mockResolvedValue({ mainDocumentUrl: 'http://example.com', warnings: [], diff --git a/lighthouse-core/util-commonjs.js b/lighthouse-core/util.cjs similarity index 100% rename from lighthouse-core/util-commonjs.js rename to lighthouse-core/util.cjs diff --git a/package.json b/package.json index 39af2022400d..951e26342ac7 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,6 @@ { "name": "lighthouse", + "type": "module", "version": "9.5.0", "description": "Automated auditing, performance metrics, and best practices for the web.", "main": "./lighthouse-core/index.js", @@ -214,7 +215,8 @@ }, "resolutions": { "puppeteer/**/devtools-protocol": "0.0.995287", - "puppeteer-core/**/devtools-protocol": "0.0.995287" + "puppeteer-core/**/devtools-protocol": "0.0.995287", + "testdouble/**/quibble": "connorjclark/quibble#mod-cache" }, "repository": "GoogleChrome/lighthouse", "keywords": [ diff --git a/report/test/generator/report-generator-test.js b/report/test/generator/report-generator-test.js index ced8ebf93d95..a3d6f0b1e3ca 100644 --- a/report/test/generator/report-generator-test.js +++ b/report/test/generator/report-generator-test.js @@ -13,9 +13,10 @@ const fs = require('fs'); const csvValidator = require('csv-validator'); const ReportGenerator = require('../../generator/report-generator.js'); -const {readJson} = require('../../../root.js'); - -const sampleResults = readJson('lighthouse-core/test/results/sample_v2.json'); +// const {readJson} = require('../../../root.js'); +// TODO(esmodules): remove when this folder is esm +// const sampleResults = readJson('lighthouse-core/test/results/sample_v2.json'); +const sampleResults = require('../../../lighthouse-core/test/results/sample_v2.json'); describe('ReportGenerator', () => { describe('#replaceStrings', () => { diff --git a/report/test/renderer/report-renderer-axe-test.js b/report/test/renderer/report-renderer-axe-test.js index bc101bf2d8fc..e3975f4f88ca 100644 --- a/report/test/renderer/report-renderer-axe-test.js +++ b/report/test/renderer/report-renderer-axe-test.js @@ -7,7 +7,7 @@ import puppeteer from 'puppeteer'; import reportGenerator from '../../generator/report-generator.js'; -import axeLib from '../../../lighthouse-core/lib/axe.js'; +import {axeSource} from '../../../lighthouse-core/lib/axe.js'; import {readJson} from '../../../lighthouse-core/test/test-utils.js'; const sampleResults = readJson('../../../lighthouse-core/test/results/sample_v2.json', import.meta); @@ -52,7 +52,7 @@ describe('ReportRendererAxe', () => { }, }; - await page.evaluate(axeLib.source); + await page.evaluate(axeSource); // eslint-disable-next-line no-undef const axeResults = await page.evaluate(config => axe.run(config), config); diff --git a/root.js b/root.js index 9912df6e2b44..949d9b677764 100644 --- a/root.js +++ b/root.js @@ -5,6 +5,14 @@ */ 'use strict'; -module.exports = { - LH_ROOT: __dirname, +import fs from 'fs'; +import {getModuleDirectory} from './esm-utils.js'; + +const LH_ROOT = getModuleDirectory(import.meta); +const pkg = JSON.parse(fs.readFileSync(`${LH_ROOT}/package.json`, 'utf-8')); +const lighthouseVersion = pkg.version; + +export { + LH_ROOT, + lighthouseVersion, }; diff --git a/shared/package.json b/shared/package.json new file mode 100644 index 000000000000..8d10bc1dfd36 --- /dev/null +++ b/shared/package.json @@ -0,0 +1,4 @@ +{ + "type": "commonjs", + "//": "Preserve commonjs in this directory. Temporary file until converted to type: module" +} diff --git a/shared/test/localization/format-test.js b/shared/test/localization/format-test.js index 625c960857d0..215485883486 100644 --- a/shared/test/localization/format-test.js +++ b/shared/test/localization/format-test.js @@ -8,10 +8,16 @@ const path = require('path'); const format = require('../../localization/format.js'); -const i18n = require('../../../lighthouse-core/lib/i18n/i18n.js'); -const constants = require('../../../lighthouse-core/config/constants.js'); const locales = require('../../localization/locales.js'); +// TODO(esmodules): remove when shared/ is esm +let i18n; +let constants; +before(async () => { + i18n = await import('../../../lighthouse-core/lib/i18n/i18n.js'); + constants = await import('../../../lighthouse-core/config/constants.js'); +}); + describe('format', () => { describe('DEFAULT_LOCALE', () => { it('is the same as the default config locale', () => { @@ -183,9 +189,9 @@ describe('format', () => { expect(formattedStr).toEqual('en-XZ cuerda!'); }); - it('overwrites existing locale strings', () => { + it('overwrites existing locale strings', async () => { const filename = 'lighthouse-core/audits/is-on-https.js'; - const UIStrings = require('../../../lighthouse-core/audits/is-on-https.js').UIStrings; + const {UIStrings} = await import('../../../lighthouse-core/audits/is-on-https.js'); const str_ = i18n.createMessageInstanceIdFn(filename, UIStrings); // To start with, we get back the intended string.. @@ -305,17 +311,21 @@ describe('format', () => { helloWorldMultiReplace: '{hello} {world}', helloPlural: '{itemCount, plural, =1{1 hello} other{hellos}}', helloPluralNestedICU: '{itemCount, plural, ' + - '=1{1 hello {in, number, bytes}} ' + - 'other{hellos {in, number, bytes}}}', + '=1{1 hello {in, number, bytes}} ' + + 'other{hellos {in, number, bytes}}}', helloPluralNestedPluralAndICU: '{itemCount, plural, ' + - '=1{{innerItemCount, plural, ' + - '=1{1 hello 1 goodbye {in, number, bytes}} ' + - 'other{1 hello, goodbyes {in, number, bytes}}}} ' + - 'other{{innerItemCount, plural, ' + - '=1{hellos 1 goodbye {in, number, bytes}} ' + - 'other{hellos, goodbyes {in, number, bytes}}}}}', + '=1{{innerItemCount, plural, ' + + '=1{1 hello 1 goodbye {in, number, bytes}} ' + + 'other{1 hello, goodbyes {in, number, bytes}}}} ' + + 'other{{innerItemCount, plural, ' + + '=1{hellos 1 goodbye {in, number, bytes}} ' + + 'other{hellos, goodbyes {in, number, bytes}}}}}', }; - const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); + + let str_; + before(() => { + str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); + }); it('formats a basic message', () => { const helloStr = str_(UIStrings.helloWorld); diff --git a/shared/test/localization/swap-locale-test.js b/shared/test/localization/swap-locale-test.js index 50272f6e1d67..41829e47b6c9 100644 --- a/shared/test/localization/swap-locale-test.js +++ b/shared/test/localization/swap-locale-test.js @@ -8,6 +8,7 @@ const swapLocale = require('../../localization/swap-locale.js'); const lhr = require('../../../lighthouse-core/test/results/sample_v2.json'); + describe('swap-locale', () => { it('does not mutate the original lhr', () => { /** @type {LH.Result} */ diff --git a/third-party/axe/valid-langs.js b/third-party/axe/valid-langs.js index a9776f10de51..ff4dcdfcd49d 100644 --- a/third-party/axe/valid-langs.js +++ b/third-party/axe/valid-langs.js @@ -107,4 +107,4 @@ function validLangs(langArray) { return codes; } -module.exports = {isValidLang}; +export {isValidLang}; diff --git a/third-party/chromium-synchronization/inspector-issueAdded-types-test.js b/third-party/chromium-synchronization/inspector-issueAdded-types-test.js index 97afc8318ae0..8d9984e5de3d 100644 --- a/third-party/chromium-synchronization/inspector-issueAdded-types-test.js +++ b/third-party/chromium-synchronization/inspector-issueAdded-types-test.js @@ -5,9 +5,9 @@ */ 'use strict'; -const fs = require('fs'); -const fetch = require('node-fetch'); -const {LH_ROOT} = require('../../root.js'); +import fs from 'fs'; +import fetch from 'node-fetch'; +import { LH_ROOT } from '../../root.js'; const inspectorIssuesGathererPath = LH_ROOT + '/lighthouse-core/gather/gatherers/inspector-issues.js'; diff --git a/third-party/chromium-synchronization/installability-errors-test.js b/third-party/chromium-synchronization/installability-errors-test.js index 604d54eec14b..664aeb366cc2 100644 --- a/third-party/chromium-synchronization/installability-errors-test.js +++ b/third-party/chromium-synchronization/installability-errors-test.js @@ -5,9 +5,9 @@ */ 'use strict'; -const fetch = require('node-fetch'); +import fetch from 'node-fetch'; -const InstallableManifestAudit = require('../../lighthouse-core/audits/installable-manifest.js'); +import {UIStrings} from '../../lighthouse-core/audits/installable-manifest.js'; describe('installabilityErrors', () => { let chromiumErrorIds; @@ -74,7 +74,7 @@ Array [ }); it('are each handled explicitly in the gatherer', () => { - const errorStrings = Object.keys(InstallableManifestAudit.UIStrings) + const errorStrings = Object.keys(UIStrings) .filter(key => chromiumErrorIds.includes(key)) .sort(); expect(errorStrings).toEqual(chromiumErrorIds); diff --git a/third-party/download-content-shell/download-content-shell.js b/third-party/download-content-shell/download-content-shell.js index 553be247f1ea..f6d2b0a93f16 100644 --- a/third-party/download-content-shell/download-content-shell.js +++ b/third-party/download-content-shell/download-content-shell.js @@ -7,11 +7,12 @@ // Grabbed from https://github.com/ChromeDevTools/devtools-frontend/commit/26bb5ad91b147e9c918819711542ec2337d6b268 -const fs = require('fs'); -const path = require('path'); -const shell = require('child_process').execSync; -const utils = require('./utils.js'); -const {LH_ROOT} = require('../../root.js'); +import fs from 'fs'; + +import path from 'path'; +import { execSync as shell } from 'child_process'; +import * as utils from './utils.js'; +import { LH_ROOT } from '../../root.js'; const TARGET = 'Release'; const CONTENT_SHELL_ZIP = 'content-shell.zip'; diff --git a/third-party/download-content-shell/utils.js b/third-party/download-content-shell/utils.js index 38f87225ddb1..6629fe51635c 100644 --- a/third-party/download-content-shell/utils.js +++ b/third-party/download-content-shell/utils.js @@ -3,13 +3,13 @@ // found in the LICENSE file. 'use strict'; -const fs = require('fs'); -const http = require('http'); -const https = require('https'); -const path = require('path'); -const parseURL = require('url').parse; -const shell = require('child_process').execSync; -const Stream = require('stream').Transform; +import fs from 'fs'; +import http from 'http'; +import https from 'https'; +import path from 'path'; +import { parse as parseURL } from 'url'; +import { execSync as shell } from 'child_process'; +import { Transform as Stream } from 'stream'; function fetch(url) { return new Promise(fetchPromise); @@ -115,7 +115,7 @@ function parseArgs(args) { return argObject; } -module.exports = { +export { fetch, atob, isFile, diff --git a/tsconfig.json b/tsconfig.json index 3b7c3916c1a8..fd660da6e5cb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,8 +13,11 @@ ], "include": [ "root.js", + "esm-utils.js", "lighthouse-cli/**/*.js", "lighthouse-core/**/*.js", + "lighthouse-core/index.cjs", + "lighthouse-core/util.cjs", "clients/**/*.js", "build/**/*.js", "./types/**/*.d.ts", @@ -30,7 +33,6 @@ "third-party/snyk/snapshot.json", "lighthouse-core/audits/byte-efficiency/polyfill-graph-data.json", "shared/localization/locales/en-US.json", - "esm-utils.mjs", ], "exclude": [ "lighthouse-core/test/audits/**/*.js", diff --git a/types/artifacts.d.ts b/types/artifacts.d.ts index 88c0fcd2c28c..759e655834e0 100644 --- a/types/artifacts.d.ts +++ b/types/artifacts.d.ts @@ -4,16 +4,14 @@ * 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. */ -import parseManifest = require('../lighthouse-core/lib/manifest-parser.js'); -import LanternSimulator = require('../lighthouse-core/lib/dependency-graph/simulator/simulator.js'); -import LighthouseError = require('../lighthouse-core/lib/lh-error.js'); -import _NetworkRequest = require('../lighthouse-core/lib/network-request.js'); -import speedline = require('speedline-core'); -import TextSourceMap = require('../lighthouse-core/lib/cdt/generated/SourceMap.js'); -import ArbitraryEqualityMap = require('../lighthouse-core/lib/arbitrary-equality-map.js'); - -type _TaskNode = import('../lighthouse-core/lib/tracehouse/main-thread-tasks.js').TaskNode; - +import {parseManifest} from '../lighthouse-core/lib/manifest-parser.js'; +import {Simulator} from '../lighthouse-core/lib/dependency-graph/simulator/simulator.js'; +import {LighthouseError} from '../lighthouse-core/lib/lh-error.js'; +import {NetworkRequest as _NetworkRequest} from '../lighthouse-core/lib/network-request.js'; +import speedline from 'speedline-core'; +import TextSourceMap from '../lighthouse-core/lib/cdt/generated/SourceMap.js'; +import {ArbitraryEqualityMap} from '../lighthouse-core/lib/arbitrary-equality-map.js'; +import type { TaskNode as _TaskNode } from '../lighthouse-core/lib/tracehouse/main-thread-tasks.js'; import AuditDetails from './lhr/audit-details' import Config from './config'; import Gatherer from './gatherer'; @@ -643,7 +641,7 @@ declare module Artifacts { trace: Trace; settings: Immutable; gatherContext: Artifacts['GatherContext']; - simulator?: InstanceType; + simulator?: InstanceType; URL: Artifacts['URL']; } diff --git a/types/audit.d.ts b/types/audit.d.ts index 755d47a93e8f..b37750d74075 100644 --- a/types/audit.d.ts +++ b/types/audit.d.ts @@ -4,12 +4,12 @@ * 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. */ -import ArbitraryEqualityMap = require('../lighthouse-core/lib/arbitrary-equality-map.js'); +import {ArbitraryEqualityMap} from '../lighthouse-core/lib/arbitrary-equality-map.js'; import {Artifacts} from './artifacts'; import AuditDetails from './lhr/audit-details'; import Config from './config'; import Gatherer from './gatherer'; -import {FormattedIcu, IcuMessage} from './lhr/i18n'; +import {IcuMessage} from './lhr/i18n'; import * as AuditResult from './lhr/audit-result'; declare module Audit { diff --git a/types/config.d.ts b/types/config.d.ts index 4d170052e6ff..67e715d0c8c6 100644 --- a/types/config.d.ts +++ b/types/config.d.ts @@ -5,7 +5,7 @@ * 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. */ -import Audit = require('../lighthouse-core/audits/audit.js'); +import {Audit} from '../lighthouse-core/audits/audit.js'; import {SharedFlagsSettings, ConfigSettings} from './lhr/settings'; import Gatherer from './gatherer'; import {IcuMessage} from './lhr/i18n'; diff --git a/types/cssstyle/index.d.ts b/types/cssstyle/index.d.ts index dd490d99626d..3cf2f0030a32 100644 --- a/types/cssstyle/index.d.ts +++ b/types/cssstyle/index.d.ts @@ -4,7 +4,7 @@ * 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. */ -declare module 'cssstyle/lib/parsers' { +declare module 'cssstyle/lib/parsers.js' { interface TYPES { INTEGER: 1; NUMBER: 2; diff --git a/types/gatherer.d.ts b/types/gatherer.d.ts index 05519f49dcbb..7ac00d708da2 100644 --- a/types/gatherer.d.ts +++ b/types/gatherer.d.ts @@ -4,13 +4,13 @@ * 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. */ -import _NetworkNode = require('../lighthouse-core/lib/dependency-graph/network-node'); -import _CPUNode = require('../lighthouse-core/lib/dependency-graph/cpu-node'); -import _Simulator = require('../lighthouse-core/lib/dependency-graph/simulator/simulator'); -import Driver = require('../lighthouse-core/gather/driver'); -import ExecutionContext = require('../lighthouse-core/gather/driver/execution-context'); -import Fetcher = require('../lighthouse-core/gather/fetcher'); -import ArbitraryEqualityMap = require('../lighthouse-core/lib/arbitrary-equality-map'); +import {NetworkNode as _NetworkNode} from '../lighthouse-core/lib/dependency-graph/network-node'; +import {CPUNode as _CPUNode} from '../lighthouse-core/lib/dependency-graph/cpu-node'; +import {Simulator as _Simulator} from '../lighthouse-core/lib/dependency-graph/simulator/simulator'; +import {Driver} from '../lighthouse-core/gather/driver'; +import {ExecutionContext} from '../lighthouse-core/gather/driver/execution-context'; +import {Fetcher} from '../lighthouse-core/gather/fetcher'; +import {ArbitraryEqualityMap} from '../lighthouse-core/lib/arbitrary-equality-map'; import {Artifacts, BaseArtifacts, FRBaseArtifacts, GathererArtifacts} from './artifacts'; import Config from './config'; diff --git a/types/global-lh.d.ts b/types/global-lh.d.ts index 3df6983408c7..2c5f3715786e 100644 --- a/types/global-lh.d.ts +++ b/types/global-lh.d.ts @@ -4,7 +4,7 @@ * 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. */ -import ArbitraryEqualityMap_ = require('../lighthouse-core/lib/arbitrary-equality-map.js'); +import {ArbitraryEqualityMap as ArbitraryEqualityMap_} from '../lighthouse-core/lib/arbitrary-equality-map.js'; import * as Artifacts_ from './artifacts'; import Audit_ from './audit'; import Budget_ from './lhr/budget'; @@ -14,7 +14,7 @@ import _CrdpMappings from 'devtools-protocol/types/protocol-mapping'; import * as Externs from './externs'; import Gatherer_ from './gatherer'; import * as I18n from './lhr/i18n'; -import LighthouseError_ = require('../lighthouse-core/lib/lh-error.js'); +import {LighthouseError as LighthouseError_} from '../lighthouse-core/lib/lh-error.js'; import LHResult from './lhr/lhr'; import FlowResult_ from './lhr/flow'; import Protocol_ from './protocol'; diff --git a/yarn.lock b/yarn.lock index dd54c4b1f089..20f411f15e7a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6131,10 +6131,9 @@ query-string@^4.1.0: object-assign "^4.1.0" strict-uri-encode "^1.0.0" -quibble@^0.6.7: +quibble@^0.6.7, quibble@connorjclark/quibble#mod-cache: version "0.6.9" - resolved "https://registry.yarnpkg.com/quibble/-/quibble-0.6.9.tgz#1e7b24a72b59bdb6cc272318448cd6b7eb61fbe8" - integrity sha512-EotkZs/lqgDdGsKzdmZuqu2ATgupQzhByUZ8oL3ElzCKDhXmgVLrX+WDe/StvrfB80h4EPOTElXuQifcfJwwFw== + resolved "https://codeload.github.com/connorjclark/quibble/tar.gz/b228a4ddbbad5061d36b465db2f364bb7c3291d3" dependencies: lodash "^4.17.21" resolve "^1.20.0"