launcher.ts
3.24 KB
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
import type { Browser, LaunchOptions } from 'playwright';
import { spawn } from 'child_process';
import { createRequire } from 'module';
import { dirname, join } from 'path';
import { logger } from '../../../../utils/logger';
const MISSING_EXECUTABLE_MESSAGE = "Executable doesn't exist";
/**
* Get the path to the locally installed playwright CLI.
* Uses Node.js module resolution to ensure the version matches the imported playwright.
*
* Note: We can't use require.resolve('playwright/cli') directly because
* the 'exports' field in playwright's package.json doesn't expose './cli'.
* Instead, we resolve the main entry and derive the cli.js path from it.
*/
function getLocalPlaywrightCliPath(): string {
const require = createRequire(import.meta.url);
const playwrightMain = require.resolve('playwright');
return join(dirname(playwrightMain), 'cli.js');
}
let installPromise: Promise<void> | null = null;
let installCompleted = false;
async function installChromiumBrowsers(): Promise<void> {
if (installCompleted) return;
if (!installPromise) {
logger.printInfoLog('Playwright Chromium 二进制缺失,正在自动安装…');
installPromise = new Promise((resolve, reject) => {
// NOTE: Avoid --with-deps here; it can try to install system packages on some platforms.
const cliPath = getLocalPlaywrightCliPath();
const child = spawn(process.execPath, [cliPath, 'install', 'chromium'], {
stdio: 'inherit',
env: process.env,
});
child.on('error', error => {
installPromise = null;
reject(error);
});
child.on('close', code => {
installPromise = null;
if (code === 0) {
installCompleted = true;
logger.printSuccessLog('Playwright Chromium 安装完成。');
resolve();
} else {
reject(new Error(`Playwright install exited with code ${code}`));
}
});
});
}
return installPromise;
}
function isMissingExecutableError(error: unknown): boolean {
return error instanceof Error && error.message.includes(MISSING_EXECUTABLE_MESSAGE);
}
export async function launchChromiumWithAutoInstall(options: LaunchOptions = {}): Promise<Browser> {
const launchOptions: LaunchOptions = { headless: true, ...options };
// Dynamic import to avoid load-time error if playwright is missing
const { chromium } = await import('playwright');
try {
return await chromium.launch(launchOptions);
} catch (error) {
if (isMissingExecutableError(error)) {
try {
await installChromiumBrowsers();
} catch (installError) {
throw new Error(
'Failed to auto-install Playwright browsers required for validation.\n' +
'Please run "npx playwright install chromium" or "pnpm exec playwright install chromium" manually and retry.\n' +
`Installer error: ${(installError as Error).message}`
);
}
return chromium.launch(launchOptions);
}
throw error;
}
}