forked from microsoft/playwright
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowserFactory.ts
More file actions
253 lines (228 loc) · 9.92 KB
/
Copy pathbrowserFactory.ts
File metadata and controls
253 lines (228 loc) · 9.92 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
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
/**
* Copyright (c) Microsoft Corporation.
*
* 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.
*/
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { playwright } from '../../inprocess';
import { registryDirectory } from '../../server/registry/index';
import { testDebug } from './log';
import { outputDir } from '../backend/context';
import { createExtensionBrowser } from './extensionContextFactory';
import { connectToBrowserAcrossVersions } from '../utils/connect';
import { serverRegistry } from '../../serverRegistry';
import { resolveExtensionOptions } from './config';
// eslint-disable-next-line no-restricted-imports
import { connectToBrowser } from '../../client/connect';
import type { CLIOptions, FullConfig } from './config';
import type { ClientInfo } from '../utils/mcp/server';
// eslint-disable-next-line no-restricted-imports
import type { Playwright } from '../../client/playwright';
import type * as playwrightTypes from '../../..';
import type { BrowserInfo } from '../../serverRegistry';
type BrowserWithInfo = {
browser: playwrightTypes.Browser,
browserInfo: BrowserInfo,
canBind: boolean,
ownership: 'attached' | 'own',
};
export async function createBrowserWithInfo(config: FullConfig, clientInfo: ClientInfo, cliOptions: CLIOptions): Promise<BrowserWithInfo> {
if (config.browser.remoteEndpoint)
return await createRemoteBrowser(config);
let browser: playwrightTypes.Browser;
let canBind = false;
let ownership: 'attached' | 'own' = 'own';
if (config.browser.cdpEndpoint) {
browser = await createCDPBrowser(config, clientInfo);
canBind = true;
ownership = 'attached';
} else if (config.browser.isolated) {
browser = await createIsolatedBrowser(config, clientInfo);
canBind = true;
ownership = 'own';
} else if (config.extension) {
const { channel, executablePath } = resolveExtensionOptions(cliOptions);
browser = await createExtensionBrowser(channel, executablePath, clientInfo.clientName);
ownership = 'attached';
} else {
browser = await createPersistentBrowser(config, clientInfo);
canBind = true;
ownership = 'own';
}
return { browser, browserInfo: browserInfo(browser, config), canBind, ownership };
}
export interface BrowserContextFactory {
contexts(clientInfo: ClientInfo): Promise<playwrightTypes.BrowserContext[]>;
createContext(clientInfo: ClientInfo): Promise<playwrightTypes.BrowserContext>;
}
function browserInfo(browser: playwrightTypes.Browser, config: FullConfig): BrowserInfo {
return {
// eslint-disable-next-line no-restricted-syntax
guid: (browser as any)._guid,
browserName: config.browser.browserName,
launchOptions: config.browser.launchOptions,
userDataDir: config.browser.userDataDir
};
}
async function createIsolatedBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
testDebug('create browser (isolated)');
const browserType = playwright[config.browser.browserName];
const tracesDir = await computeTracesDir(config, clientInfo);
const browser = await browserType.launch({
tracesDir,
...config.browser.launchOptions,
handleSIGINT: false,
handleSIGTERM: false,
}).catch(error => {
throwIfExecutableMissing(error, config);
throw error;
});
return browser;
}
async function createCDPBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
testDebug('create browser (cdp)');
const artifactsDir = await computeTracesDir(config, clientInfo);
const browser = await playwright.chromium.connectOverCDP(config.browser.cdpEndpoint!, {
headers: config.browser.cdpHeaders,
timeout: config.browser.cdpTimeout,
artifactsDir,
});
return browser;
}
async function createRemoteBrowser(config: FullConfig): Promise<BrowserWithInfo> {
testDebug('create browser (remote)');
// `remoteEndpoint` may be a plain URL string or a ConnectOptions object that
// carries additional fields such as `exposeNetwork`, `headers`, `slowMo`, and
// `timeout`. Normalize once so the rest of the function deals with a single
// shape.
const remote = config.browser.remoteEndpoint!;
const remoteOptions = typeof remote === 'string'
? { endpoint: remote }
: remote;
const descriptor = await serverRegistry.find(remoteOptions.endpoint);
if (descriptor) {
const browser = await connectToBrowserAcrossVersions(descriptor);
return {
browser,
browserInfo: {
guid: descriptor.browser.guid,
browserName: descriptor.browser.browserName,
launchOptions: descriptor.browser.launchOptions,
userDataDir: descriptor.browser.userDataDir
},
canBind: false,
ownership: 'attached'
};
}
const playwrightObject = playwright as Playwright;
// Use connectToBrowser instead of playwright[browserName].connect because we don't have browserName.
const browser = await connectToBrowser(playwrightObject, remoteOptions);
browser._connectToBrowserType(playwrightObject[browser._browserName], {}, undefined);
return { browser, browserInfo: browserInfo(browser, config), canBind: false, ownership: 'attached' };
}
async function createPersistentBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
testDebug('create browser (persistent)');
const userDataDir = config.browser.userDataDir ?? await createUserDataDir(config, clientInfo);
const tracesDir = await computeTracesDir(config, clientInfo);
if (await isProfileLocked5Times(userDataDir))
throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
const browserType = playwright[config.browser.browserName];
const configIgnoreDefaultArgs = config.browser.launchOptions?.ignoreDefaultArgs;
const launchOptions: playwrightTypes.LaunchOptions & playwrightTypes.BrowserContextOptions = {
tracesDir,
...config.browser.launchOptions,
...config.browser.contextOptions,
handleSIGINT: false,
handleSIGTERM: false,
ignoreDefaultArgs: configIgnoreDefaultArgs === true
? true
: [
'--disable-extensions',
...Array.isArray(configIgnoreDefaultArgs) ? configIgnoreDefaultArgs : [],
],
};
try {
const browserContext = await browserType.launchPersistentContext(userDataDir, launchOptions);
const browser = browserContext.browser()!;
return browser;
} catch (error: any) {
throwIfExecutableMissing(error, config);
if (error.message.includes('cannot open shared object file: No such file or directory')) {
const browserName = launchOptions.channel ?? config.browser.browserName;
throw new Error(`Missing system dependencies required to run browser ${browserName}. Install them with: sudo npx playwright install-deps ${browserName}`);
}
if (error.message.includes('ProcessSingleton') || error.message.includes('exitCode=21'))
throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
throw error;
}
}
async function createUserDataDir(config: FullConfig, clientInfo: ClientInfo) {
const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? registryDirectory;
const browserToken = config.browser.launchOptions?.channel ?? config.browser?.browserName;
// Hesitant putting hundreds of files into the user's workspace, so using it for hashing instead.
const rootPathToken = createHash(clientInfo.cwd);
const result = path.join(dir, `mcp-${browserToken}-${rootPathToken}`);
await fs.promises.mkdir(result, { recursive: true });
return result;
}
function createHash(data: string): string {
return crypto.createHash('sha256').update(data).digest('hex').slice(0, 7);
}
async function computeTracesDir(config: FullConfig, clientInfo: ClientInfo): Promise<string | undefined> {
return path.resolve(outputDir({ config, cwd: clientInfo.cwd }), 'traces');
}
async function isProfileLocked5Times(userDataDir: string): Promise<boolean> {
for (let i = 0; i < 5; i++) {
if (!isProfileLocked(userDataDir))
return false;
await new Promise(f => setTimeout(f, 1000));
}
return true;
}
export function isProfileLocked(userDataDir: string): boolean {
const lockFile = process.platform === 'win32' ? 'lockfile' : 'SingletonLock';
const lockPath = path.join(userDataDir, lockFile);
if (process.platform === 'win32') {
try {
const fd = fs.openSync(lockPath, 'r+');
fs.closeSync(fd);
return false;
} catch (e: any) {
return e.code !== 'ENOENT';
}
}
try {
const target = fs.readlinkSync(lockPath);
const pid = parseInt(target.split('-').pop() || '', 10);
if (isNaN(pid))
return false;
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function throwIfExecutableMissing(error: Error, config: FullConfig): void {
// The "Executable doesn't exist" prefix is shared by all managed binaries
// (browser, ffmpeg, winldd). Disambiguate by the path so the user is told
// which dependency to install.
if (!error.message.includes(`Executable doesn't exist`))
return;
const target = error.message.includes('ffmpeg') ? 'ffmpeg' : (config.browser.launchOptions?.channel ?? config.browser.browserName);
const label = target === 'ffmpeg' ? 'FFmpeg' : `Browser "${target}"`;
if (config.skillMode)
throw new Error(`${label} is not installed. Run \`playwright-cli install-browser ${target}\` to install`);
throw new Error(`${label} is not installed. Run \`npx @playwright/mcp install-browser ${target}\` to install`);
}