2019-12-19 16:53:24 -08:00
|
|
|
/**
|
|
|
|
* Copyright 2017 Google Inc. All rights reserved.
|
|
|
|
* Modifications 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.
|
|
|
|
*/
|
|
|
|
|
2020-01-07 16:13:49 -08:00
|
|
|
import * as fs from 'fs';
|
2019-12-19 16:53:24 -08:00
|
|
|
import * as os from 'os';
|
|
|
|
import * as path from 'path';
|
2020-04-01 14:42:47 -07:00
|
|
|
import * as util from 'util';
|
2020-03-28 10:14:59 -07:00
|
|
|
import * as ws from 'ws';
|
2019-12-19 16:53:24 -08:00
|
|
|
import { TimeoutError } from '../errors';
|
2020-03-02 13:51:32 -08:00
|
|
|
import { Events } from '../events';
|
|
|
|
import { FFBrowser } from '../firefox/ffBrowser';
|
|
|
|
import { kBrowserCloseMessageId } from '../firefox/ffConnection';
|
2020-05-20 00:10:10 -07:00
|
|
|
import { helper, assert, debugAssert } from '../helper';
|
2020-03-30 13:49:52 -07:00
|
|
|
import { BrowserServer, WebSocketWrapper } from './browserServer';
|
2020-05-20 16:30:04 -07:00
|
|
|
import { BrowserArgOptions, LaunchServerOptions, BrowserTypeBase, processBrowserArgOptions, LaunchType } from './browserType';
|
2020-03-02 13:51:32 -08:00
|
|
|
import { launchProcess, waitForLine } from './processLauncher';
|
2020-04-01 14:42:47 -07:00
|
|
|
import { ConnectionTransport, SequenceNumberMixer, WebSocketTransport } from '../transport';
|
2020-05-20 16:30:04 -07:00
|
|
|
import { InnerLogger, logError } from '../logger';
|
2020-04-28 17:06:01 -07:00
|
|
|
import { BrowserDescriptor } from '../install/browserPaths';
|
2020-05-20 16:30:04 -07:00
|
|
|
import { BrowserBase, BrowserOptions } from '../browser';
|
2020-01-09 14:49:22 -08:00
|
|
|
|
2020-04-01 14:42:47 -07:00
|
|
|
const mkdtempAsync = util.promisify(fs.mkdtemp);
|
2020-02-11 19:10:02 -08:00
|
|
|
|
2020-05-20 16:30:04 -07:00
|
|
|
export class Firefox extends BrowserTypeBase {
|
2020-04-28 17:06:01 -07:00
|
|
|
constructor(packagePath: string, browser: BrowserDescriptor) {
|
|
|
|
super(packagePath, browser);
|
2020-01-28 18:09:07 -08:00
|
|
|
}
|
|
|
|
|
2020-05-20 16:30:04 -07:00
|
|
|
_connectToServer(browserServer: BrowserServer, persistent: boolean, transport: ConnectionTransport, downloadsPath: string): Promise<BrowserBase> {
|
|
|
|
const options = browserServer._launchOptions;
|
|
|
|
// TODO: connect to the underlying socket.
|
|
|
|
return WebSocketTransport.connect(browserServer.wsEndpoint()!, transport => {
|
|
|
|
return FFBrowser.connect(transport, {
|
|
|
|
slowMo: options.slowMo,
|
|
|
|
logger: browserServer._logger,
|
|
|
|
persistent,
|
|
|
|
downloadsPath,
|
|
|
|
headful: !processBrowserArgOptions(options).headless,
|
|
|
|
ownedServer: browserServer,
|
|
|
|
});
|
|
|
|
}, browserServer._logger);
|
2020-02-04 19:41:38 -08:00
|
|
|
}
|
|
|
|
|
2020-05-20 16:30:04 -07:00
|
|
|
_connectToTransport(transport: ConnectionTransport, options: BrowserOptions): Promise<FFBrowser> {
|
|
|
|
return FFBrowser.connect(transport, options);
|
2020-02-05 12:41:55 -08:00
|
|
|
}
|
|
|
|
|
2020-05-20 16:30:04 -07:00
|
|
|
async _launchServer(options: LaunchServerOptions, launchType: LaunchType, browserServer: BrowserServer, userDataDir?: string): Promise<{ downloadsPath: string }> {
|
2019-12-19 16:53:24 -08:00
|
|
|
const {
|
|
|
|
ignoreDefaultArgs = false,
|
|
|
|
args = [],
|
|
|
|
executablePath = null,
|
|
|
|
env = process.env,
|
|
|
|
handleSIGHUP = true,
|
|
|
|
handleSIGINT = true,
|
|
|
|
handleSIGTERM = true,
|
|
|
|
timeout = 30000,
|
2020-03-31 16:34:59 -07:00
|
|
|
port = 0,
|
2019-12-19 16:53:24 -08:00
|
|
|
} = options;
|
2020-03-31 16:34:59 -07:00
|
|
|
assert(!port || launchType === 'server', 'Cannot specify a port without launching as a server.');
|
2020-05-20 00:10:10 -07:00
|
|
|
const logger = browserServer._logger;
|
2019-12-19 16:53:24 -08:00
|
|
|
|
|
|
|
let temporaryProfileDir = null;
|
2020-02-05 12:41:55 -08:00
|
|
|
if (!userDataDir) {
|
2020-05-06 10:42:27 -07:00
|
|
|
userDataDir = await mkdtempAsync(path.join(os.tmpdir(), 'playwright_dev_firefox_profile-'));
|
2020-02-05 16:36:36 -08:00
|
|
|
temporaryProfileDir = userDataDir;
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
2020-02-05 12:41:55 -08:00
|
|
|
|
2020-05-10 15:23:53 -07:00
|
|
|
const firefoxArguments = [];
|
2020-02-05 16:36:36 -08:00
|
|
|
if (!ignoreDefaultArgs)
|
2020-04-01 14:42:47 -07:00
|
|
|
firefoxArguments.push(...this._defaultArgs(options, launchType, userDataDir, 0));
|
2020-02-05 16:36:36 -08:00
|
|
|
else if (Array.isArray(ignoreDefaultArgs))
|
2020-04-01 14:42:47 -07:00
|
|
|
firefoxArguments.push(...this._defaultArgs(options, launchType, userDataDir, 0).filter(arg => !ignoreDefaultArgs.includes(arg)));
|
2020-02-05 16:36:36 -08:00
|
|
|
else
|
|
|
|
firefoxArguments.push(...args);
|
2019-12-19 16:53:24 -08:00
|
|
|
|
2020-04-28 17:06:01 -07:00
|
|
|
const firefoxExecutable = executablePath || this.executablePath();
|
2020-03-19 11:43:35 -07:00
|
|
|
if (!firefoxExecutable)
|
|
|
|
throw new Error(`No executable path is specified. Pass "executablePath" option directly.`);
|
2020-01-08 13:55:38 -08:00
|
|
|
|
2020-05-14 13:22:33 -07:00
|
|
|
// Note: it is important to define these variables before launchProcess, so that we don't get
|
|
|
|
// "Cannot access 'browserServer' before initialization" if something went wrong.
|
|
|
|
let browserWSEndpoint: string | undefined = undefined;
|
2020-04-07 15:01:42 -07:00
|
|
|
const { launchedProcess, gracefullyClose, downloadsPath } = await launchProcess({
|
2019-12-19 16:53:24 -08:00
|
|
|
executablePath: firefoxExecutable,
|
|
|
|
args: firefoxArguments,
|
|
|
|
env: os.platform() === 'linux' ? {
|
|
|
|
...env,
|
|
|
|
// On linux Juggler ships the libstdc++ it was linked against.
|
|
|
|
LD_LIBRARY_PATH: `${path.dirname(firefoxExecutable)}:${process.env.LD_LIBRARY_PATH}`,
|
|
|
|
} : env,
|
|
|
|
handleSIGINT,
|
|
|
|
handleSIGTERM,
|
|
|
|
handleSIGHUP,
|
2020-04-20 07:52:26 -07:00
|
|
|
logger,
|
2019-12-19 16:53:24 -08:00
|
|
|
pipe: false,
|
2020-01-13 13:33:25 -08:00
|
|
|
tempDir: temporaryProfileDir || undefined,
|
2020-01-08 13:55:38 -08:00
|
|
|
attemptToGracefullyClose: async () => {
|
2020-05-20 14:58:27 -07:00
|
|
|
if ((options as any).__testHookGracefullyClose)
|
|
|
|
await (options as any).__testHookGracefullyClose();
|
2020-05-20 00:10:10 -07:00
|
|
|
debugAssert(browserServer._isInitialized());
|
2020-01-08 13:55:38 -08:00
|
|
|
// We try to gracefully close to prevent crash reporting and core dumps.
|
2020-04-01 14:42:47 -07:00
|
|
|
const transport = await WebSocketTransport.connect(browserWSEndpoint!, async transport => transport);
|
2020-01-23 17:45:31 -08:00
|
|
|
const message = { method: 'Browser.close', params: {}, id: kBrowserCloseMessageId };
|
2020-05-20 16:30:04 -07:00
|
|
|
transport.send(message);
|
2020-01-08 13:55:38 -08:00
|
|
|
},
|
2020-01-28 13:07:53 -08:00
|
|
|
onkill: (exitCode, signal) => {
|
2020-05-20 00:10:10 -07:00
|
|
|
browserServer.emit(Events.BrowserServer.Close, exitCode, signal);
|
2020-01-24 15:58:04 -08:00
|
|
|
},
|
2019-12-19 16:53:24 -08:00
|
|
|
});
|
|
|
|
|
2020-01-08 13:55:38 -08:00
|
|
|
const timeoutError = new TimeoutError(`Timed out after ${timeout} ms while trying to connect to Firefox!`);
|
|
|
|
const match = await waitForLine(launchedProcess, launchedProcess.stdout, /^Juggler listening on (ws:\/\/.*)$/, timeout, timeoutError);
|
2020-03-28 10:14:59 -07:00
|
|
|
const innerEndpoint = match[1];
|
|
|
|
|
2020-05-18 19:00:38 -07:00
|
|
|
const webSocketWrapper = launchType === 'server' ?
|
|
|
|
(await WebSocketTransport.connect(innerEndpoint, t => wrapTransportWithWebSocket(t, logger, port), logger)) :
|
|
|
|
new WebSocketWrapper(innerEndpoint, []);
|
2020-03-30 13:49:52 -07:00
|
|
|
browserWSEndpoint = webSocketWrapper.wsEndpoint;
|
2020-05-20 00:10:10 -07:00
|
|
|
browserServer._initialize(launchedProcess, gracefullyClose, webSocketWrapper);
|
|
|
|
return { downloadsPath };
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-02-27 14:09:24 -08:00
|
|
|
private _defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] {
|
2020-05-14 13:22:33 -07:00
|
|
|
const { devtools, headless } = processBrowserArgOptions(options);
|
|
|
|
const { args = [] } = options;
|
2020-01-24 14:49:47 -08:00
|
|
|
if (devtools)
|
2020-03-24 22:42:20 +01:00
|
|
|
console.warn('devtools parameter is not supported as a launch argument in Firefox. You can launch the devtools window manually.');
|
2020-02-05 16:36:36 -08:00
|
|
|
const userDataDirArg = args.find(arg => arg.startsWith('-profile') || arg.startsWith('--profile'));
|
|
|
|
if (userDataDirArg)
|
|
|
|
throw new Error('Pass userDataDir parameter instead of specifying -profile argument');
|
|
|
|
if (args.find(arg => arg.startsWith('-juggler')))
|
|
|
|
throw new Error('Use the port parameter instead of -juggler argument');
|
|
|
|
|
|
|
|
const firefoxArguments = ['-no-remote'];
|
2020-02-10 20:35:58 -08:00
|
|
|
if (headless) {
|
2020-01-07 16:13:49 -08:00
|
|
|
firefoxArguments.push('-headless');
|
2020-02-10 20:35:58 -08:00
|
|
|
} else {
|
2020-01-21 17:22:48 -08:00
|
|
|
firefoxArguments.push('-wait-for-browser');
|
2020-02-10 20:35:58 -08:00
|
|
|
firefoxArguments.push('-foreground');
|
|
|
|
}
|
2020-02-05 16:36:36 -08:00
|
|
|
firefoxArguments.push(`-profile`, userDataDir);
|
|
|
|
firefoxArguments.push('-juggler', String(port));
|
2020-01-07 16:13:49 -08:00
|
|
|
firefoxArguments.push(...args);
|
2020-05-10 15:23:53 -07:00
|
|
|
if (launchType === 'persistent')
|
|
|
|
firefoxArguments.push('about:blank');
|
|
|
|
else
|
2020-04-10 14:12:30 -07:00
|
|
|
firefoxArguments.push('-silent');
|
2020-01-07 16:13:49 -08:00
|
|
|
return firefoxArguments;
|
|
|
|
}
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-04-20 23:24:53 -07:00
|
|
|
function wrapTransportWithWebSocket(transport: ConnectionTransport, logger: InnerLogger, port: number): WebSocketWrapper {
|
2020-03-28 10:14:59 -07:00
|
|
|
const server = new ws.Server({ port });
|
2020-04-01 14:42:47 -07:00
|
|
|
const guid = helper.guid();
|
2020-03-28 10:14:59 -07:00
|
|
|
const idMixer = new SequenceNumberMixer<{id: number, socket: ws}>();
|
|
|
|
const pendingBrowserContextCreations = new Set<number>();
|
|
|
|
const pendingBrowserContextDeletions = new Map<number, string>();
|
|
|
|
const browserContextIds = new Map<string, ws>();
|
|
|
|
const sessionToSocket = new Map<string, ws>();
|
|
|
|
const sockets = new Set<ws>();
|
|
|
|
|
|
|
|
transport.onmessage = message => {
|
|
|
|
if (typeof message.id === 'number') {
|
|
|
|
// Process command response.
|
|
|
|
const seqNum = message.id;
|
|
|
|
const value = idMixer.take(seqNum);
|
|
|
|
if (!value)
|
|
|
|
return;
|
|
|
|
const { id, socket } = value;
|
|
|
|
|
|
|
|
if (socket.readyState === ws.CLOSING) {
|
|
|
|
if (pendingBrowserContextCreations.has(id)) {
|
|
|
|
transport.send({
|
|
|
|
id: ++SequenceNumberMixer._lastSequenceNumber,
|
|
|
|
method: 'Browser.removeBrowserContext',
|
|
|
|
params: { browserContextId: message.result.browserContextId }
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (pendingBrowserContextCreations.has(seqNum)) {
|
|
|
|
// Browser.createBrowserContext response -> establish context attribution.
|
|
|
|
browserContextIds.set(message.result.browserContextId, socket);
|
|
|
|
pendingBrowserContextCreations.delete(seqNum);
|
|
|
|
}
|
|
|
|
|
|
|
|
const deletedContextId = pendingBrowserContextDeletions.get(seqNum);
|
|
|
|
if (deletedContextId) {
|
|
|
|
// Browser.removeBrowserContext response -> remove context attribution.
|
|
|
|
browserContextIds.delete(deletedContextId);
|
|
|
|
pendingBrowserContextDeletions.delete(seqNum);
|
|
|
|
}
|
|
|
|
|
|
|
|
message.id = id;
|
|
|
|
socket.send(JSON.stringify(message));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Process notification response.
|
|
|
|
const { method, params, sessionId } = message;
|
|
|
|
if (sessionId) {
|
|
|
|
const socket = sessionToSocket.get(sessionId);
|
|
|
|
if (!socket || socket.readyState === ws.CLOSING) {
|
|
|
|
// Drop unattributed messages on the floor.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
socket.send(JSON.stringify(message));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (method === 'Browser.attachedToTarget') {
|
|
|
|
const socket = browserContextIds.get(params.targetInfo.browserContextId);
|
|
|
|
if (!socket || socket.readyState === ws.CLOSING) {
|
|
|
|
// Drop unattributed messages on the floor.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
sessionToSocket.set(params.sessionId, socket);
|
|
|
|
socket.send(JSON.stringify(message));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (method === 'Browser.detachedFromTarget') {
|
|
|
|
const socket = sessionToSocket.get(params.sessionId);
|
|
|
|
sessionToSocket.delete(params.sessionId);
|
|
|
|
if (socket && socket.readyState !== ws.CLOSING)
|
|
|
|
socket.send(JSON.stringify(message));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
transport.onclose = () => {
|
|
|
|
for (const socket of sockets) {
|
|
|
|
socket.removeListener('close', (socket as any).__closeListener);
|
|
|
|
socket.close(undefined, 'Browser disconnected');
|
|
|
|
}
|
|
|
|
server.close();
|
|
|
|
transport.onmessage = undefined;
|
|
|
|
transport.onclose = undefined;
|
|
|
|
};
|
|
|
|
|
|
|
|
server.on('connection', (socket: ws, req) => {
|
|
|
|
if (req.url !== '/' + guid) {
|
|
|
|
socket.close();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
sockets.add(socket);
|
|
|
|
|
|
|
|
socket.on('message', (message: string) => {
|
|
|
|
const parsedMessage = JSON.parse(Buffer.from(message).toString());
|
|
|
|
const { id, method, params } = parsedMessage;
|
|
|
|
const seqNum = idMixer.generate({ id, socket });
|
|
|
|
transport.send({ ...parsedMessage, id: seqNum });
|
|
|
|
if (method === 'Browser.createBrowserContext')
|
|
|
|
pendingBrowserContextCreations.add(seqNum);
|
|
|
|
if (method === 'Browser.removeBrowserContext')
|
|
|
|
pendingBrowserContextDeletions.set(seqNum, params.browserContextId);
|
|
|
|
});
|
|
|
|
|
2020-04-20 07:52:26 -07:00
|
|
|
socket.on('error', logError(logger));
|
2020-03-30 18:18:38 -07:00
|
|
|
|
2020-03-28 10:14:59 -07:00
|
|
|
socket.on('close', (socket as any).__closeListener = () => {
|
|
|
|
for (const [browserContextId, s] of browserContextIds) {
|
|
|
|
if (s === socket) {
|
|
|
|
transport.send({
|
|
|
|
id: ++SequenceNumberMixer._lastSequenceNumber,
|
|
|
|
method: 'Browser.removeBrowserContext',
|
|
|
|
params: { browserContextId }
|
|
|
|
});
|
|
|
|
browserContextIds.delete(browserContextId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
sockets.delete(socket);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
const address = server.address();
|
2020-03-30 13:49:52 -07:00
|
|
|
const wsEndpoint = typeof address === 'string' ? `${address}/${guid}` : `ws://127.0.0.1:${address.port}/${guid}`;
|
|
|
|
return new WebSocketWrapper(wsEndpoint,
|
|
|
|
[pendingBrowserContextCreations, pendingBrowserContextDeletions, browserContextIds, sessionToSocket, sockets]);
|
2020-03-28 10:14:59 -07:00
|
|
|
}
|