refactor: move Target to api (#10602)

This commit is contained in:
Alex Rudenko 2023-07-21 09:04:14 +02:00 committed by GitHub
parent c60572a1ca
commit 0e60ce4cec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 215 additions and 127 deletions

View File

@ -52,6 +52,7 @@ sidebar_label: API
| [InterceptResolutionAction](./puppeteer.interceptresolutionaction.md) | |
| [LocatorEmittedEvents](./puppeteer.locatoremittedevents.md) | All the events that a locator instance may emit. |
| [PageEmittedEvents](./puppeteer.pageemittedevents.md) | All the events that a page instance may emit. |
| [TargetType](./puppeteer.targettype.md) | |
## Functions

View File

@ -10,20 +10,13 @@ Identifies what kind of target this is.
```typescript
class Target {
type():
| 'page'
| 'background_page'
| 'service_worker'
| 'shared_worker'
| 'other'
| 'browser'
| 'webview';
type(): TargetType;
}
```
**Returns:**
'page' \| 'background_page' \| 'service_worker' \| 'shared_worker' \| 'other' \| 'browser' \| 'webview'
[TargetType](./puppeteer.targettype.md)
## Remarks

View File

@ -0,0 +1,23 @@
---
sidebar_label: TargetType
---
# TargetType enum
#### Signature:
```typescript
export declare enum TargetType
```
## Enumeration Members
| Member | Value | Description |
| --------------- | ---------------------------------------- | ----------- |
| BACKGROUND_PAGE | <code>&quot;background_page&quot;</code> | |
| BROWSER | <code>&quot;browser&quot;</code> | |
| OTHER | <code>&quot;other&quot;</code> | |
| PAGE | <code>&quot;page&quot;</code> | |
| SERVICE_WORKER | <code>&quot;service_worker&quot;</code> | |
| SHARED_WORKER | <code>&quot;shared_worker&quot;</code> | |
| WEBVIEW | <code>&quot;webview&quot;</code> | |

View File

@ -21,10 +21,10 @@ import {ChildProcess} from 'child_process';
import {Protocol} from 'devtools-protocol';
import {EventEmitter} from '../common/EventEmitter.js';
import type {Target} from '../common/Target.js'; // TODO: move to ./api
import type {BrowserContext} from './BrowserContext.js';
import type {Page} from './Page.js';
import type {Target} from './Target.js';
/**
* BrowserContext options.

View File

@ -15,10 +15,10 @@
*/
import {EventEmitter} from '../common/EventEmitter.js';
import {Target} from '../common/Target.js';
import type {Permission, Browser} from './Browser.js';
import {Page} from './Page.js';
import type {Target} from './Target.js';
/**
* BrowserContexts provide a way to operate multiple independent browser

View File

@ -43,7 +43,6 @@ import {
PDFOptions,
} from '../common/PDFOptions.js';
import type {Viewport} from '../common/PuppeteerViewport.js';
import type {Target} from '../common/Target.js';
import type {Tracing} from '../common/Tracing.js';
import type {
EvaluateFunc,
@ -74,6 +73,7 @@ import type {
import {Keyboard, KeyboardTypeOptions, Mouse, Touchscreen} from './Input.js';
import type {JSHandle} from './JSHandle.js';
import {Locator, NodeLocator, UnionLocatorOf} from './locators/locators.js';
import type {Target} from './Target.js';
/**
* @public

View File

@ -0,0 +1,106 @@
/**
* Copyright 2023 Google Inc. All rights reserved.
*
* 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 type {Browser} from '../api/Browser.js';
import type {BrowserContext} from '../api/BrowserContext.js';
import {Page} from '../api/Page.js';
import {CDPSession} from '../common/Connection.js';
import {WebWorker} from '../common/WebWorker.js';
/**
* @public
*/
export enum TargetType {
PAGE = 'page',
BACKGROUND_PAGE = 'background_page',
SERVICE_WORKER = 'service_worker',
SHARED_WORKER = 'shared_worker',
BROWSER = 'browser',
WEBVIEW = 'webview',
OTHER = 'other',
}
/**
* Target represents a
* {@link https://chromedevtools.github.io/devtools-protocol/tot/Target/ | CDP target}.
* In CDP a target is something that can be debugged such a frame, a page or a
* worker.
* @public
*/
export class Target {
/**
* @internal
*/
protected constructor() {}
/**
* If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.
*/
async worker(): Promise<WebWorker | null> {
return null;
}
/**
* If the target is not of type `"page"`, `"webview"` or `"background_page"`,
* returns `null`.
*/
async page(): Promise<Page | null> {
return null;
}
url(): string {
throw new Error('not implemented');
}
/**
* Creates a Chrome Devtools Protocol session attached to the target.
*/
createCDPSession(): Promise<CDPSession> {
throw new Error('not implemented');
}
/**
* Identifies what kind of target this is.
*
* @remarks
*
* See {@link https://developer.chrome.com/extensions/background_pages | docs} for more info about background pages.
*/
type(): TargetType {
throw new Error('not implemented');
}
/**
* Get the browser the target belongs to.
*/
browser(): Browser {
throw new Error('not implemented');
}
/**
* Get the browser context the target belongs to.
*/
browserContext(): BrowserContext {
throw new Error('not implemented');
}
/**
* Get the target that opened this target. Top-level targets return `null`.
*/
opener(): Target | undefined {
throw new Error('not implemented');
}
}

View File

@ -24,3 +24,4 @@ export * from './Frame.js';
export * from './HTTPResponse.js';
export * from './HTTPRequest.js';
export * from './locators/locators.js';
export * from './Target.js';

View File

@ -32,6 +32,7 @@ import {
} from '../api/Browser.js';
import {BrowserContext} from '../api/BrowserContext.js';
import {Page} from '../api/Page.js';
import {Target} from '../api/Target.js';
import {assert} from '../util/assert.js';
import {Deferred} from '../util/Deferred.js';
@ -43,7 +44,7 @@ import {
InitializationStatus,
OtherTarget,
PageTarget,
Target,
CDPTarget,
WorkerTarget,
} from './Target.js';
import {TargetManager, TargetManagerEmittedEvents} from './TargetManager.js';
@ -97,7 +98,7 @@ export class CDPBrowser extends BrowserBase {
/**
* @internal
*/
override get _targets(): Map<string, Target> {
override get _targets(): Map<string, CDPTarget> {
return this.#targetManager.getAvailableTargets();
}
@ -366,7 +367,7 @@ export class CDPBrowser extends BrowserBase {
);
};
#onAttachedToTarget = async (target: Target) => {
#onAttachedToTarget = async (target: CDPTarget) => {
if (
(await target._initializedDeferred.valueOrThrow()) ===
InitializationStatus.SUCCESS
@ -378,7 +379,7 @@ export class CDPBrowser extends BrowserBase {
}
};
#onDetachedFromTarget = async (target: Target): Promise<void> => {
#onDetachedFromTarget = async (target: CDPTarget): Promise<void> => {
target._initializedDeferred.resolve(InitializationStatus.ABORTED);
target._isClosedDeferred.resolve();
if (
@ -392,7 +393,7 @@ export class CDPBrowser extends BrowserBase {
}
};
#onTargetChanged = ({target}: {target: Target}): void => {
#onTargetChanged = ({target}: {target: CDPTarget}): void => {
this.emit(BrowserEmittedEvents.TargetChanged, target);
target
.browserContext()
@ -463,7 +464,7 @@ export class CDPBrowser extends BrowserBase {
* All active targets inside the Browser. In case of multiple browser contexts, returns
* an array with all the targets in all browser contexts.
*/
override targets(): Target[] {
override targets(): CDPTarget[] {
return Array.from(
this.#targetManager.getAvailableTargets().values()
).filter(target => {
@ -476,7 +477,7 @@ export class CDPBrowser extends BrowserBase {
/**
* The target associated with the browser.
*/
override target(): Target {
override target(): CDPTarget {
const browserTarget = this.targets().find(target => {
return target.type() === 'browser';
});
@ -504,11 +505,13 @@ export class CDPBrowser extends BrowserBase {
* ```
*/
override async waitForTarget(
predicate: (x: Target) => boolean | Promise<boolean>,
predicate: (x: CDPTarget) => boolean | Promise<boolean>,
options: WaitForTargetOptions = {}
): Promise<Target> {
): Promise<CDPTarget> {
const {timeout = 30000} = options;
const targetDeferred = Deferred.create<Target | PromiseLike<Target>>();
const targetDeferred = Deferred.create<
CDPTarget | PromiseLike<CDPTarget>
>();
this.on(BrowserEmittedEvents.TargetCreated, check);
this.on(BrowserEmittedEvents.TargetChanged, check);
@ -527,7 +530,7 @@ export class CDPBrowser extends BrowserBase {
this.off(BrowserEmittedEvents.TargetChanged, check);
}
async function check(target: Target): Promise<void> {
async function check(target: CDPTarget): Promise<void> {
if ((await predicate(target)) && !targetDeferred.resolved()) {
targetDeferred.resolve(target);
}
@ -596,7 +599,7 @@ export class CDPBrowserContext extends BrowserContext {
/**
* An array of all active targets inside the browser context.
*/
override targets(): Target[] {
override targets(): CDPTarget[] {
return this.#browser.targets().filter(target => {
return target.browserContext() === this;
});
@ -623,9 +626,9 @@ export class CDPBrowserContext extends BrowserContext {
* that matches the `predicate` function.
*/
override waitForTarget(
predicate: (x: Target) => boolean | Promise<boolean>,
predicate: (x: CDPTarget) => boolean | Promise<boolean>,
options: {timeout?: number} = {}
): Promise<Target> {
): Promise<CDPTarget> {
return this.#browser.waitForTarget(target => {
return target.browserContext() === this && predicate(target);
}, options);
@ -636,7 +639,7 @@ export class CDPBrowserContext extends BrowserContext {
*
* @returns Promise which resolves to an array of all open pages.
* Non visible pages, such as `"background_page"`, will not be listed here.
* You can find them using {@link Target.page | the target page}.
* You can find them using {@link CDPTarget.page | the target page}.
*/
override async pages(): Promise<Page[]> {
const pages = await Promise.all(

View File

@ -22,7 +22,7 @@ import {Deferred} from '../util/Deferred.js';
import {CDPSession, Connection} from './Connection.js';
import {EventEmitter} from './EventEmitter.js';
import {InitializationStatus, Target} from './Target.js';
import {InitializationStatus, CDPTarget} from './Target.js';
import {
TargetInterceptor,
TargetFactory,
@ -55,11 +55,11 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager {
* A target is added to this map once ChromeTargetManager has created
* a Target and attached at least once to it.
*/
#attachedTargetsByTargetId = new Map<string, Target>();
#attachedTargetsByTargetId = new Map<string, CDPTarget>();
/**
* Tracks which sessions attach to which target.
*/
#attachedTargetsBySessionId = new Map<string, Target>();
#attachedTargetsBySessionId = new Map<string, CDPTarget>();
/**
* If a target was filtered out by `targetFilterCallback`, we still receive
* events about it from CDP, but we don't forward them to the rest of Puppeteer.
@ -115,7 +115,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager {
targetId,
targetInfo,
] of this.#discoveredTargetsByTargetId.entries()) {
const targetForFilter = new Target(
const targetForFilter = new CDPTarget(
targetInfo,
undefined,
undefined,
@ -151,7 +151,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager {
this.#removeAttachmentListeners(this.#connection);
}
getAvailableTargets(): Map<string, Target> {
getAvailableTargets(): Map<string, CDPTarget> {
return this.#attachedTargetsByTargetId;
}

View File

@ -22,7 +22,7 @@ import {Deferred} from '../util/Deferred.js';
import {CDPSession, Connection} from './Connection.js';
import {EventEmitter} from './EventEmitter.js';
import {Target} from './Target.js';
import {CDPTarget} from './Target.js';
import {
TargetFactory,
TargetInterceptor,
@ -66,11 +66,11 @@ export class FirefoxTargetManager
*
* The target is removed from here once it's been destroyed.
*/
#availableTargetsByTargetId = new Map<string, Target>();
#availableTargetsByTargetId = new Map<string, CDPTarget>();
/**
* Tracks which sessions attach to which target.
*/
#availableTargetsBySessionId = new Map<string, Target>();
#availableTargetsBySessionId = new Map<string, CDPTarget>();
/**
* If a target was filtered out by `targetFilterCallback`, we still receive
* events about it from CDP, but we don't forward them to the rest of Puppeteer.
@ -155,7 +155,7 @@ export class FirefoxTargetManager
}
}
getAvailableTargets(): Map<string, Target> {
getAvailableTargets(): Map<string, CDPTarget> {
return this.#availableTargetsByTargetId;
}

View File

@ -30,7 +30,7 @@ import {FrameTree} from './FrameTree.js';
import {IsolatedWorld} from './IsolatedWorld.js';
import {MAIN_WORLD, PUPPETEER_WORLD} from './IsolatedWorlds.js';
import {NetworkManager} from './NetworkManager.js';
import {Target} from './Target.js';
import {CDPTarget} from './Target.js';
import {TimeoutSettings} from './TimeoutSettings.js';
import {debugError, PuppeteerURL} from './util.js';
@ -216,7 +216,7 @@ export class FrameManager extends EventEmitter {
return this._frameTree.getById(frameId) || null;
}
onAttachedToTarget(target: Target): void {
onAttachedToTarget(target: CDPTarget): void {
if (target._getTargetInfo().type !== 'iframe') {
return;
}

View File

@ -65,7 +65,7 @@ import {
} from './NetworkManager.js';
import {PDFOptions} from './PDFOptions.js';
import {Viewport} from './PuppeteerViewport.js';
import {Target} from './Target.js';
import {CDPTarget} from './Target.js';
import {TargetManagerEmittedEvents} from './TargetManager.js';
import {TaskQueue} from './TaskQueue.js';
import {TimeoutSettings} from './TimeoutSettings.js';
@ -97,7 +97,7 @@ export class CDPPage extends Page {
*/
static async _create(
client: CDPSession,
target: Target,
target: CDPTarget,
ignoreHTTPSErrors: boolean,
defaultViewport: Viewport | null,
screenshotTaskQueue: TaskQueue
@ -125,7 +125,7 @@ export class CDPPage extends Page {
#closed = false;
#client: CDPSession;
#target: Target;
#target: CDPTarget;
#keyboard: CDPKeyboard;
#mouse: CDPMouse;
#timeoutSettings = new TimeoutSettings();
@ -150,7 +150,7 @@ export class CDPPage extends Page {
*/
constructor(
client: CDPSession,
target: Target,
target: CDPTarget,
ignoreHTTPSErrors: boolean,
screenshotTaskQueue: TaskQueue
) {
@ -266,7 +266,7 @@ export class CDPPage extends Page {
.catch(debugError);
}
#onDetachedFromTarget = (target: Target) => {
#onDetachedFromTarget = (target: CDPTarget) => {
const sessionId = target._session()?.id();
const worker = this.#workers.get(sessionId!);
if (!worker) {
@ -276,7 +276,7 @@ export class CDPPage extends Page {
this.emit(PageEmittedEvents.WorkerDestroyed, worker);
};
#onAttachedToTarget = (createdTarget: Target) => {
#onAttachedToTarget = (createdTarget: CDPTarget) => {
this.#frameManager.onAttachedToTarget(createdTarget);
if (createdTarget._getTargetInfo().type === 'worker') {
const session = createdTarget._session();
@ -387,7 +387,7 @@ export class CDPPage extends Page {
return await this.#emulationManager.setGeolocation(options);
}
override target(): Target {
override target(): CDPTarget {
return this.#target;
}

View File

@ -19,6 +19,7 @@ import {Protocol} from 'devtools-protocol';
import type {Browser} from '../api/Browser.js';
import type {BrowserContext} from '../api/BrowserContext.js';
import {Page, PageEmittedEvents} from '../api/Page.js';
import {Target, TargetType} from '../api/Target.js';
import {Deferred} from '../util/Deferred.js';
import {CDPSession} from './Connection.js';
@ -38,14 +39,9 @@ export enum InitializationStatus {
}
/**
* Target represents a
* {@link https://chromedevtools.github.io/devtools-protocol/tot/Target/ | CDP target}.
* In CDP a target is something that can be debugged such a frame, a page or a
* worker.
*
* @public
* @internal
*/
export class Target {
export class CDPTarget extends Target {
#browserContext?: BrowserContext;
#session?: CDPSession;
#targetInfo: Protocol.Target.TargetInfo;
@ -81,6 +77,7 @@ export class Target {
| ((isAutoAttachEmulated: boolean) => Promise<CDPSession>)
| undefined
) {
super();
this.#session = session;
this.#targetManager = targetManager;
this.#targetInfo = targetInfo;
@ -108,16 +105,37 @@ export class Target {
return this.#sessionFactory;
}
/**
* Creates a Chrome Devtools Protocol session attached to the target.
*/
createCDPSession(): Promise<CDPSession> {
override createCDPSession(): Promise<CDPSession> {
if (!this.#sessionFactory) {
throw new Error('sessionFactory is not initialized');
}
return this.#sessionFactory(false);
}
override url(): string {
return this.#targetInfo.url;
}
override type(): TargetType {
const type = this.#targetInfo.type;
switch (type) {
case 'page':
return TargetType.PAGE;
case 'background_page':
return TargetType.BACKGROUND_PAGE;
case 'service_worker':
return TargetType.SERVICE_WORKER;
case 'shared_worker':
return TargetType.SHARED_WORKER;
case 'browser':
return TargetType.BROWSER;
case 'webview':
return TargetType.WEBVIEW;
default:
return TargetType.OTHER;
}
}
/**
* @internal
*/
@ -135,70 +153,21 @@ export class Target {
return this.#targetInfo;
}
/**
* If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.
*/
async worker(): Promise<WebWorker | null> {
return null;
}
url(): string {
return this.#targetInfo.url;
}
/**
* Identifies what kind of target this is.
*
* @remarks
*
* See {@link https://developer.chrome.com/extensions/background_pages | docs} for more info about background pages.
*/
type():
| 'page'
| 'background_page'
| 'service_worker'
| 'shared_worker'
| 'other'
| 'browser'
| 'webview' {
const type = this.#targetInfo.type;
if (
type === 'page' ||
type === 'background_page' ||
type === 'service_worker' ||
type === 'shared_worker' ||
type === 'browser' ||
type === 'webview'
) {
return type;
}
return 'other';
}
/**
* Get the browser the target belongs to.
*/
browser(): Browser {
override browser(): Browser {
if (!this.#browserContext) {
throw new Error('browserContext is not initialised');
}
return this.#browserContext.browser();
}
/**
* Get the browser context the target belongs to.
*/
browserContext(): BrowserContext {
override browserContext(): BrowserContext {
if (!this.#browserContext) {
throw new Error('browserContext is not initialised');
}
return this.#browserContext;
}
/**
* Get the target that opened this target. Top-level targets return `null`.
*/
opener(): Target | undefined {
override opener(): Target | undefined {
const {openerId} = this.#targetInfo;
if (!openerId) {
return;
@ -229,20 +198,12 @@ export class Target {
this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
}
}
/**
* If the target is not of type `"page"`, `"webview"` or `"background_page"`,
* returns `null`.
*/
async page(): Promise<Page | null> {
return null;
}
}
/**
* @internal
*/
export class PageTarget extends Target {
export class PageTarget extends CDPTarget {
#defaultViewport?: Viewport;
protected pagePromise?: Promise<Page>;
#screenshotTaskQueue: TaskQueue;
@ -326,7 +287,7 @@ export class PageTarget extends Target {
/**
* @internal
*/
export class WorkerTarget extends Target {
export class WorkerTarget extends CDPTarget {
#workerPromise?: Promise<WebWorker>;
override async worker(): Promise<WebWorker | null> {
@ -353,4 +314,4 @@ export class WorkerTarget extends Target {
/**
* @internal
*/
export class OtherTarget extends Target {}
export class OtherTarget extends CDPTarget {}

View File

@ -18,7 +18,7 @@ import {Protocol} from 'devtools-protocol';
import {CDPSession} from './Connection.js';
import {EventEmitter} from './EventEmitter.js';
import {Target} from './Target.js';
import {CDPTarget} from './Target.js';
/**
* @internal
@ -26,14 +26,14 @@ import {Target} from './Target.js';
export type TargetFactory = (
targetInfo: Protocol.Target.TargetInfo,
session?: CDPSession
) => Target;
) => CDPTarget;
/**
* @internal
*/
export type TargetInterceptor = (
createdTarget: Target,
parentTarget: Target | null
createdTarget: CDPTarget,
parentTarget: CDPTarget | null
) => void;
/**
@ -48,7 +48,7 @@ export type TargetInterceptor = (
* @internal
*/
export interface TargetManager extends EventEmitter {
getAvailableTargets(): Map<string, Target>;
getAvailableTargets(): Map<string, CDPTarget>;
initialize(): Promise<void>;
dispose(): void;
addTargetInterceptor(

View File

@ -16,6 +16,7 @@
import expect from 'expect';
import {BrowserContext} from 'puppeteer-core/internal/api/BrowserContext.js';
import {CDPTarget} from 'puppeteer-core/internal/common/Target.js';
import {describeWithDebugLogs, getTestState, launch} from './mocha-utils.js';
import {attachFrame, detachFrame, navigateFrame} from './utils.js';
@ -447,6 +448,6 @@ describeWithDebugLogs('OOPIF', function () {
function oopifs(context: BrowserContext) {
return context.targets().filter(target => {
return target._getTargetInfo().type === 'iframe';
return (target as CDPTarget)._getTargetInfo().type === 'iframe';
});
}

View File

@ -17,9 +17,8 @@
import {ServerResponse} from 'http';
import expect from 'expect';
import {TimeoutError} from 'puppeteer';
import {TimeoutError, Target} from 'puppeteer';
import {Page} from 'puppeteer-core/internal/api/Page.js';
import {Target} from 'puppeteer-core/internal/common/Target.js';
import {getTestState, setupTestBrowserHooks} from './mocha-utils.js';
import {waitEvent} from './utils.js';