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

upgrade node, various dependencies and build as ES modules #261

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
17 changes: 9 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"type": "module",
"name": "chrome-launcher",
"main": "./dist/index.js",
"engines": {
"node": ">=12.13.0"
"node": ">=14.15.0"
},
"scripts": {
"build": "tsc",
"dev": "tsc -w",
"test": "mocha --require ts-node/register --reporter=dot test/**/*-test.ts --timeout=10000",
"test": "TS_NODE_FILES=true node ./node_modules/mocha/bin/mocha --loader=ts-node/esm --reporter=dot test/**/*-test.ts --timeout=10000",
"test-formatting": "test/check-formatting.sh",
"format": "scripts/format.sh",
"type-check": "tsc --allowJs --checkJs --noEmit --target es2019 *.js",
Expand All @@ -17,19 +18,19 @@
"print-chrome-path": "bin/print-chrome-path.js"
},
"devDependencies": {
"@types/mocha": "^8.0.4",
"@types/mocha": "^9.1.0",
"@types/sinon": "^9.0.1",
"clang-format": "^1.0.50",
"mocha": "^8.2.1",
"sinon": "^9.0.1",
"ts-node": "^9.1.0",
"typescript": "^4.1.2"
"mocha": "^9.2.1",
"sinon": "^13.0.1",
"ts-node": "^10.7.0",
"typescript": "^4.6.2"
},
"dependencies": {
"@types/node": "*",
"escape-string-regexp": "^4.0.0",
"is-wsl": "^2.2.0",
"lighthouse-logger": "^1.0.0"
"lighthouse-logger": "^1.3.0"
},
"version": "0.15.0",
"types": "./dist/index.d.ts",
Expand Down
10 changes: 5 additions & 5 deletions src/chrome-finder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
*/
'use strict';

import fs = require('fs');
import path = require('path');
import fs from 'fs';
import path from 'path';
import {homedir} from 'os';
import {execSync, execFileSync} from 'child_process';
import escapeRegExp = require('escape-string-regexp');
const log = require('lighthouse-logger');
import escapeRegExp from 'escape-string-regexp';
import log from 'lighthouse-logger';

import {getWSLLocalAppDataPath, toWSLPath, ChromePathNotSetError} from './utils';
import {getWSLLocalAppDataPath, toWSLPath, ChromePathNotSetError} from './utils.js';

const newLineRegex = /\r?\n/;

Expand Down
41 changes: 20 additions & 21 deletions src/chrome-launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
*/
'use strict';

import * as childProcess from 'child_process';
import * as fs from 'fs';
import * as net from 'net';
import * as chromeFinder from './chrome-finder';
import {getRandomPort} from './random-port';
import {DEFAULT_FLAGS} from './flags';
import {makeTmpDir, defaults, delay, getPlatform, toWin32Path, InvalidUserDataDirectoryError, UnsupportedPlatformError, ChromeNotInstalledError} from './utils';
import childProcess from 'child_process';
import fs from 'fs';
import net from 'net';
import {ChildProcess} from 'child_process';
const log = require('lighthouse-logger');
import log from 'lighthouse-logger';
import * as chromeFinder from './chrome-finder.js';
import {getRandomPort} from './random-port.js';
import {DEFAULT_FLAGS} from './flags.js';
import {makeTmpDir, defaults, delay, getPlatform, toWin32Path, InvalidUserDataDirectoryError, UnsupportedPlatformError, ChromeNotInstalledError} from './utils.js';

const spawn = childProcess.spawn;
const execSync = childProcess.execSync;
const isWsl = getPlatform() === 'wsl';
Expand Down Expand Up @@ -94,23 +95,22 @@ function getChromePath(): string {
}

async function killAll(): Promise<Array<Error>> {
let errors = [];
let errors: Error[] = [];
for (const instance of instances) {
try {
await instance.kill();
// only delete if kill did not error
// this means erroring instances remain in the Set
instances.delete(instance);
} catch (err) {
} catch (err: any) {
errors.push(err);
}
}
return errors;
}

class Launcher {
private tmpDirandPidFileReady = false;
private pidFile: string;
private hasPrepared = false;
private startingUrl: string;
private outFile?: number;
private errFile?: number;
Expand Down Expand Up @@ -213,13 +213,9 @@ class Launcher {

this.setBrowserPrefs();

// fix for Node4
// you can't pass a fd to fs.writeFileSync
this.pidFile = `${this.userDataDir}/chrome.pid`;

log.verbose('ChromeLauncher', `created ${this.userDataDir}`);

this.tmpDirandPidFileReady = true;
this.hasPrepared = true;
}

private setBrowserPrefs() {
Expand All @@ -239,7 +235,7 @@ class Launcher {
// create new Preference file
this.fs.writeFileSync(preferenceFile, JSON.stringify({...this.prefs}), 'utf-8');
}
} catch (err) {
} catch (err: any) {
log.log('ChromeLauncher', `Failed to set browser prefs: ${err.message}`);
}
}
Expand All @@ -266,7 +262,7 @@ class Launcher {
this.chromePath = installation;
}

if (!this.tmpDirandPidFileReady) {
if (!this.hasPrepared) {
this.prepare();
}

Expand Down Expand Up @@ -298,7 +294,10 @@ class Launcher {
this.chrome = chrome;

if (chrome.pid) {
this.fs.writeFileSync(this.pidFile, chrome.pid.toString());
// fix for Node4
// you can't pass a fd to fs.writeFileSync
const pidFile = `${this.userDataDir}/chrome.pid`;
this.fs.writeFileSync(pidFile, chrome.pid.toString());
}

log.verbose('ChromeLauncher', `Chrome running with pid ${chrome.pid} on port ${this.port}.`);
Expand Down Expand Up @@ -391,7 +390,7 @@ class Launcher {
process.kill(-this.chrome.pid);
}
}
} catch (err) {
} catch (err: any) {
const message = `Chrome could not be killed ${err.message}`;
log.warn('ChromeLauncher', message);
reject(new Error(message));
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './chrome-launcher';
export * from './chrome-launcher.js';
11 changes: 8 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@
import {join} from 'path';
import {execSync, execFileSync} from 'child_process';
import {mkdirSync} from 'fs';
import isWsl = require('is-wsl');
import isWsl from 'is-wsl';

let execFileSync_ = execFileSync;
export function __testInjectExecFileSyncStub(execFileSyncStub: any) {
execFileSync_ = execFileSyncStub;
}

export const enum LaunchErrorCodes {
ERR_LAUNCHER_PATH_NOT_SET = 'ERR_LAUNCHER_PATH_NOT_SET',
Expand Down Expand Up @@ -91,15 +96,15 @@ export function toWin32Path(dir: string = ''): string {
}

try {
return execFileSync('wslpath', ['-w', dir]).toString().trim();
return execFileSync_('wslpath', ['-w', dir]).toString().trim();
} catch {
return toWinDirFormat(dir);
}
}

export function toWSLPath(dir: string, fallback: string): string {
try {
return execFileSync('wslpath', ['-u', dir]).toString().trim();
return execFileSync_('wslpath', ['-u', dir]).toString().trim();
} catch {
return fallback;
}
Expand Down
8 changes: 4 additions & 4 deletions test/chrome-launcher-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
*/
'use strict';

import {Launcher, launch, killAll, Options, getChromePath} from '../src/chrome-launcher';
import {DEFAULT_FLAGS} from '../src/flags';
import {Launcher, launch, killAll, Options, getChromePath} from '../src/chrome-launcher.js';
import {DEFAULT_FLAGS} from '../src/flags.js';

import {spy, stub} from 'sinon';
import * as assert from 'assert';
import assert from 'assert';
import log from 'lighthouse-logger';

const log = require('lighthouse-logger');
const fsMock = {
openSync: () => {},
closeSync: () => {},
Expand Down
7 changes: 3 additions & 4 deletions test/launch-signature-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@

'use strict';

import {launch} from '../src/';
import * as assert from 'assert';
import {launch} from '../src/index.js';
import assert from 'assert';
import log from 'lighthouse-logger';

const log = require('lighthouse-logger');
describe('Launcher', () => {

beforeEach(() => {
log.setLevel('error');
});
Expand Down
4 changes: 2 additions & 2 deletions test/random-port-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
*/
'use strict';

import * as assert from 'assert';
import {getRandomPort} from '../src/random-port';
import assert from 'assert';
import {getRandomPort} from '../src/random-port.js';

describe('Random port generation', () => {
it('generates a valid random port number', async () => {
Expand Down
7 changes: 7 additions & 0 deletions test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../tsconfig.json",
"include": [
"*-test.ts",
"../types"
]
}
23 changes: 16 additions & 7 deletions test/utils-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,20 @@
*/
'use strict';

import * as assert from 'assert';
import { toWin32Path, toWSLPath, getWSLLocalAppDataPath } from '../src/utils';
import * as sinon from 'sinon';
import * as child_process from 'child_process';
import assert from 'assert';
import { toWin32Path, toWSLPath, getWSLLocalAppDataPath, __testInjectExecFileSyncStub } from '../src/utils.js';
import sinon from 'sinon';
import child_process from 'child_process';

const execFileSyncStub = sinon.stub(child_process, 'execFileSync').callThrough();

const asBuffer = (str: string): Buffer => Buffer.from(str, 'utf-8');

describe('toWin32Path', () => {
beforeEach(() => execFileSyncStub.reset());
beforeEach(() => {
execFileSyncStub.reset();
__testInjectExecFileSyncStub(execFileSyncStub);
});

it('calls toWin32Path -w', () => {
execFileSyncStub.returns(asBuffer(''));
Expand Down Expand Up @@ -66,7 +69,10 @@ describe('toWin32Path', () => {
})

describe('toWSLPath', () => {
beforeEach(() => execFileSyncStub.reset());
beforeEach(() => {
execFileSyncStub.reset();
__testInjectExecFileSyncStub(execFileSyncStub);
});

it('calls wslpath -u', () => {
execFileSyncStub.returns(asBuffer(''));
Expand Down Expand Up @@ -95,7 +101,10 @@ describe('toWSLPath', () => {
})

describe('getWSLLocalAppDataPath', () => {
beforeEach(() => execFileSyncStub.reset());
beforeEach(() => {
execFileSyncStub.reset();
__testInjectExecFileSyncStub(execFileSyncStub);
});

it('transforms it to a Linux path using wslpath', () => {
execFileSyncStub.returns(asBuffer('/c/folder/'));
Expand Down
19 changes: 9 additions & 10 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"module": "ES2020",
"moduleResolution": "node",
"outDir": "dist",
"target": "es2019",
"target": "es2020",
"declaration": true,
"noImplicitAny": true,
"inlineSourceMap": true,
"noEmitOnError": false,
"strictNullChecks": true,
"strict": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true
"noUnusedParameters": true,
"allowSyntheticDefaultImports": true,
},
"exclude": [
"node_modules"
],
"include": [
"src"
]
"src",
"types",
],
}
33 changes: 33 additions & 0 deletions types/lighthouse-logger.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @license Copyright 2017 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.
*/

declare module 'lighthouse-logger' {
interface Status {
msg: string;
id: string;
args?: any[];
}
export function setLevel(level: string): void;
export function formatProtocol(prefix: string, data: Object, level?: string): void;
export function log(title: string, ...args: any[]): void;
export function warn(title: string, ...args: any[]): void;
export function error(title: string, ...args: any[]): void;
export function verbose(title: string, ...args: any[]): void;
export function time(status: Status, level?: string): void;
export function timeEnd(status: Status, level?: string): void;
export function reset(): string;
export const cross: string;
export const dim: string;
export const tick: string;
export const bold: string;
export const purple: string;
export function redify(message: any): string;
export function greenify(message: any): string;
/** Retrieves and clears all stored time entries */
export function takeTimeEntries(): PerformanceEntry[];
export function getTimeEntries(): PerformanceEntry[];
export const events: import('events').EventEmitter;
}
Loading