forked from DevExpress/testcafe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
425 lines (325 loc) · 14.8 KB
/
index.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
// NOTE: Initializer should be the first
import './shared-adapter-initializer';
import { readSync as read } from 'read-file-relative';
import { Dictionary } from '../../../../../../configuration/interfaces';
import Protocol from 'devtools-protocol';
import path from 'path';
import os from 'os';
import remoteChrome from 'chrome-remote-interface';
import debug from 'debug';
import { GET_WINDOW_DIMENSIONS_INFO_SCRIPT } from '../../../../utils/client-functions';
import WARNING_MESSAGE from '../../../../../../notifications/warning-message';
import * as SharedErrors from '../../../../../../shared/errors';
import {
Config,
RuntimeInfo,
TouchConfigOptions,
Size,
} from '../interfaces';
import prettyTime from 'pretty-hrtime';
import { CheckedCDPMethod, ELAPSED_TIME_UPPERBOUNDS } from '../elapsed-upperbounds';
import guardTimeExecution from '../../../../../../utils/guard-time-execution';
import { CallsiteRecord } from 'callsite-record';
import { ExecuteClientFunctionCommand, ExecuteSelectorCommand } from '../../../../../../test-run/commands/observation';
import ClientFunctionExecutor from './client-function-executor';
import { SwitchToIframeCommand } from '../../../../../../test-run/commands/actions';
import ExecutionContext from './execution-context';
import * as clientsManager from './clients-manager';
import delay from '../../../../../../utils/delay';
const DEBUG_SCOPE = (id: string): string => `testcafe:browser:provider:built-in:chrome:browser-client:${id}`;
const DOWNLOADS_DIR = path.join(os.homedir(), 'Downloads');
const debugLog = debug('testcafe:browser:provider:built-in:dedicated:chrome');
class ProtocolApiInfo {
public inactive: boolean;
public client: remoteChrome.ProtocolApi;
public constructor (client: remoteChrome.ProtocolApi) {
this.client = client;
this.inactive = false;
}
}
export class BrowserClient {
private _clients: Dictionary<ProtocolApiInfo> = {};
private _runtimeInfo: RuntimeInfo;
private readonly _proxyless: boolean;
private _parentTarget?: remoteChrome.TargetInfo;
private readonly debugLogger: debug.Debugger;
private readonly _clientFunctionExecutor: ClientFunctionExecutor;
public constructor (runtimeInfo: RuntimeInfo, proxyless: boolean) {
this._runtimeInfo = runtimeInfo;
this.debugLogger = debug(DEBUG_SCOPE(runtimeInfo.browserId));
this._proxyless = proxyless;
this._clientFunctionExecutor = new ClientFunctionExecutor();
runtimeInfo.browserClient = this;
}
private get _clientKey (): string {
return this._runtimeInfo.activeWindowId || this._runtimeInfo.browserId;
}
private get _config (): Config {
return this._runtimeInfo.config;
}
private async _getTabs (): Promise<remoteChrome.TargetInfo[]> {
const tabs = await remoteChrome.List({ port: this._runtimeInfo.cdpPort });
return tabs.filter(t => t.type === 'page');
}
private async _getActiveTab (): Promise<remoteChrome.TargetInfo> {
let tabs = await this._getTabs();
if (this._runtimeInfo.activeWindowId)
tabs = tabs.filter(t => t.title.includes(this._runtimeInfo.activeWindowId));
return tabs[0];
}
private _checkDropOfPerformance (method: CheckedCDPMethod, elapsedTime: [number, number]): void {
this.debugLogger(`CDP method '${method}' took ${prettyTime(elapsedTime)}`);
const [ elapsedSeconds ] = elapsedTime;
if (elapsedSeconds > ELAPSED_TIME_UPPERBOUNDS[method]) {
this._runtimeInfo.providerMethods.reportWarning(
WARNING_MESSAGE.browserProviderDropOfPerformance,
this._runtimeInfo.browserName
);
}
}
private async _createClient (): Promise<remoteChrome.ProtocolApi> {
const target = await this._getActiveTab();
const client = await remoteChrome({ target, port: this._runtimeInfo.cdpPort });
const { Page, Network, Runtime } = client;
this._clients[this._clientKey] = new ProtocolApiInfo(client);
await guardTimeExecution(
async () => await Page.enable(),
elapsedTime => this._checkDropOfPerformance(CheckedCDPMethod.PageEnable, elapsedTime)
);
await Network.enable({});
await Runtime.enable();
return client;
}
private async _setupClient (client: remoteChrome.ProtocolApi): Promise<void> {
if (this._config.emulation)
await this._setEmulation(client);
if (this._config.headless)
await this._setupDownloads(client);
}
private async _setDeviceMetricsOverride (client: remoteChrome.ProtocolApi, width: number, height: number, deviceScaleFactor: number, mobile: boolean): Promise<void> {
await guardTimeExecution(
async () => {
await client.Emulation.setDeviceMetricsOverride({
width,
height,
deviceScaleFactor,
mobile,
// @ts-ignore
fitWindow: false,
});
},
elapsedTime => this._checkDropOfPerformance(CheckedCDPMethod.SetDeviceMetricsOverride, elapsedTime)
);
}
private async _setUserAgentEmulation (client: remoteChrome.ProtocolApi): Promise<void> {
if (this._config.userAgent === void 0)
return;
await client.Network.setUserAgentOverride({ userAgent: this._config.userAgent });
}
private async _setTouchEmulation (client: remoteChrome.ProtocolApi): Promise<void> {
if (this._config.touch === void 0)
return;
const touchConfig: TouchConfigOptions = {
enabled: this._config.touch,
configuration: this._config.mobile ? 'mobile' : 'desktop',
maxTouchPoints: 1,
};
if (client.Emulation.setEmitTouchEventsForMouse)
await client.Emulation.setEmitTouchEventsForMouse(touchConfig);
if (client.Emulation.setTouchEmulationEnabled)
await client.Emulation.setTouchEmulationEnabled(touchConfig);
}
private async _setEmulation (client: remoteChrome.ProtocolApi): Promise<void> {
await this._setUserAgentEmulation(client);
await this._setTouchEmulation(client);
await this.resizeWindow({
width: this._config.width,
height: this._config.height,
});
}
private async _setupDownloads (client: remoteChrome.ProtocolApi): Promise<void> {
await client.Page.setDownloadBehavior({
behavior: 'allow',
downloadPath: DOWNLOADS_DIR,
});
}
private async _evaluateRuntime (client: remoteChrome.ProtocolApi, expression: string, returnByValue: boolean = false): Promise<Protocol.Runtime.EvaluateResponse> {
return client.Runtime.evaluate({ expression, returnByValue });
}
private async _calculateEmulatedDevicePixelRatio (client: remoteChrome.ProtocolApi): Promise<void> {
if (!client)
return;
const devicePixelRatioQueryResult = await client.Runtime.evaluate({ expression: 'window.devicePixelRatio' });
this._runtimeInfo.originalDevicePixelRatio = devicePixelRatioQueryResult.result.value;
this._runtimeInfo.emulatedDevicePixelRatio = this._config.scaleFactor || this._runtimeInfo.originalDevicePixelRatio;
}
private async _injectProxylessStuff (client: remoteChrome.ProtocolApi): Promise<void> {
await client.Page.addScriptToEvaluateOnNewDocument({
source: read('../../../../../../../lib/client/proxyless/index.js') as string,
});
}
public async resizeWindow (newDimensions: Size): Promise<void> {
const { browserId, config, viewportSize, providerMethods, emulatedDevicePixelRatio } = this._runtimeInfo;
const currentWidth = viewportSize.width;
const currentHeight = viewportSize.height;
const newWidth = newDimensions.width || currentWidth;
const newHeight = newDimensions.height || currentHeight;
if (!config.headless)
await providerMethods.resizeLocalBrowserWindow(browserId, newWidth, newHeight, currentWidth, currentHeight);
viewportSize.width = newWidth;
viewportSize.height = newHeight;
const client = await this.getActiveClient();
if (client && config.emulation) {
await this._setDeviceMetricsOverride(client, viewportSize.width, viewportSize.height, emulatedDevicePixelRatio, config.mobile);
await guardTimeExecution(
async () => {
await client.Emulation.setVisibleSize({ width: viewportSize.width, height: viewportSize.height });
},
elapsedTime => this._checkDropOfPerformance(CheckedCDPMethod.SetVisibleSize, elapsedTime)
);
}
}
public isHeadlessTab (): boolean {
return !!this._parentTarget && this._config.headless;
}
public async setClientInactive (): Promise<void> {
// NOTE: ensure client exists
await this.getActiveClient();
const client = this._clients[this._clientKey];
if (client)
client.inactive = true;
}
public async getActiveClient (): Promise<remoteChrome.ProtocolApi | void> {
try {
if (!this._clients[this._clientKey])
await this._createClient();
}
catch (err) {
debugLog(err);
return void 0;
}
const info = this._clients[this._clientKey];
if (info.inactive)
return void 0;
return info.client;
}
public async init (): Promise<void> {
try {
const tabs = await this._getTabs();
this._parentTarget = tabs.find(t => t.url.includes(this._runtimeInfo.browserId));
if (!this._parentTarget)
return;
const client = await this.getActiveClient();
if (client) {
await this._calculateEmulatedDevicePixelRatio(client);
await this._setupClient(client);
if (this._proxyless) {
await this._injectProxylessStuff(client);
ExecutionContext.initialize(client);
clientsManager.setClient(client);
}
}
}
catch (e) {
return;
}
}
public async getScreenshotData (fullPage?: boolean): Promise<Buffer> {
let viewportWidth = 0;
let viewportHeight = 0;
const { config, emulatedDevicePixelRatio } = this._runtimeInfo;
const client = await this.getActiveClient();
if (!client) {
// NOTE: required for https://github.com/DevExpress/testcafe/issues/6037
await delay(0);
return Buffer.alloc(0);
}
if (fullPage) {
const { contentSize, visualViewport } = await client.Page.getLayoutMetrics();
await this._setDeviceMetricsOverride(
client,
Math.ceil(contentSize.width),
Math.ceil(contentSize.height),
emulatedDevicePixelRatio,
config.mobile);
viewportWidth = visualViewport.clientWidth;
viewportHeight = visualViewport.clientHeight;
}
const screenshotData = await client.Page.captureScreenshot({});
if (fullPage) {
if (config.emulation) {
await this._setDeviceMetricsOverride(
client,
config.width || viewportWidth,
config.height || viewportHeight,
emulatedDevicePixelRatio,
config.mobile);
}
else
await client.Emulation.clearDeviceMetricsOverride();
}
return Buffer.from(screenshotData.data, 'base64');
}
public async closeTab (): Promise<void> {
if (this._parentTarget)
await remoteChrome.Close({ id: this._parentTarget.id, port: this._runtimeInfo.cdpPort });
}
public async updateMobileViewportSize (): Promise<void> {
const client = await this.getActiveClient();
if (!client)
return;
const windowDimensionsQueryResult = await this._evaluateRuntime(client, `(${GET_WINDOW_DIMENSIONS_INFO_SCRIPT})()`, true);
const windowDimensions = windowDimensionsQueryResult.result.value;
this._runtimeInfo.viewportSize.width = windowDimensions.outerWidth;
this._runtimeInfo.viewportSize.height = windowDimensions.outerHeight;
}
public async executeClientFunction (command: ExecuteClientFunctionCommand, callsite: CallsiteRecord): Promise<object> {
const client = await this.getActiveClient();
if (!client)
throw new Error('Cannot get the active browser client');
return this._clientFunctionExecutor.executeClientFunction(client.Runtime, command, callsite);
}
public async executeSelector (command: ExecuteSelectorCommand, callsite: CallsiteRecord, selectorTimeout: number): Promise<object> {
const client = await this.getActiveClient();
if (!client)
throw new Error('Cannot get the active browser client');
return this._clientFunctionExecutor.executeSelector({
Runtime: client.Runtime,
errCtors: {
notFound: SharedErrors.CannotObtainInfoForElementSpecifiedBySelectorError.name,
invisible: SharedErrors.CannotObtainInfoForElementSpecifiedBySelectorError.name,
},
command, callsite, selectorTimeout,
});
}
public async switchToIframe (command: SwitchToIframeCommand, callsite: CallsiteRecord, selectorTimeout: number): Promise<void> {
const client = await this.getActiveClient();
if (!client)
return;
const selector = command.selector;
if (typeof selector.timeout === 'number')
selectorTimeout = selector.timeout;
selector.needError = true;
const node = await this._clientFunctionExecutor.getNode({
DOM: client.DOM,
Runtime: client.Runtime,
command: selector,
errCtors: {
notFound: SharedErrors.ActionElementNotFoundError.name,
invisible: SharedErrors.ActionElementIsInvisibleError.name,
},
callsite, selectorTimeout,
});
if (!node.frameId)
throw new SharedErrors.ActionElementNotIframeError(callsite);
ExecutionContext.switchToIframe(node.frameId);
}
public switchToMainWindow (): void {
ExecutionContext.switchToMainWindow();
}
public async closeBrowserChildWindow (): Promise<void> {
await this.setClientInactive();
// NOTE: delay browser window closing
await delay(100);
}
}