-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
CLI.ts
527 lines (506 loc) · 16.6 KB
/
CLI.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/**
* @license
* Copyright 2023 Google Inc.
* SPDX-License-Identifier: Apache-2.0
*/
import {stdin as input, stdout as output} from 'process';
import * as readline from 'readline';
import ProgressBar from 'progress';
import type * as Yargs from 'yargs';
import yargs from 'yargs';
import {hideBin} from 'yargs/helpers';
import {
resolveBuildId,
type Browser,
BrowserPlatform,
type ChromeReleaseChannel,
} from './browser-data/browser-data.js';
import {Cache} from './Cache.js';
import {detectBrowserPlatform} from './detectPlatform.js';
import {install} from './install.js';
import {
computeExecutablePath,
computeSystemExecutablePath,
launch,
} from './launch.js';
interface InstallBrowser {
name: Browser;
buildId: string;
}
interface InstallArgs {
browser?: InstallBrowser;
path?: string;
platform?: BrowserPlatform;
baseUrl?: string;
installDeps?: boolean;
}
interface LaunchArgs {
browser: {
name: Browser;
buildId: string;
};
path?: string;
platform?: BrowserPlatform;
detached: boolean;
system: boolean;
}
interface ClearArgs {
path?: string;
}
interface ListArgs {
path?: string;
}
/**
* @public
*/
export class CLI {
#cachePath;
#rl?: readline.Interface;
#scriptName = '';
#allowCachePathOverride = true;
#pinnedBrowsers?: Partial<{
[key in Browser]: {
buildId: string;
skipDownload: boolean;
};
}>;
#prefixCommand?: {cmd: string; description: string};
constructor(
opts?:
| string
| {
cachePath?: string;
scriptName?: string;
prefixCommand?: {cmd: string; description: string};
allowCachePathOverride?: boolean;
pinnedBrowsers?: Partial<{
[key in Browser]: {
buildId: string;
skipDownload: boolean;
};
}>;
},
rl?: readline.Interface,
) {
if (!opts) {
opts = {};
}
if (typeof opts === 'string') {
opts = {
cachePath: opts,
};
}
this.#cachePath = opts.cachePath ?? process.cwd();
this.#rl = rl;
this.#scriptName = opts.scriptName ?? '@puppeteer/browsers';
this.#allowCachePathOverride = opts.allowCachePathOverride ?? true;
this.#pinnedBrowsers = opts.pinnedBrowsers;
this.#prefixCommand = opts.prefixCommand;
}
#defineBrowserParameter(yargs: Yargs.Argv<unknown>): void {
yargs.positional('browser', {
description:
'Which browser to install <browser>[@<buildId|latest>]. `latest` will try to find the latest available build. `buildId` is a browser-specific identifier such as a version or a revision.',
type: 'string',
coerce: (opt): InstallArgs['browser'] => {
return {
name: this.#parseBrowser(opt),
buildId: this.#parseBuildId(opt),
};
},
});
}
#definePlatformParameter(yargs: Yargs.Argv<unknown>): void {
yargs.option('platform', {
type: 'string',
desc: 'Platform that the binary needs to be compatible with.',
choices: Object.values(BrowserPlatform),
defaultDescription: 'Auto-detected',
});
}
#definePathParameter(yargs: Yargs.Argv<unknown>, required = false): void {
if (!this.#allowCachePathOverride) {
return;
}
yargs.option('path', {
type: 'string',
desc: 'Path to the root folder for the browser downloads and installation. The installation folder structure is compatible with the cache structure used by Puppeteer.',
defaultDescription: 'Current working directory',
...(required ? {} : {default: process.cwd()}),
});
if (required) {
yargs.demandOption('path');
}
}
async run(argv: string[]): Promise<void> {
const yargsInstance = yargs(hideBin(argv));
let target = yargsInstance.scriptName(this.#scriptName);
if (this.#prefixCommand) {
target = target.command(
this.#prefixCommand.cmd,
this.#prefixCommand.description,
yargs => {
return this.#build(yargs);
},
);
} else {
target = this.#build(target);
}
await target
.demandCommand(1)
.help()
.wrap(Math.min(120, yargsInstance.terminalWidth()))
.parse();
}
#build(yargs: Yargs.Argv<unknown>): Yargs.Argv<unknown> {
const latestOrPinned = this.#pinnedBrowsers ? 'pinned' : 'latest';
// If there are pinned browsers allow the positional arg to be optional
const browserArgType = this.#pinnedBrowsers ? '[browser]' : '<browser>';
return yargs
.command(
`install ${browserArgType}`,
'Download and install the specified browser. If successful, the command outputs the actual browser buildId that was installed and the absolute path to the browser executable (format: <browser>@<buildID> <path>).',
yargs => {
this.#defineBrowserParameter(yargs);
this.#definePlatformParameter(yargs);
this.#definePathParameter(yargs);
yargs.option('base-url', {
type: 'string',
desc: 'Base URL to download from',
});
if (this.#pinnedBrowsers) {
yargs.example('$0 install', 'Install all pinned browsers');
}
yargs.option('install-deps', {
type: 'boolean',
desc: 'Whether to attempt installing system dependencies (only supported on Linux, requires root privileges).',
default: false,
});
yargs.example(
'$0 install chrome',
`Install the ${latestOrPinned} available build of the Chrome browser.`,
);
yargs.example(
'$0 install chrome@latest',
'Install the latest available build for the Chrome browser.',
);
yargs.example(
'$0 install chrome@stable',
'Install the latest available build for the Chrome browser from the stable channel.',
);
yargs.example(
'$0 install chrome@beta',
'Install the latest available build for the Chrome browser from the beta channel.',
);
yargs.example(
'$0 install chrome@dev',
'Install the latest available build for the Chrome browser from the dev channel.',
);
yargs.example(
'$0 install chrome@canary',
'Install the latest available build for the Chrome Canary browser.',
);
yargs.example(
'$0 install chrome@115',
'Install the latest available build for Chrome 115.',
);
yargs.example(
'$0 install chromedriver@canary',
'Install the latest available build for ChromeDriver Canary.',
);
yargs.example(
'$0 install chromedriver@115',
'Install the latest available build for ChromeDriver 115.',
);
yargs.example(
'$0 install [email protected]',
'Install the latest available patch (115.0.5790.X) build for ChromeDriver.',
);
yargs.example(
'$0 install chrome-headless-shell',
'Install the latest available chrome-headless-shell build.',
);
yargs.example(
'$0 install chrome-headless-shell@beta',
'Install the latest available chrome-headless-shell build corresponding to the Beta channel.',
);
yargs.example(
'$0 install chrome-headless-shell@118',
'Install the latest available chrome-headless-shell 118 build.',
);
yargs.example(
'$0 install chromium@1083080',
'Install the revision 1083080 of the Chromium browser.',
);
yargs.example(
'$0 install firefox',
'Install the latest nightly available build of the Firefox browser.',
);
yargs.example(
'$0 install firefox@stable',
'Install the latest stable build of the Firefox browser.',
);
yargs.example(
'$0 install firefox@beta',
'Install the latest beta build of the Firefox browser.',
);
yargs.example(
'$0 install firefox@devedition',
'Install the latest devedition build of the Firefox browser.',
);
yargs.example(
'$0 install firefox@esr',
'Install the latest ESR build of the Firefox browser.',
);
yargs.example(
'$0 install firefox@nightly',
'Install the latest nightly build of the Firefox browser.',
);
yargs.example(
'$0 install firefox@stable_111.0.1',
'Install a specific version of the Firefox browser.',
);
yargs.example(
'$0 install firefox --platform mac',
'Install the latest Mac (Intel) build of the Firefox browser.',
);
if (this.#allowCachePathOverride) {
yargs.example(
'$0 install firefox --path /tmp/my-browser-cache',
'Install to the specified cache directory.',
);
}
},
async argv => {
const args = argv as unknown as InstallArgs;
if (this.#pinnedBrowsers && !args.browser) {
// Use allSettled to avoid scenarios that
// a browser may fail early and leave the other
// installation in a faulty state
const result = await Promise.allSettled(
Object.entries(this.#pinnedBrowsers).map(
async ([browser, options]) => {
if (options.skipDownload) {
return;
}
await this.#install({
...argv,
browser: {
name: browser as Browser,
buildId: options.buildId,
},
});
},
),
);
for (const install of result) {
if (install.status === 'rejected') {
throw install.reason;
}
}
} else {
await this.#install(args);
}
},
)
.command(
'launch <browser>',
'Launch the specified browser',
yargs => {
this.#defineBrowserParameter(yargs);
this.#definePlatformParameter(yargs);
this.#definePathParameter(yargs);
yargs.option('detached', {
type: 'boolean',
desc: 'Detach the child process.',
default: false,
});
yargs.option('system', {
type: 'boolean',
desc: 'Search for a browser installed on the system instead of the cache folder.',
default: false,
});
yargs.example(
'$0 launch [email protected]',
'Launch Chrome 115.0.5790.170',
);
yargs.example(
'$0 launch [email protected]',
'Launch the Firefox browser identified by the milestone 112.0a1.',
);
yargs.example(
'$0 launch [email protected] --detached',
'Launch the browser but detach the sub-processes.',
);
yargs.example(
'$0 launch chrome@canary --system',
'Try to locate the Canary build of Chrome installed on the system and launch it.',
);
},
async argv => {
const args = argv as unknown as LaunchArgs;
const executablePath = args.system
? computeSystemExecutablePath({
browser: args.browser.name,
// TODO: throw an error if not a ChromeReleaseChannel is provided.
channel: args.browser.buildId as ChromeReleaseChannel,
platform: args.platform,
})
: computeExecutablePath({
browser: args.browser.name,
buildId: args.browser.buildId,
cacheDir: args.path ?? this.#cachePath,
platform: args.platform,
});
launch({
executablePath,
detached: args.detached,
});
},
)
.command(
'clear',
this.#allowCachePathOverride
? 'Removes all installed browsers from the specified cache directory'
: `Removes all installed browsers from ${this.#cachePath}`,
yargs => {
this.#definePathParameter(yargs, true);
},
async argv => {
const args = argv as unknown as ClearArgs;
const cacheDir = args.path ?? this.#cachePath;
const rl = this.#rl ?? readline.createInterface({input, output});
rl.question(
`Do you want to permanently and recursively delete the content of ${cacheDir} (yes/No)? `,
answer => {
rl.close();
if (!['y', 'yes'].includes(answer.toLowerCase().trim())) {
console.log('Cancelled.');
return;
}
const cache = new Cache(cacheDir);
cache.clear();
console.log(`${cacheDir} cleared.`);
},
);
},
)
.command(
'list',
'List all installed browsers in the cache directory',
yargs => {
this.#definePathParameter(yargs);
yargs.example(
'$0 list',
'List all installed browsers in the cache directory',
);
if (this.#allowCachePathOverride) {
yargs.example(
'$0 list --path /tmp/my-browser-cache',
'List browsers installed in the specified cache directory',
);
}
},
async argv => {
const args = argv as unknown as ListArgs;
const cacheDir = args.path ?? this.#cachePath;
const cache = new Cache(cacheDir);
const browsers = cache.getInstalledBrowsers();
for (const browser of browsers) {
console.log(
`${browser.browser}@${browser.buildId} (${browser.platform}) ${browser.executablePath}`,
);
}
},
)
.demandCommand(1)
.help();
}
#parseBrowser(version: string): Browser {
return version.split('@').shift() as Browser;
}
#parseBuildId(version: string): string {
const parts = version.split('@');
return parts.length === 2
? parts[1]!
: this.#pinnedBrowsers
? 'pinned'
: 'latest';
}
async #install(args: InstallArgs) {
args.platform ??= detectBrowserPlatform();
if (!args.browser) {
throw new Error(`No browser arg proveded`);
}
if (!args.platform) {
throw new Error(`Could not resolve the current platform`);
}
if (args.browser.buildId === 'pinned') {
const options = this.#pinnedBrowsers?.[args.browser.name];
if (!options || !options.buildId) {
throw new Error(`No pinned version found for ${args.browser.name}`);
}
args.browser.buildId = options.buildId;
}
const originalBuildId = args.browser.buildId;
args.browser.buildId = await resolveBuildId(
args.browser.name,
args.platform,
args.browser.buildId,
);
await install({
browser: args.browser.name,
buildId: args.browser.buildId,
platform: args.platform,
cacheDir: args.path ?? this.#cachePath,
downloadProgressCallback: makeProgressCallback(
args.browser.name,
args.browser.buildId,
),
baseUrl: args.baseUrl,
buildIdAlias:
originalBuildId !== args.browser.buildId ? originalBuildId : undefined,
installDeps: args.installDeps,
});
console.log(
`${args.browser.name}@${args.browser.buildId} ${computeExecutablePath({
browser: args.browser.name,
buildId: args.browser.buildId,
cacheDir: args.path ?? this.#cachePath,
platform: args.platform,
})}`,
);
}
}
/**
* @public
*/
export function makeProgressCallback(
browser: Browser,
buildId: string,
): (downloadedBytes: number, totalBytes: number) => void {
let progressBar: ProgressBar;
let lastDownloadedBytes = 0;
return (downloadedBytes: number, totalBytes: number) => {
if (!progressBar) {
progressBar = new ProgressBar(
`Downloading ${browser} ${buildId} - ${toMegabytes(
totalBytes,
)} [:bar] :percent :etas `,
{
complete: '=',
incomplete: ' ',
width: 20,
total: totalBytes,
},
);
}
const delta = downloadedBytes - lastDownloadedBytes;
lastDownloadedBytes = downloadedBytes;
progressBar.tick(delta);
};
}
function toMegabytes(bytes: number) {
const mb = bytes / 1000 / 1000;
return `${Math.round(mb * 10) / 10} MB`;
}