๐Ÿ“ฆ microsoft / playwright

๐Ÿ“„ ffPage.ts ยท 571 lines
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571/**
 * Copyright 2019 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.
 */

import { eventsHelper } from '../utils/eventsHelper';
import * as dialog from '../dialog';
import * as dom from '../dom';
import { InitScript } from '../page';
import { Page, Worker } from '../page';
import { FFSession } from './ffConnection';
import { createHandle, FFExecutionContext } from './ffExecutionContext';
import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './ffInput';
import { FFNetworkManager } from './ffNetworkManager';
import { splitErrorMessage } from '../../utils/isomorphic/stackTrace';
import { TargetClosedError } from '../errors';
import { debugLogger } from '../utils/debugLogger';

import type { Progress } from '../progress';
import type { FFBrowserContext } from './ffBrowser';
import type { Protocol } from './protocol';
import type { RegisteredListener } from '../utils/eventsHelper';
import type * as frames from '../frames';
import type { PageDelegate } from '../page';
import type * as types from '../types';

export const UTILITY_WORLD_NAME = '__playwright_utility_world__';

export class FFPage implements PageDelegate {
  readonly cspErrorsAsynchronousForInlineScripts = true;
  readonly rawMouse: RawMouseImpl;
  readonly rawKeyboard: RawKeyboardImpl;
  readonly rawTouchscreen: RawTouchscreenImpl;
  readonly _session: FFSession;
  readonly _page: Page;
  readonly _networkManager: FFNetworkManager;
  readonly _browserContext: FFBrowserContext;
  private _reportedAsNew = false;
  readonly _opener: FFPage | null;
  private readonly _contextIdToContext: Map<string, dom.FrameExecutionContext>;
  private _eventListeners: RegisteredListener[];
  private _workers = new Map<string, { frameId: string, session: FFSession }>();
  private _screencastId: string | undefined;
  private _initScripts: { initScript: InitScript, worldName?: string }[] = [];

  constructor(session: FFSession, browserContext: FFBrowserContext, opener: FFPage | null) {
    this._session = session;
    this._opener = opener;
    this.rawKeyboard = new RawKeyboardImpl(session);
    this.rawMouse = new RawMouseImpl(session);
    this.rawTouchscreen = new RawTouchscreenImpl(session);
    this._contextIdToContext = new Map();
    this._browserContext = browserContext;
    this._page = new Page(this, browserContext);
    this.rawMouse.setPage(this._page);
    this._networkManager = new FFNetworkManager(session, this._page);
    this._page.on(Page.Events.FrameDetached, frame => this._removeContextsForFrame(frame));
    // TODO: remove Page.willOpenNewWindowAsynchronously from the protocol.
    this._eventListeners = [
      eventsHelper.addEventListener(this._session, 'Page.eventFired', this._onEventFired.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.frameAttached', this._onFrameAttached.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.frameDetached', this._onFrameDetached.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.navigationAborted', this._onNavigationAborted.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.navigationCommitted', this._onNavigationCommitted.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.navigationStarted', this._onNavigationStarted.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.sameDocumentNavigation', this._onSameDocumentNavigation.bind(this)),
      eventsHelper.addEventListener(this._session, 'Runtime.executionContextCreated', this._onExecutionContextCreated.bind(this)),
      eventsHelper.addEventListener(this._session, 'Runtime.executionContextDestroyed', this._onExecutionContextDestroyed.bind(this)),
      eventsHelper.addEventListener(this._session, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.linkClicked', event => this._onLinkClicked(event.phase)),
      eventsHelper.addEventListener(this._session, 'Page.uncaughtError', this._onUncaughtError.bind(this)),
      eventsHelper.addEventListener(this._session, 'Runtime.console', this._onConsole.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.dialogOpened', this._onDialogOpened.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.bindingCalled', this._onBindingCalled.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.fileChooserOpened', this._onFileChooserOpened.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.workerCreated', this._onWorkerCreated.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.workerDestroyed', this._onWorkerDestroyed.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.dispatchMessageFromWorker', this._onDispatchMessageFromWorker.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.crashed', this._onCrashed.bind(this)),

      eventsHelper.addEventListener(this._session, 'Page.webSocketCreated', this._onWebSocketCreated.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.webSocketClosed', this._onWebSocketClosed.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.webSocketFrameReceived', this._onWebSocketFrameReceived.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.webSocketFrameSent', this._onWebSocketFrameSent.bind(this)),
      eventsHelper.addEventListener(this._session, 'Page.screencastFrame', this._onScreencastFrame.bind(this)),

    ];

    const screencast = this._page.screencast;
    const videoOptions = screencast.launchVideoRecorder();
    if (videoOptions)
      screencast.startVideoRecording(videoOptions).catch(e => debugLogger.log('error', e));

    this._session.once('Page.ready', () => {
      if (this._reportedAsNew)
        return;
      this._reportedAsNew = true;
      this._page.reportAsNew(this._opener?._page);
    });
    // Ideally, we somehow ensure that utility world is created before Page.ready arrives, but currently it is racy.
    // Therefore, we can end up with an initialized page without utility world, although very unlikely.
    this.addInitScript(new InitScript(''), UTILITY_WORLD_NAME).catch(e => this._markAsError(e));
  }

  async _markAsError(error: Error) {
    // Same error may be reported twice: channel disconnected and session.send fails.
    if (this._reportedAsNew)
      return;
    this._reportedAsNew = true;
    this._page.reportAsNew(this._opener?._page, error);
  }

  _onWebSocketCreated(event: Protocol.Page.webSocketCreatedPayload) {
    this._page.frameManager.onWebSocketCreated(webSocketId(event.frameId, event.wsid), event.requestURL);
    this._page.frameManager.onWebSocketRequest(webSocketId(event.frameId, event.wsid));
  }

  _onWebSocketClosed(event: Protocol.Page.webSocketClosedPayload) {
    if (event.error)
      this._page.frameManager.webSocketError(webSocketId(event.frameId, event.wsid), event.error);
    this._page.frameManager.webSocketClosed(webSocketId(event.frameId, event.wsid));
  }

  _onWebSocketFrameReceived(event: Protocol.Page.webSocketFrameReceivedPayload) {
    this._page.frameManager.webSocketFrameReceived(webSocketId(event.frameId, event.wsid), event.opcode, event.data);
  }

  _onWebSocketFrameSent(event: Protocol.Page.webSocketFrameSentPayload) {
    this._page.frameManager.onWebSocketFrameSent(webSocketId(event.frameId, event.wsid), event.opcode, event.data);
  }

  _onExecutionContextCreated(payload: Protocol.Runtime.executionContextCreatedPayload) {
    const { executionContextId, auxData } = payload;
    const frame = this._page.frameManager.frame(auxData.frameId!);
    if (!frame)
      return;
    const delegate = new FFExecutionContext(this._session, executionContextId);
    let worldName: types.World|null = null;
    if (auxData.name === UTILITY_WORLD_NAME)
      worldName = 'utility';
    else if (!auxData.name)
      worldName = 'main';
    const context = new dom.FrameExecutionContext(delegate, frame, worldName);
    if (worldName)
      frame._contextCreated(worldName, context);
    this._contextIdToContext.set(executionContextId, context);
  }

  _onExecutionContextDestroyed(payload: Protocol.Runtime.executionContextDestroyedPayload) {
    const { executionContextId } = payload;
    const context = this._contextIdToContext.get(executionContextId);
    if (!context)
      return;
    this._contextIdToContext.delete(executionContextId);
    context.frame._contextDestroyed(context);
  }

  _onExecutionContextsCleared() {
    for (const executionContextId of Array.from(this._contextIdToContext.keys()))
      this._onExecutionContextDestroyed({ executionContextId });
  }

  private _removeContextsForFrame(frame: frames.Frame) {
    for (const [contextId, context] of this._contextIdToContext) {
      if (context.frame === frame)
        this._contextIdToContext.delete(contextId);
    }
  }

  _onLinkClicked(phase: 'before' | 'after') {
    if (phase === 'before')
      this._page.frameManager.frameWillPotentiallyRequestNavigation();
    else
      this._page.frameManager.frameDidPotentiallyRequestNavigation();
  }

  _onNavigationStarted(params: Protocol.Page.navigationStartedPayload) {
    this._page.frameManager.frameRequestedNavigation(params.frameId, params.navigationId);
  }

  _onNavigationAborted(params: Protocol.Page.navigationAbortedPayload) {
    this._page.frameManager.frameAbortedNavigation(params.frameId, params.errorText, params.navigationId);
  }

  _onNavigationCommitted(params: Protocol.Page.navigationCommittedPayload) {
    for (const [workerId, worker] of this._workers) {
      if (worker.frameId === params.frameId)
        this._onWorkerDestroyed({ workerId });
    }
    this._page.frameManager.frameCommittedNewDocumentNavigation(params.frameId, params.url, params.name || '', params.navigationId || '', false);
  }

  _onSameDocumentNavigation(params: Protocol.Page.sameDocumentNavigationPayload) {
    this._page.frameManager.frameCommittedSameDocumentNavigation(params.frameId, params.url);
  }

  _onFrameAttached(params: Protocol.Page.frameAttachedPayload) {
    this._page.frameManager.frameAttached(params.frameId, params.parentFrameId);
  }

  _onFrameDetached(params: Protocol.Page.frameDetachedPayload) {
    this._page.frameManager.frameDetached(params.frameId);
  }

  _onEventFired(payload: Protocol.Page.eventFiredPayload) {
    const { frameId, name } = payload;
    if (name === 'load')
      this._page.frameManager.frameLifecycleEvent(frameId, 'load');
    if (name === 'DOMContentLoaded')
      this._page.frameManager.frameLifecycleEvent(frameId, 'domcontentloaded');
  }

  _onUncaughtError(params: Protocol.Page.uncaughtErrorPayload) {
    const { name, message } = splitErrorMessage(params.message);
    const error = new Error(message);
    error.stack = params.message + '\n' + params.stack.split('\n').filter(Boolean).map(a => a.replace(/([^@]*)@(.*)/, '    at $1 ($2)')).join('\n');
    error.name = name;
    this._page.addPageError(error);
  }

  _onConsole(payload: Protocol.Runtime.consolePayload) {
    const { type, args, executionContextId, location } = payload;
    const context = this._contextIdToContext.get(executionContextId);
    if (!context)
      return;
    // Juggler reports 'warn' for some internal messages generated by the browser.
    this._page.addConsoleMessage(null, type === 'warn' ? 'warning' : type, args.map(arg => createHandle(context, arg)), location);
  }

  _onDialogOpened(params: Protocol.Page.dialogOpenedPayload) {
    this._page.browserContext.dialogManager.dialogDidOpen(new dialog.Dialog(
        this._page,
        params.type,
        params.message,
        async (accept: boolean, promptText?: string) => {
          await this._session.sendMayFail('Page.handleDialog', { dialogId: params.dialogId, accept, promptText });
        },
        params.defaultValue));
  }

  async _onBindingCalled(event: Protocol.Page.bindingCalledPayload) {
    const pageOrError = await this._page.waitForInitializedOrError();
    if (!(pageOrError instanceof Error)) {
      const context = this._contextIdToContext.get(event.executionContextId);
      if (context)
        await this._page.onBindingCalled(event.payload, context);
    }
  }

  async _onFileChooserOpened(payload: Protocol.Page.fileChooserOpenedPayload) {
    const { executionContextId, element } = payload;
    const context = this._contextIdToContext.get(executionContextId);
    if (!context)
      return;
    const handle = createHandle(context, element).asElement()!;
    await this._page._onFileChooserOpened(handle);
  }

  async _onWorkerCreated(event: Protocol.Page.workerCreatedPayload) {
    const workerId = event.workerId;
    const worker = new Worker(this._page, event.url);
    const workerSession = new FFSession(this._session._connection, workerId, (message: any) => {
      this._session.send('Page.sendMessageToWorker', {
        frameId: event.frameId,
        workerId: workerId,
        message: JSON.stringify(message)
      }).catch(e => {
        workerSession.dispatchMessage({ id: message.id, method: '', params: {}, error: { message: e.message, data: undefined } });
      });
    });
    this._workers.set(workerId, { session: workerSession, frameId: event.frameId });
    this._page.addWorker(workerId, worker);
    workerSession.once('Runtime.executionContextCreated', event => {
      worker.createExecutionContext(new FFExecutionContext(workerSession, event.executionContextId));
      worker.workerScriptLoaded();
    });
    workerSession.on('Runtime.console', event => {
      const { type, args, location } = event;
      const context = worker.existingExecutionContext!;
      this._page.addConsoleMessage(worker, type, args.map(arg => createHandle(context, arg)), location);
    });
    // Note: we receive worker exceptions directly from the page.
  }

  _onWorkerDestroyed(event: Protocol.Page.workerDestroyedPayload) {
    const workerId = event.workerId;
    const worker = this._workers.get(workerId);
    if (!worker)
      return;
    worker.session.dispose();
    this._workers.delete(workerId);
    this._page.removeWorker(workerId);
  }

  async _onDispatchMessageFromWorker(event: Protocol.Page.dispatchMessageFromWorkerPayload) {
    const worker = this._workers.get(event.workerId);
    if (!worker)
      return;
    worker.session.dispatchMessage(JSON.parse(event.message));
  }

  async _onCrashed(event: Protocol.Page.crashedPayload) {
    this._session.markAsCrashed();
    this._page._didCrash();
  }


  didClose() {
    this._markAsError(new TargetClosedError(this._page.closeReason()));
    this._session.dispose();
    eventsHelper.removeEventListeners(this._eventListeners);
    this._networkManager.dispose();
    this._page._didClose();
  }

  async navigateFrame(frame: frames.Frame, url: string, referer: string | undefined): Promise<frames.GotoResult> {
    const response = await this._session.send('Page.navigate', { url, referer, frameId: frame._id });
    return { newDocumentId: response.navigationId || undefined };
  }

  async updateExtraHTTPHeaders(): Promise<void> {
    await this._session.send('Network.setExtraHTTPHeaders', { headers: this._page.extraHTTPHeaders() || [] });
  }

  async updateEmulatedViewportSize(): Promise<void> {
    const viewportSize = this._page.emulatedSize()?.viewport ?? null;
    await this._session.send('Page.setViewportSize', { viewportSize });
  }

  async bringToFront(): Promise<void> {
    await this._session.send('Page.bringToFront', {});
  }

  async updateEmulateMedia(): Promise<void> {
    const emulatedMedia = this._page.emulatedMedia();
    const colorScheme = emulatedMedia.colorScheme === 'no-override' ? undefined : emulatedMedia.colorScheme;
    const reducedMotion = emulatedMedia.reducedMotion === 'no-override' ? undefined : emulatedMedia.reducedMotion;
    const forcedColors = emulatedMedia.forcedColors === 'no-override' ? undefined : emulatedMedia.forcedColors;
    const contrast = emulatedMedia.contrast === 'no-override' ? undefined : emulatedMedia.contrast;
    await this._session.send('Page.setEmulatedMedia', {
      // Empty string means reset.
      type: emulatedMedia.media === 'no-override' ? '' : emulatedMedia.media,
      colorScheme,
      reducedMotion,
      forcedColors,
      contrast,
    });
  }

  async updateRequestInterception(): Promise<void> {
    await this._networkManager.setRequestInterception(this._page.needsRequestInterception());
  }

  async updateFileChooserInterception() {
    const enabled = this._page.fileChooserIntercepted();
    await this._session.send('Page.setInterceptFileChooserDialog', { enabled }).catch(() => {}); // target can be closed.
  }

  async reload(): Promise<void> {
    await this._session.send('Page.reload');
  }

  async goBack(): Promise<boolean> {
    const { success } = await this._session.send('Page.goBack', { frameId: this._page.mainFrame()._id });
    return success;
  }

  async goForward(): Promise<boolean> {
    const { success } = await this._session.send('Page.goForward', { frameId: this._page.mainFrame()._id });
    return success;
  }

  async requestGC(): Promise<void> {
    await this._session.send('Heap.collectGarbage');
  }

  async addInitScript(initScript: InitScript, worldName?: string): Promise<void> {
    this._initScripts.push({ initScript, worldName });
    await this._updateInitScripts();
  }

  async removeInitScripts(initScripts: InitScript[]): Promise<void> {
    const set = new Set(initScripts);
    this._initScripts = this._initScripts.filter(s => !set.has(s.initScript));
    await this._updateInitScripts();
  }

  private async _updateInitScripts() {
    await this._session.send('Page.setInitScripts', { scripts: this._initScripts.map(s => ({ script: s.initScript.source, worldName: s.worldName })) });
  }

  async closePage(runBeforeUnload: boolean): Promise<void> {
    await this._session.send('Page.close', { runBeforeUnload });
  }

  async setBackgroundColor(color?: { r: number; g: number; b: number; a: number; }): Promise<void> {
    if (color)
      throw new Error('Not implemented');
  }

  async takeScreenshot(progress: Progress, format: 'png' | 'jpeg', documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, quality: number | undefined, fitsViewport: boolean, scale: 'css' | 'device'): Promise<Buffer> {
    if (!documentRect) {
      const scrollOffset = await this._page.mainFrame().waitForFunctionValueInUtility(progress, () => ({ x: window.scrollX, y: window.scrollY }));
      documentRect = {
        x: viewportRect!.x + scrollOffset.x,
        y: viewportRect!.y + scrollOffset.y,
        width: viewportRect!.width,
        height: viewportRect!.height,
      };
    }
    const { data } = await progress.race(this._session.send('Page.screenshot', {
      mimeType: ('image/' + format) as ('image/png' | 'image/jpeg'),
      clip: documentRect,
      quality,
      omitDeviceScaleFactor: scale === 'css',
    }));
    return Buffer.from(data, 'base64');
  }

  async getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null> {
    const { contentFrameId } = await this._session.send('Page.describeNode', {
      frameId: handle._context.frame._id,
      objectId: handle._objectId,
    });
    if (!contentFrameId)
      return null;
    return this._page.frameManager.frame(contentFrameId);
  }

  async getOwnerFrame(handle: dom.ElementHandle): Promise<string | null> {
    const { ownerFrameId } = await this._session.send('Page.describeNode', {
      frameId: handle._context.frame._id,
      objectId: handle._objectId
    });
    return ownerFrameId || null;
  }

  async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
    const quads = await this.getContentQuads(handle);
    if (!quads || !quads.length)
      return null;
    let minX = Infinity;
    let maxX = -Infinity;
    let minY = Infinity;
    let maxY = -Infinity;
    for (const quad of quads) {
      for (const point of quad) {
        minX = Math.min(minX, point.x);
        maxX = Math.max(maxX, point.x);
        minY = Math.min(minY, point.y);
        maxY = Math.max(maxY, point.y);
      }
    }
    return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
  }

  async scrollRectIntoViewIfNeeded(handle: dom.ElementHandle, rect?: types.Rect): Promise<'error:notvisible' | 'error:notconnected' | 'done'> {
    return await this._session.send('Page.scrollIntoViewIfNeeded', {
      frameId: handle._context.frame._id,
      objectId: handle._objectId,
      rect,
    }).then(() => 'done' as const).catch(e => {
      if (e instanceof Error && e.message.includes('Node is detached from document'))
        return 'error:notconnected';
      if (e instanceof Error && e.message.includes('Node does not have a layout object'))
        return 'error:notvisible';
      throw e;
    });
  }

  async startScreencast(options: { width: number, height: number, quality: number }): Promise<void> {
    await this._session.send('Page.startScreencast', options);
  }

  async stopScreencast(): Promise<void> {
    await this._session.sendMayFail('Page.stopScreencast');
  }

  private _onScreencastFrame(event: Protocol.Page.screencastFramePayload) {
    this._page.screencast.throttleFrameAck(() => {
      this._session.sendMayFail('Page.screencastFrameAck');
    });

    const buffer = Buffer.from(event.data, 'base64');
    this._page.emit(Page.Events.ScreencastFrame, {
      buffer,
      frameSwapWallTime: event.timestamp * 1000, // timestamp is in seconds, we need to convert to milliseconds.
      width: event.deviceWidth,
      height: event.deviceHeight,
    });
  }

  rafCountForStablePosition(): number {
    return 1;
  }

  async getContentQuads(handle: dom.ElementHandle): Promise<types.Quad[] | null> {
    const result = await this._session.sendMayFail('Page.getContentQuads', {
      frameId: handle._context.frame._id,
      objectId: handle._objectId,
    });
    if (!result)
      return null;
    return result.quads.map(quad => [quad.p1, quad.p2, quad.p3, quad.p4]);
  }

  async setInputFilePaths(handle: dom.ElementHandle<HTMLInputElement>, files: string[]): Promise<void> {
    await this._session.send('Page.setFileInputFiles', {
      frameId: handle._context.frame._id,
      objectId: handle._objectId,
      files
    });
  }

  async adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>> {
    const result = await this._session.send('Page.adoptNode', {
      frameId: handle._context.frame._id,
      objectId: handle._objectId,
      executionContextId: (to.delegate as FFExecutionContext)._executionContextId
    });
    if (!result.remoteObject)
      throw new Error(dom.kUnableToAdoptErrorMessage);
    return createHandle(to, result.remoteObject) as dom.ElementHandle<T>;
  }

  async inputActionEpilogue(): Promise<void> {
  }

  async resetForReuse(progress: Progress): Promise<void> {
    // Firefox sometimes keeps the last mouse position in the page,
    // which affects things like hovered state.
    // See https://github.com/microsoft/playwright/issues/22432.
    // Move mouse to (-1, -1) to avoid anything being hovered.
    await this.rawMouse.move(progress, -1, -1, 'none', new Set(), new Set(), false);
  }

  async getFrameElement(frame: frames.Frame): Promise<dom.ElementHandle> {
    const parent = frame.parentFrame();
    if (!parent)
      throw new Error('Frame has been detached.');
    const context = await parent._mainContext();
    const result = await this._session.send('Page.adoptNode', {
      frameId: frame._id,
      executionContextId: (context.delegate as FFExecutionContext)._executionContextId
    });
    if (!result.remoteObject)
      throw new Error('Frame has been detached.');
    return createHandle(context, result.remoteObject) as dom.ElementHandle;
  }

  shouldToggleStyleSheetToSyncAnimations(): boolean {
    return false;
  }
}

function webSocketId(frameId: string, wsid: string): string {
  return `${frameId}---${wsid}`;
}