Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

misc: remove createCommonjsRefs #14004

Merged
merged 8 commits into from
Jun 9, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions build/build-bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import fs from 'fs';
import path from 'path';
import {execSync} from 'child_process';
import {createRequire} from 'module';

import esMain from 'es-main';
import {rollup} from 'rollup';
Expand All @@ -21,9 +22,8 @@ import PubAdsPlugin from 'lighthouse-plugin-publisher-ads/plugin.js';
import * as rollupPlugins from './rollup-plugins.js';
import Runner from '../lighthouse-core/runner.js';
import {LH_ROOT, readJson} from '../root.js';
import {createCommonjsRefs} from '../lighthouse-core/scripts/esm-utils.js';

const {require} = createCommonjsRefs(import.meta);
const require = createRequire(import.meta.url);

/** The commit hash for the current HEAD. */
const COMMIT_HASH = execSync('git rev-parse HEAD').toString().trim();
Expand Down
5 changes: 3 additions & 2 deletions build/build-treemap.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
* 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 {createRequire} from 'module';

import {GhPagesApp} from './gh-pages-app.js';
import {LH_ROOT} from '../root.js';
import {getIcuMessageIdParts} from '../shared/localization/format.js';
import locales from '../shared/localization/locales.js';
import {UIStrings} from '../treemap/app/src/util.js';
import {createCommonjsRefs} from '../lighthouse-core/scripts/esm-utils.js';

const {require} = createCommonjsRefs(import.meta);
const require = createRequire(import.meta.url);

/**
* Extract only the strings needed for treemap into
Expand Down
5 changes: 3 additions & 2 deletions build/build-viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
* 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 {createRequire} from 'module';

import {rollup} from 'rollup';

import * as rollupPlugins from './rollup-plugins.js';
import {GhPagesApp} from './gh-pages-app.js';
import {LH_ROOT} from '../root.js';
import {createCommonjsRefs} from '../lighthouse-core/scripts/esm-utils.js';

const {require} = createCommonjsRefs(import.meta);
const require = createRequire(import.meta.url);

async function buildReportGenerator() {
const bundle = await rollup({
Expand Down
4 changes: 2 additions & 2 deletions build/test/plugins/inline-fs-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@

import fs from 'fs';
import path from 'path';
import {createRequire} from 'module';

import {inlineFs} from '../../plugins/inline-fs.js';
import {LH_ROOT} from '../../../root.js';
import {createCommonjsRefs} from '../../../lighthouse-core/scripts/esm-utils.js';

const {require} = createCommonjsRefs(import.meta);
const require = createRequire(import.meta.url);

const filepath = `${LH_ROOT}/lighthouse-core/index.js`;

Expand Down
22 changes: 14 additions & 8 deletions lighthouse-core/scripts/esm-utils.js → esm-utils.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,38 @@
* 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';
// TODO(esmodules): rename to .js when root is type: module

import module from 'module';
import url from 'url';
import path from 'path';

const require = module.createRequire(import.meta.url);

/**
* Commonjs equivalent of `require.resolve`.
* @param {string} packageName
*/
function resolveModulePath(packageName) {
const require = module.createRequire(import.meta.url);
return require.resolve(packageName);
}

/**
* @param {ImportMeta} importMeta
*/
function createCommonjsRefs(importMeta) {
const require = module.createRequire(importMeta.url);
const filename = url.fileURLToPath(importMeta.url);
const dirname = path.dirname(filename);
return {require, __filename: filename, __dirname: dirname};
function getModuleName(importMeta) {
connorjclark marked this conversation as resolved.
Show resolved Hide resolved
return url.fileURLToPath(importMeta.url);
}

/**
* @param {ImportMeta} importMeta
*/
function getModuleDirectory(importMeta) {
return path.dirname(getModuleName(importMeta));
}

export {
resolveModulePath,
createCommonjsRefs,
getModuleName,
getModuleDirectory,
};
2 changes: 1 addition & 1 deletion lighthouse-core/scripts/cleanup-vuln-snapshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {readFileSync, writeFileSync} from 'fs';

import prettyJSONStringify from 'pretty-json-stringify';

import {resolveModulePath} from './esm-utils.js';
import {resolveModulePath} from '../../esm-utils.mjs';

const libDetectorSource = readFileSync(
resolveModulePath('js-library-detector/library/libraries.js'),
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/scripts/i18n/collect-strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ 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.js';
import {resolveModulePath} from '../../../esm-utils.mjs';

// 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
Expand Down
14 changes: 8 additions & 6 deletions lighthouse-core/test/config/config-helpers-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import path from 'path';
import {createRequire} from 'module';

import {jest} from '@jest/globals';

Expand All @@ -24,9 +25,10 @@ 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 {createCommonjsRefs} from '../../scripts/esm-utils.js';
import {getModuleDirectory} from '../../../esm-utils.mjs';

const {require, __dirname} = createCommonjsRefs(import.meta);
const require = createRequire(import.meta.url);
const moduleDir = getModuleDirectory(import.meta);

jest.mock('process', () => ({
cwd: () => jest.fn(),
Expand Down Expand Up @@ -347,7 +349,7 @@ describe('.resolveGathererToDefn', () => {
});

it('should find relative to configDir', () => {
const configDir = path.resolve(__dirname, '../../gather/');
const configDir = path.resolve(moduleDir, '../../gather/');
const result = resolveGathererToDefn('gatherers/image-elements', [], configDir);
expect(result).toEqual({
path: 'gatherers/image-elements',
Expand Down Expand Up @@ -377,7 +379,7 @@ describe('.resolveAuditsToDefns', () => {
});

it('should find relative to configDir', () => {
const configDir = path.resolve(__dirname, '../../');
const configDir = path.resolve(moduleDir, '../../');
const result = resolveAuditsToDefns(['audits/user-timings'], configDir);

expect(result).toEqual([
Expand Down Expand Up @@ -410,7 +412,7 @@ describe('.resolveAuditsToDefns', () => {
});

describe('.resolveModulePath', () => {
const configFixturePath = path.resolve(__dirname, '../fixtures/config');
const configFixturePath = path.resolve(moduleDir, '../fixtures/config');

beforeEach(() => {
process.cwd = jest.fn(() => configFixturePath);
Expand Down Expand Up @@ -438,7 +440,7 @@ describe('.resolveModulePath', () => {
});

describe('lighthouse and plugins are installed by npm', () => {
const pluginsDirectory = path.resolve(__dirname, '../fixtures/config/');
const pluginsDirectory = path.resolve(moduleDir, '../fixtures/config/');

// working directory/
// |-- node_modules/
Expand Down
6 changes: 3 additions & 3 deletions lighthouse-core/test/config/config-plugin-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@

import {strict as assert} from 'assert';

import {getModuleName} from '../../../esm-utils.mjs';
import ConfigPlugin from '../../config/config-plugin.js';
import i18n from '../../lib/i18n/i18n.js';
import {createCommonjsRefs} from '../../scripts/esm-utils.js';

const {__filename} = createCommonjsRefs(import.meta);
const moduleName = getModuleName(import.meta);

/**
* @param {any} val
Expand Down Expand Up @@ -72,7 +72,7 @@ describe('ConfigPlugin', () => {
title: 'this is a title',
description: 'this is a description',
};
const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);
const str_ = i18n.createMessageInstanceIdFn(moduleName, UIStrings);

const localizedPlugin = {
groups: {
Expand Down
27 changes: 15 additions & 12 deletions lighthouse-core/test/config/config-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import {strict as assert} from 'assert';
import path from 'path';
import {createRequire} from 'module';

import log from 'lighthouse-logger';

Expand All @@ -16,9 +17,11 @@ import Gatherer from '../../gather/gatherers/gatherer.js';
import Audit from '../../audits/audit.js';
import i18n from '../../lib/i18n/i18n.js';
import format from '../../../shared/localization/format.js';
import {createCommonjsRefs} from '../../scripts/esm-utils.js';
import {getModuleDirectory, getModuleName} from '../../../esm-utils.mjs';

const {require, __filename, __dirname} = createCommonjsRefs(import.meta);
const require = createRequire(import.meta.url);
const moduleName = getModuleName(import.meta);
const moduleDir = getModuleDirectory(import.meta);

describe('Config', () => {
let origConfig;
Expand Down Expand Up @@ -367,7 +370,7 @@ describe('Config', () => {
});

it('loads an audit relative to a config path', () => {
const configPath = __filename;
const configPath = moduleName;

return assert.doesNotThrow(_ => new Config({
audits: ['../fixtures/valid-custom-audit'],
Expand All @@ -387,7 +390,7 @@ describe('Config', () => {
it('loads an audit relative to the working directory', () => {
// Construct an audit URL relative to current working directory, regardless
// of where test was started from.
const absoluteAuditPath = path.resolve(__dirname, '../fixtures/valid-custom-audit');
const absoluteAuditPath = path.resolve(moduleDir, '../fixtures/valid-custom-audit');
assert.doesNotThrow(_ => require.resolve(absoluteAuditPath));
const relativePath = path.relative(process.cwd(), absoluteAuditPath);

Expand All @@ -398,7 +401,7 @@ describe('Config', () => {

it('throws but not for missing audit when audit has a dependency error', () => {
return assert.throws(_ => new Config({
audits: [path.resolve(__dirname, '../fixtures/invalid-audits/require-error.js')],
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.
Expand All @@ -407,7 +410,7 @@ describe('Config', () => {
});

it('throws when it finds invalid audits', () => {
const basePath = path.resolve(__dirname, '../fixtures/invalid-audits');
const basePath = path.resolve(moduleDir, '../fixtures/invalid-audits');
assert.throws(_ => new Config({
audits: [basePath + '/missing-audit'],
}), /audit\(\) method/);
Expand Down Expand Up @@ -961,7 +964,7 @@ describe('Config', () => {

describe('mergePlugins', () => {
// Include a configPath flag so that config.js looks for the plugins in the fixtures dir.
const configFixturePath = __dirname + '/../fixtures/config-plugins/';
const configFixturePath = moduleDir + '/../fixtures/config-plugins/';

it('should append audits', () => {
const configJson = {
Expand Down Expand Up @@ -1333,7 +1336,7 @@ describe('Config', () => {
});

it('loads gatherers from custom paths', () => {
const customPath = path.resolve(__dirname, '../fixtures/valid-custom-gatherer');
const customPath = path.resolve(moduleDir, '../fixtures/valid-custom-gatherer');
const gatherer = loadGatherer(customPath);
assert.equal(gatherer.instance.name, 'CustomGatherer');
assert.equal(typeof gatherer.instance.beforePass, 'function');
Expand All @@ -1342,7 +1345,7 @@ describe('Config', () => {
it('loads a gatherer relative to a config path', () => {
const config = new Config({
passes: [{gatherers: ['../fixtures/valid-custom-gatherer']}],
}, {configPath: __filename});
}, {configPath: moduleName});
const gatherer = config.passes[0].gatherers[0];

assert.equal(gatherer.instance.name, 'CustomGatherer');
Expand Down Expand Up @@ -1385,7 +1388,7 @@ describe('Config', () => {
it('loads a gatherer relative to the working directory', () => {
// Construct a gatherer URL relative to current working directory,
// regardless of where test was started from.
const absoluteGathererPath = path.resolve(__dirname, '../fixtures/valid-custom-gatherer');
const absoluteGathererPath = path.resolve(moduleDir, '../fixtures/valid-custom-gatherer');
assert.doesNotThrow(_ => require.resolve(absoluteGathererPath));
const relativeGathererPath = path.relative(process.cwd(), absoluteGathererPath);

Expand All @@ -1395,7 +1398,7 @@ describe('Config', () => {
});

it('throws but not for missing gatherer when it has a dependency error', () => {
const gathererPath = path.resolve(__dirname, '../fixtures/invalid-gatherers/require-error');
const gathererPath = path.resolve(moduleDir, '../fixtures/invalid-gatherers/require-error');
return assert.throws(_ => loadGatherer(gathererPath),
function(err) {
// We're expecting not to find parent class Gatherer, so only reject on
Expand All @@ -1411,7 +1414,7 @@ describe('Config', () => {
});

it('throws for invalid gatherers', () => {
const root = path.resolve(__dirname, '../fixtures/invalid-gatherers');
const root = path.resolve(moduleDir, '../fixtures/invalid-gatherers');

assert.throws(_ => loadGatherer(`${root}/missing-before-pass`),
/beforePass\(\) method/);
Expand Down
4 changes: 2 additions & 2 deletions lighthouse-core/test/gather/gather-runner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import {strict as assert} from 'assert';
import {createRequire} from 'module';

import {jest} from '@jest/globals';

Expand All @@ -25,9 +26,8 @@ import {
fnAny,
} from '../test-utils.js';
import fakeDriver from './fake-driver.js';
import {createCommonjsRefs} from '../../scripts/esm-utils.js';

const {require} = createCommonjsRefs(import.meta);
const require = createRequire(import.meta.url);

/**
* Same as jest.requireMock(), but uses `any` instead of `unknown`.
Expand Down
12 changes: 6 additions & 6 deletions lighthouse-core/test/lib/asset-saver-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import traceEvents from '../fixtures/traces/progressive-app.json';
import dbwTrace from '../results/artifacts/defaultPass.trace.json';
import dbwResults from '../results/sample_v2.json';
import Audit from '../../audits/audit.js';
import {createCommonjsRefs} from '../../scripts/esm-utils.js';
import {getModuleDirectory} from '../../../esm-utils.mjs';
import fullTraceObj from '../fixtures/traces/progressive-app-m60.json';
import devtoolsLog from '../fixtures/traces/progressive-app-m60.devtools.log.json';

const {__dirname} = createCommonjsRefs(import.meta);
const moduleDir = getModuleDirectory(import.meta);

// deepStrictEqual can hang on a full trace, we assert trace same-ness like so
function assertTraceEventsEqual(traceEventsA, traceEventsB) {
Expand Down Expand Up @@ -214,7 +214,7 @@ describe('asset-saver helper', () => {

describe('loadArtifacts', () => {
it('loads artifacts from disk', async () => {
const artifactsPath = __dirname + '/../fixtures/artifacts/perflog/';
const artifactsPath = moduleDir + '/../fixtures/artifacts/perflog/';
const artifacts = await assetSaver.loadArtifacts(artifactsPath);
assert.strictEqual(artifacts.LighthouseRunWarnings.length, 2);
assert.strictEqual(artifacts.URL.requestedUrl, 'https://www.reddit.com/r/nba');
Expand All @@ -224,14 +224,14 @@ describe('asset-saver helper', () => {
});

describe('JSON serialization', () => {
const outputPath = __dirname + '/json-serialization-test-data/';
const outputPath = moduleDir + '/json-serialization-test-data/';

afterEach(() => {
fs.rmSync(outputPath, {recursive: true, force: true});
});

it('round trips saved artifacts', async () => {
const artifactsPath = __dirname + '/../results/artifacts/';
const artifactsPath = moduleDir + '/../results/artifacts/';
const originalArtifacts = await assetSaver.loadArtifacts(artifactsPath);

await assetSaver.saveArtifacts(originalArtifacts, outputPath);
Expand All @@ -248,7 +248,7 @@ describe('asset-saver helper', () => {
const existingDevtoolslogPath = `${outputPath}/bestPass.devtoolslog.json`;
fs.writeFileSync(existingDevtoolslogPath, '[]');

const artifactsPath = __dirname + '/../results/artifacts/';
const artifactsPath = moduleDir + '/../results/artifacts/';
const originalArtifacts = await assetSaver.loadArtifacts(artifactsPath);

await assetSaver.saveArtifacts(originalArtifacts, outputPath);
Expand Down
Loading