Skip to content

Commit ce65153

Browse files
committed
Refactor installation file
1 parent 5d85833 commit ce65153

1 file changed

Lines changed: 78 additions & 56 deletions

File tree

install.js

Lines changed: 78 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
'use strict';
22
// @ts-check
33

4-
const fs = require('fs');
4+
const fs = require('node:fs');
55
const helper = require('./lib/chromedriver');
66
const axios = require('axios');
7-
const path = require('path');
8-
const child_process = require('child_process');
9-
const os = require('os');
10-
const url = require('url');
11-
const https = require('https');
12-
const { promisify } = require('util');
13-
const { finished } = require('stream');
7+
const path = require('node:path');
8+
const child_process = require('node:child_process');
9+
const os = require('node:os');
10+
const url = require('node:url');
11+
const https = require('node:https');
12+
const { promisify } = require('node:util');
13+
const { finished } = require('node:stream');
1414
const extractZip = require('extract-zip');
1515
const { getChromeVersion } = require('@testim/chrome-version');
1616
const HttpsProxyAgent = require('https-proxy-agent');
@@ -19,57 +19,51 @@ const { compareVersions } = require('compare-versions');
1919

2020
const finishedAsync = promisify(finished);
2121

22-
const skipDownload = process.env.npm_config_chromedriver_skip_download || process.env.CHROMEDRIVER_SKIP_DOWNLOAD;
23-
if (skipDownload === 'true') {
22+
const skipDownload = (process.env.npm_config_chromedriver_skip_download || process.env.CHROMEDRIVER_SKIP_DOWNLOAD) === 'true';
23+
if (skipDownload) {
2424
console.log('Found CHROMEDRIVER_SKIP_DOWNLOAD variable, skipping installation.');
2525
process.exit(0);
2626
}
2727

28-
const libPath = path.join(__dirname, 'lib', 'chromedriver');
29-
let cdnUrl = process.env.npm_config_chromedriver_cdnurl || process.env.CHROMEDRIVER_CDNURL || 'https://chromedriver.storage.googleapis.com';
30-
const configuredfilePath = process.env.npm_config_chromedriver_filepath || process.env.CHROMEDRIVER_FILEPATH;
31-
32-
// adapt http://chromedriver.storage.googleapis.com/
33-
cdnUrl = cdnUrl.replace(/\/+$/, '');
34-
const detect_chromedriver_version = process.env.npm_config_detect_chromedriver_version || process.env.DETECT_CHROMEDRIVER_VERSION;
35-
const include_chromium = (process.env.npm_config_include_chromium || process.env.INCLUDE_CHROMIUM) === 'true';
36-
let chromedriver_version = process.env.npm_config_chromedriver_version || process.env.CHROMEDRIVER_VERSION || helper.version;
37-
let chromedriverBinaryFilePath;
38-
let downloadedFile = '';
39-
let platform = '';
40-
4128
(async function install() {
29+
let cdnUrl = process.env.npm_config_chromedriver_cdnurl || process.env.CHROMEDRIVER_CDNURL || 'https://chromedriver.storage.googleapis.com';
30+
// adapt http://chromedriver.storage.googleapis.com/
31+
cdnUrl = cdnUrl.replace(/\/+$/, '');
32+
let chromedriverVersion = process.env.npm_config_chromedriver_version || process.env.CHROMEDRIVER_VERSION || helper.version;
33+
const detectChromedriverVersion = (process.env.npm_config_detect_chromedriver_version || process.env.DETECT_CHROMEDRIVER_VERSION) === 'true';
4234
try {
43-
if (detect_chromedriver_version === 'true') {
35+
if (detectChromedriverVersion) {
36+
const includeChromium = (process.env.npm_config_include_chromium || process.env.INCLUDE_CHROMIUM) === 'true';
4437
// Refer http://chromedriver.chromium.org/downloads/version-selection
45-
const chromeVersion = await getChromeVersion(include_chromium);
38+
const chromeVersion = await getChromeVersion(includeChromium);
4639
console.log("Your Chrome version is " + chromeVersion);
4740
const versionMatch = /^(.*?)\.\d+$/.exec(chromeVersion);
4841
if (versionMatch) {
4942
const chromeVersionWithoutPatch = versionMatch[1];
50-
await getChromeDriverVersion(getRequestOptions(cdnUrl + '/LATEST_RELEASE_' + chromeVersionWithoutPatch));
51-
console.log("Compatible ChromeDriver version is " + chromedriver_version);
43+
chromedriverVersion = await getChromeDriverVersion(getRequestOptions(cdnUrl + '/LATEST_RELEASE_' + chromeVersionWithoutPatch));
44+
console.log("Compatible ChromeDriver version is " + chromedriverVersion);
5245
}
5346
}
54-
if (chromedriver_version === 'LATEST') {
55-
await getChromeDriverVersion(getRequestOptions(`${cdnUrl}/LATEST_RELEASE`));
47+
if (chromedriverVersion === 'LATEST') {
48+
chromedriverVersion = await getChromeDriverVersion(getRequestOptions(`${cdnUrl}/LATEST_RELEASE`));
5649
} else {
57-
const latestReleaseForVersionMatch = chromedriver_version.match(/LATEST_(\d+)/);
50+
const latestReleaseForVersionMatch = chromedriverVersion.match(/LATEST_(\d+)/);
5851
if (latestReleaseForVersionMatch) {
5952
const majorVersion = latestReleaseForVersionMatch[1];
60-
await getChromeDriverVersion(getRequestOptions(`${cdnUrl}/LATEST_RELEASE_${majorVersion}`));
53+
chromedriverVersion = await getChromeDriverVersion(getRequestOptions(`${cdnUrl}/LATEST_RELEASE_${majorVersion}`));
6154
}
6255
}
63-
platform = validatePlatform();
64-
const tmpPath = findSuitableTempDirectory();
56+
const tmpPath = findSuitableTempDirectory(chromedriverVersion);
6557
const chromedriverBinaryFileName = process.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver';
66-
chromedriverBinaryFilePath = path.resolve(tmpPath, chromedriverBinaryFileName);
67-
const chromedriverIsAvailable = await verifyIfChromedriverIsAvailableAndHasCorrectVersion();
58+
const chromedriverBinaryFilePath = path.resolve(tmpPath, chromedriverBinaryFileName);
59+
const chromedriverIsAvailable = await verifyIfChromedriverIsAvailableAndHasCorrectVersion(chromedriverVersion, chromedriverBinaryFilePath);
6860
if (!chromedriverIsAvailable) {
6961
console.log('Current existing ChromeDriver binary is unavailable, proceeding with download and extraction.');
70-
await downloadFile(tmpPath);
71-
await extractDownload(tmpPath);
62+
const platform = validatePlatform(chromedriverVersion);
63+
const downloadedFile = await downloadFile(tmpPath, chromedriverVersion, platform, cdnUrl, detectChromedriverVersion);
64+
await extractDownload(tmpPath, chromedriverBinaryFilePath, downloadedFile);
7265
}
66+
const libPath = path.join(__dirname, 'lib', 'chromedriver');
7367
await copyIntoPlace(tmpPath, libPath);
7468
fixFilePermissions();
7569
console.log('Done. ChromeDriver binary available at', helper.path);
@@ -79,7 +73,11 @@ let platform = '';
7973
}
8074
})();
8175

82-
function validatePlatform() {
76+
/**
77+
* @param {string} chromedriverVersion
78+
* @returns {string}
79+
*/
80+
function validatePlatform(chromedriverVersion) {
8381
/** @type string */
8482
let thePlatform = process.platform;
8583
if (thePlatform === 'linux') {
@@ -90,7 +88,7 @@ function validatePlatform() {
9088
process.exit(1);
9189
}
9290
} else if (thePlatform === 'darwin' || thePlatform === 'freebsd') {
93-
const osxPlatform = getMacOsRealArch();
91+
const osxPlatform = getMacOsRealArch(chromedriverVersion);
9492

9593
if (!osxPlatform) {
9694
console.log('Only Mac 64 bits supported.');
@@ -106,23 +104,35 @@ function validatePlatform() {
106104
return thePlatform;
107105
}
108106

109-
async function downloadFile(dirToLoadTo) {
110-
if (detect_chromedriver_version !== 'true' && configuredfilePath) {
111-
downloadedFile = configuredfilePath;
112-
console.log('Using file: ', downloadedFile);
113-
return;
107+
/**
108+
* @param {string} dirToLoadTo
109+
* @param {string} chromedriverVersion
110+
* @param {string} platform
111+
* @param {string} cdnUrl
112+
* @param {boolean} detectChromedriverVersion
113+
*/
114+
async function downloadFile(dirToLoadTo, chromedriverVersion, platform, cdnUrl, detectChromedriverVersion) {
115+
const configuredfilePath = process.env.npm_config_chromedriver_filepath || process.env.CHROMEDRIVER_FILEPATH;
116+
if (detectChromedriverVersion && configuredfilePath) {
117+
console.log('Using file: ', configuredfilePath);
118+
return configuredfilePath;
114119
} else {
115120
const fileName = `chromedriver_${platform}.zip`;
116121
const tempDownloadedFile = path.resolve(dirToLoadTo, fileName);
117-
downloadedFile = tempDownloadedFile;
118-
const formattedDownloadUrl = `${cdnUrl}/${chromedriver_version}/${fileName}`;
122+
let downloadedFile = tempDownloadedFile;
123+
const formattedDownloadUrl = `${cdnUrl}/${chromedriverVersion}/${fileName}`;
119124
console.log('Downloading from file: ', formattedDownloadUrl);
120125
console.log('Saving to file:', downloadedFile);
121126
await requestBinary(getRequestOptions(formattedDownloadUrl), downloadedFile);
127+
return downloadedFile;
122128
}
123129
}
124130

125-
function verifyIfChromedriverIsAvailableAndHasCorrectVersion() {
131+
/**
132+
* @param {string} chromedriverVersion
133+
* @param {string} chromedriverBinaryFilePath
134+
*/
135+
function verifyIfChromedriverIsAvailableAndHasCorrectVersion(chromedriverVersion, chromedriverBinaryFilePath) {
126136
if (!fs.existsSync(chromedriverBinaryFilePath))
127137
return Promise.resolve(false);
128138
const forceDownload = process.env.npm_config_chromedriver_force_download === 'true' || process.env.CHROMEDRIVER_FORCE_DOWNLOAD === 'true';
@@ -142,7 +152,7 @@ function verifyIfChromedriverIsAvailableAndHasCorrectVersion() {
142152
const parts = str.split(' ');
143153
if (parts.length < 3)
144154
return deferred.resolve(false);
145-
if (parts[1].startsWith(chromedriver_version)) {
155+
if (parts[1].startsWith(chromedriverVersion)) {
146156
console.log(`ChromeDriver is already available at '${chromedriverBinaryFilePath}'.`);
147157
return deferred.resolve(true);
148158
}
@@ -155,7 +165,10 @@ function verifyIfChromedriverIsAvailableAndHasCorrectVersion() {
155165
return deferred.promise;
156166
}
157167

158-
function findSuitableTempDirectory() {
168+
/**
169+
* @param {string} chromedriverVersion
170+
*/
171+
function findSuitableTempDirectory(chromedriverVersion) {
159172
const now = Date.now();
160173
const candidateTmpDirs = [
161174
process.env.npm_config_tmp,
@@ -167,7 +180,7 @@ function findSuitableTempDirectory() {
167180

168181
for (const tempDir of candidateTmpDirs) {
169182
if (!tempDir) continue;
170-
const namespace = chromedriver_version;
183+
const namespace = chromedriverVersion;
171184
const candidatePath = path.join(tempDir, namespace, 'chromedriver');
172185
try {
173186
fs.mkdirSync(candidatePath, { recursive: true });
@@ -242,15 +255,16 @@ function getRequestOptions(downloadPath) {
242255
}
243256

244257
/**
245-
*
246258
* @param {import('axios').AxiosRequestConfig} requestOptions
259+
* @returns {Promise<string>}
247260
*/
248261
async function getChromeDriverVersion(requestOptions) {
249262
console.log('Finding Chromedriver version.');
250263
// @ts-expect-error
251264
const response = await axios.request(requestOptions);
252-
chromedriver_version = response.data.trim();
253-
console.log(`Chromedriver version is ${chromedriver_version}.`);
265+
const chromedriverVersion = response.data.trim();
266+
console.log(`Chromedriver version is ${chromedriverVersion}.`);
267+
return chromedriverVersion;
254268
}
255269

256270
/**
@@ -296,7 +310,12 @@ async function requestBinary(requestOptions, filePath) {
296310
});
297311
}
298312

299-
async function extractDownload(dirToExtractTo) {
313+
/**
314+
* @param {string} dirToExtractTo
315+
* @param {string} chromedriverBinaryFilePath
316+
* @param {string} downloadedFile
317+
*/
318+
async function extractDownload(dirToExtractTo, chromedriverBinaryFilePath, downloadedFile) {
300319
if (path.extname(downloadedFile) !== '.zip') {
301320
fs.copyFileSync(downloadedFile, chromedriverBinaryFilePath);
302321
console.log('Skipping zip extraction - binary file found.');
@@ -345,9 +364,12 @@ function fixFilePermissions() {
345364
}
346365
}
347366

348-
function getMacOsRealArch() {
367+
/**
368+
* @param {string} chromedriverVersion
369+
*/
370+
function getMacOsRealArch(chromedriverVersion) {
349371
if (process.arch === 'arm64' || isEmulatedRosettaEnvironment()) {
350-
if (compareVersions(chromedriver_version, '106.0.5249.61') < 0) {
372+
if (compareVersions(chromedriverVersion, '106.0.5249.61') < 0) {
351373
return 'mac64_m1';
352374
}
353375

0 commit comments

Comments
 (0)