Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(lint): webkit linting #1

Merged
merged 1 commit into from
Nov 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions src/webkit/Browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,12 @@

import * as childProcess from 'child_process';
import { EventEmitter } from 'events';
import { Connection, ConnectionEvents } from './Connection';
import { Connection } from './Connection';
import { Events } from '../Events';
import { RegisteredListener, assert, helper } from '../helper';
import { Page, Viewport } from './Page';
import { Target } from './Target';
import { TaskQueue } from './TaskQueue';
import { Protocol } from './protocol';

export class Browser extends EventEmitter {
_defaultViewport: Viewport;
Expand Down Expand Up @@ -101,7 +100,7 @@ export class Browser extends EventEmitter {
return this._createPageInContext(this._defaultContext._id);
}

async _createPageInContext(browserContextId?: string ): Promise<Page> {
async _createPageInContext(browserContextId?: string): Promise<Page> {
const {targetId} = await this._connection.send('Browser.createPage', {browserContextId});
const target = this._targets.get(targetId);
return await target.page();
Expand Down Expand Up @@ -146,11 +145,11 @@ export class Browser extends EventEmitter {
async _onTargetCreated({targetInfo}) {
let context = null;
if (targetInfo.browserContextId) {
context = this._contexts.get(targetInfo.browserContextId);
// FIXME: we don't know about the default context id, so assume that all targets from
// unknown contexts are created in the 'default' context which can in practice be represented
// by multiple actual contexts in WebKit. Solving this properly will require adding context
// lifecycle events.
context = this._contexts.get(targetInfo.browserContextId);
// if (!context)
// throw new Error(`Target ${targetId} created in unknown browser context ${browserContextId}.`);
}
Expand All @@ -177,8 +176,7 @@ export class Browser extends EventEmitter {
target.browserContext().emit(Events.BrowserContext.TargetDestroyed, target);
}

async _onProvisionalTargetCommitted({oldTargetId, newTargetId})
{
async _onProvisionalTargetCommitted({oldTargetId, newTargetId}) {
const oldTarget = this._targets.get(oldTargetId);
if (!oldTarget._pagePromise)
return;
Expand Down
18 changes: 8 additions & 10 deletions src/webkit/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export class Connection extends EventEmitter {
else
callback.resolve(object.result);
} else {
assert(this._closed, "Received response for unknown callback: " + object.id);
assert(this._closed, 'Received response for unknown callback: ' + object.id);
}
} else {
this.emit(object.method, object.params);
Expand All @@ -114,16 +114,16 @@ export class Connection extends EventEmitter {
} else if (object.method === 'Target.dispatchMessageFromTarget') {
const session = this._sessions.get(object.params.targetId);
if (!session)
throw new Error("Unknown target: " + object.params.targetId);
throw new Error('Unknown target: ' + object.params.targetId);
session._dispatchMessageFromTarget(object.params.message);
} else if (object.method === 'Target.didCommitProvisionalTarget') {
const {oldTargetId, newTargetId} = object.params;
const newSession = this._sessions.get(newTargetId);
if (!newSession)
throw new Error("Unknown new target: " + newTargetId);
throw new Error('Unknown new target: ' + newTargetId);
const oldSession = this._sessions.get(oldTargetId);
if (!oldSession)
throw new Error("Unknown old target: " + oldTargetId);
throw new Error('Unknown old target: ' + oldTargetId);
}
}

Expand Down Expand Up @@ -188,28 +188,28 @@ export class TargetSession extends EventEmitter {
method,
params
};
debugWrappedMessage("SEND ► " + JSON.stringify(messageObj, null, 2));
debugWrappedMessage('SEND ► ' + JSON.stringify(messageObj, null, 2));
this._out.push(messageObj);
// Serialize message before adding callback in case JSON throws.
const message = JSON.stringify(messageObj);
const result = new Promise<Protocol.CommandReturnValues[T]>((resolve, reject) => {
this._callbacks.set(innerId, {resolve, reject, error: new Error(), method});
});
this._connection.send("Target.sendMessageToTarget", {
this._connection.send('Target.sendMessageToTarget', {
message: message, targetId: this._sessionId
}).catch(e => {
// There is a possible race of the connection closure. We may have received
// targetDestroyed notification before response for the command, in that
// case it's safe to swallow the exception.g
const callback = this._callbacks.get(innerId);
assert(!callback, "Callback was not rejected when target was destroyed.");
assert(!callback, 'Callback was not rejected when target was destroyed.');
});
return result;
}

_dispatchMessageFromTarget(message: string) {
const object = JSON.parse(message);
debugWrappedMessage("◀ RECV " + JSON.stringify(object, null, 2));
debugWrappedMessage('◀ RECV ' + JSON.stringify(object, null, 2));
this._in.push(object);
if (object.id && this._callbacks.has(object.id)) {
const callback = this._callbacks.get(object.id);
Expand All @@ -219,8 +219,6 @@ export class TargetSession extends EventEmitter {
else
callback.resolve(object.result);
} else {
if (object.id)
console.log(JSON.stringify(object, null, 2));
assert(!object.id);
// console.log(`[${this._sessionId}] ${object.method}`);
this.emit(object.method, object.params);
Expand Down
19 changes: 10 additions & 9 deletions src/webkit/ExecutionContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export class ExecutionContext {
return void 0;
throw e;
}
}
};
return this._session.send('Runtime.callFunctionOn', {
// Serialize object using standard JSON implementation to correctly pass 'undefined'.
functionDeclaration: serializeFunction + '\n' + suffix + '\n',
Expand All @@ -121,7 +121,8 @@ export class ExecutionContext {
});
}
return valueFromRemoteObject(response.result);
}).catch(rewriteError); }
}).catch(rewriteError);
}

if (typeof pageFunction !== 'function')
throw new Error(`Expected to get |string| or |function| as the first argument, but got "${pageFunction}" instead.`);
Expand All @@ -147,10 +148,10 @@ export class ExecutionContext {
let serializableArgs;
if (args.some(isUnserializable)) {
serializableArgs = [];
let paramStrings = [];
for (let arg of args) {
const paramStrings = [];
for (const arg of args) {
if (isUnserializable(arg)) {
paramStrings.push(unserializableToString(arg))
paramStrings.push(unserializableToString(arg));
} else {
paramStrings.push('arguments[' + serializableArgs.length + ']');
serializableArgs.push(arg);
Expand All @@ -172,7 +173,7 @@ export class ExecutionContext {
returnByValue: false,
emulateUserGesture: true
});
} catch(err) {
} catch (err) {
if (err instanceof TypeError && err.message.startsWith('Converting circular structure to JSON'))
err.message += ' Are you passing a nested JSHandle?';
throw err;
Expand All @@ -198,7 +199,7 @@ export class ExecutionContext {
if (response.wasThrown)
throw new Error('Evaluation failed: ' + response.result.description);
if (!returnByValue)
return createJSHandle(this, response.result);;
return createJSHandle(this, response.result);
if (response.result.objectId) {
const serializeFunction = function() {
try {
Expand All @@ -208,7 +209,7 @@ export class ExecutionContext {
return void 0;
throw e;
}
}
};
return this._session.send('Runtime.callFunctionOn', {
// Serialize object using standard JSON implementation to correctly pass 'undefined'.
functionDeclaration: serializeFunction + '\n' + suffix + '\n',
Expand Down Expand Up @@ -294,7 +295,7 @@ export class ExecutionContext {

async _contextGlobalObjectId() {
if (!this._globalObjectId) {
const globalObject = await this._session.send('Runtime.evaluate', { expression: "this", contextId: this._contextId });
const globalObject = await this._session.send('Runtime.evaluate', { expression: 'this', contextId: this._contextId });
this._globalObjectId = globalObject.result.objectId;
}
return this._globalObjectId;
Expand Down
38 changes: 19 additions & 19 deletions src/webkit/FrameManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,27 @@
*/
import * as EventEmitter from 'events';
import * as fs from 'fs';
import {helper, assert, debugError, RegisteredListener} from '../helper';
import {TimeoutError} from '../Errors';
import {Events} from '../Events';
import {ExecutionContext, EVALUATION_SCRIPT_URL} from './ExecutionContext';
import {NetworkManager, Response, Request, NetworkManagerEvents} from './NetworkManager';
import { TimeoutError } from '../Errors';
import { Events } from '../Events';
import { assert, debugError, helper, RegisteredListener } from '../helper';
import { TimeoutSettings } from '../TimeoutSettings';
import { TargetSession } from './Connection';
import { ExecutionContext } from './ExecutionContext';
import { ElementHandle, JSHandle } from './JSHandle';
import { NetworkManager, NetworkManagerEvents, Request, Response } from './NetworkManager';
import { Page } from './Page';
import { TimeoutSettings } from '../TimeoutSettings';
import { JSHandle, ElementHandle } from './JSHandle';
import { Protocol } from './protocol';
const readFileAsync = helper.promisify(fs.readFile);

export const FrameManagerEvents = {
FrameNavigatedWithinDocument: Symbol('FrameNavigatedWithinDocument'),
TargetSwappedOnNavigation: Symbol('TargetSwappedOnNavigation'),
LifecycleEvent: Symbol('LifecycleEvent'),
FrameAttached: Symbol('FrameAttached'),
FrameDetached: Symbol('FrameDetached'),
FrameNavigated: Symbol('FrameNavigated'),
}
};

export class FrameManager extends EventEmitter {
_session: TargetSession;
_page: Page;
Expand Down Expand Up @@ -71,8 +73,7 @@ export class FrameManager extends EventEmitter {
]);
}

_addSessionListeners()
{
_addSessionListeners() {
this._sessionListeners = [
helper.addEventListener(this._session, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame)),
helper.addEventListener(this._session, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)),
Expand All @@ -82,8 +83,7 @@ export class FrameManager extends EventEmitter {
];
}

async _swapTargetOnNavigation(newSession)
{
async _swapTargetOnNavigation(newSession) {
helper.removeEventListeners(this._sessionListeners);
this.disconnectFromTarget();
this._session = newSession;
Expand All @@ -95,7 +95,7 @@ export class FrameManager extends EventEmitter {

disconnectFromTarget() {
for (const frame of this.frames())
frame._setContext(null);
frame._setContext(null);
// this._mainFrame = null;
}

Expand Down Expand Up @@ -210,7 +210,7 @@ export class FrameManager extends EventEmitter {
return;
/** @type {!ExecutionContext} */
const context: ExecutionContext = new ExecutionContext(this._session, contextPayload, frame);
frame._setContext(context)
frame._setContext(context);
this._contextIdToContext.set(contextPayload.id, context);
}

Expand Down Expand Up @@ -282,7 +282,7 @@ export class Frame {
}

async waitForNavigation(): Promise<Response | null> {
//FIXME: this method only works for main frames.
// FIXME: this method only works for main frames.
const watchDog = new NextNavigationWatchdog(this, 10000);
return watchDog.waitForNavigation();
}
Expand Down Expand Up @@ -521,7 +521,7 @@ export class Frame {
return this._detached;
}

async click(selector: string, options: { delay?: number; button?: "left" | "right" | "middle"; clickCount?: number; } | undefined) {
async click(selector: string, options: { delay?: number; button?: 'left' | 'right' | 'middle'; clickCount?: number; } | undefined) {
const handle = await this.$(selector);
assert(handle, 'No node found for selector: ' + selector);
await handle.click(options);
Expand Down Expand Up @@ -586,7 +586,7 @@ export class Frame {
return this.waitForFunction(selectorOrFunctionOrTimeout, options, ...args);
return Promise.reject(new Error('Unsupported target type: ' + (typeof selectorOrFunctionOrTimeout)));
}

async title(): Promise<string> {
return this.evaluate(() => document.title);
}
Expand Down Expand Up @@ -696,7 +696,7 @@ class NextNavigationWatchdog {
constructor(frame, timeout) {
this._frame = frame;
this._newDocumentNavigationPromise = new Promise(fulfill => {
this._newDocumentNavigationCallback = fulfill
this._newDocumentNavigationCallback = fulfill;
});
this._sameDocumentNavigationPromise = new Promise(fulfill => {
this._sameDocumentNavigationCallback = fulfill;
Expand Down Expand Up @@ -742,7 +742,7 @@ class NextNavigationWatchdog {
break;
}
} catch (e) {
console.log("_onTargetReconnected " + e);
debugError('_onTargetReconnected ' + e);
}
}

Expand Down
1 change: 0 additions & 1 deletion src/webkit/Input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ export class Keyboard {
const ControlKey = 1 << 1;
const AltKey = 1 << 2;
const MetaKey = 1 << 3;
const CapsLockKey = 1 << 4;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's strange.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caps lock is a modifier in WK, see Source/WebCore/platform/PlatformEvent.h

if (key === 'Alt')
return AltKey;
if (key === 'Control')
Expand Down
11 changes: 5 additions & 6 deletions src/webkit/JSHandle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as path from 'path';
import * as fs from 'fs';
import { assert, debugError, helper } from '../helper';
import { TargetSession } from './Connection';
import { ExecutionContext } from './ExecutionContext';
import { Frame, FrameManager } from './FrameManager';
import { assert, debugError, helper } from '../helper';
import { valueFromRemoteObject, releaseObject } from './protocolHelper';
import { FrameManager } from './FrameManager';
import { Button } from './Input';
import { Page } from './Page';
import { Modifier, Button } from './Input';
import { Protocol } from './protocol';
import { releaseObject, valueFromRemoteObject } from './protocolHelper';
const writeFileAsync = helper.promisify(fs.writeFile);

export type ClickOptions = {
Expand Down Expand Up @@ -173,7 +172,7 @@ export class ElementHandle extends JSHandle {
this._client.send('DOM.getContentQuads', {
objectId: this._remoteObject.objectId
}).catch(debugError),
this._page.evaluate(() => { return { clientWidth: innerWidth, clientHeight: innerHeight} }),
this._page.evaluate(() => ({ clientWidth: innerWidth, clientHeight: innerHeight })),
]);
if (!result || !result.quads.length)
throw new Error('Node is either not visible or not an HTMLElement');
Expand Down
10 changes: 3 additions & 7 deletions src/webkit/Launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@
* limitations under the License.
*/
import * as childProcess from 'child_process';
import * as path from 'path';
import { debugError, helper } from '../helper';
import { Browser } from './Browser';
import { BrowserFetcher } from './BrowserFetcher';
import { Connection } from './Connection';
import { debugError, helper } from '../helper';
import { Viewport } from './Page';
import { PipeTransport } from './PipeTransport';
import * as os from 'os';


export class Launcher {
Expand All @@ -43,7 +41,6 @@ export class Launcher {
handleSIGINT = true,
handleSIGTERM = true,
handleSIGHUP = true,
headless = true,
defaultViewport = {width: 800, height: 600},
slowMo = 0
} = options;
Expand All @@ -56,7 +53,7 @@ export class Launcher {
throw new Error(missingText);
webkitExecutable = executablePath;
}

let stdio: ('ignore' | 'pipe')[] = ['pipe', 'pipe', 'pipe'];
if (dumpio)
stdio = ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'];
Expand Down Expand Up @@ -100,8 +97,7 @@ export class Launcher {
try {
const transport = new PipeTransport(webkitProcess.stdio[3] as NodeJS.WritableStream, webkitProcess.stdio[4] as NodeJS.ReadableStream);
connection = new Connection('', transport, slowMo);
const browser = new Browser(connection, defaultViewport, webkitProcess
, gracefullyCloseWebkit);
const browser = new Browser(connection, defaultViewport, webkitProcess, gracefullyCloseWebkit);
return browser;
} catch (e) {
killWebKit();
Expand Down
Loading