chore: remove src/externs.d.ts (#5811)

* chore: remove src/externs.d.ts

It defined global types that we don't want to use, and instead we move
to using interfaces that we import and reference just like with any
other interface.

This means other than Protocol (which I think is fine to leave as is),
there are no other magic global types and you have to import any types
or interfaces that you want.
This commit is contained in:
Jack Franklin 2020-05-06 14:23:07 +01:00 committed by GitHub
parent de4f08dc52
commit ae7483d5cf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 106 additions and 52 deletions

View File

@ -26,7 +26,7 @@
"eslint": "([ \"$CI\" = true ] && eslint --ext js --ext ts --quiet -f codeframe . || eslint --ext js --ext ts .)", "eslint": "([ \"$CI\" = true ] && eslint --ext js --ext ts --quiet -f codeframe . || eslint --ext js --ext ts .)",
"lint": "npm run eslint && npm run tsc && npm run doc", "lint": "npm run eslint && npm run tsc && npm run doc",
"doc": "node utils/doclint/cli.js", "doc": "node utils/doclint/cli.js",
"tsc": "tsc --version && tsc -p . && cp src/protocol.d.ts lib/ && cp src/externs.d.ts lib/", "tsc": "tsc --version && tsc -p . && cp src/protocol.d.ts lib/",
"apply-next-version": "node utils/apply_next_version.js", "apply-next-version": "node utils/apply_next_version.js",
"test-types": "node utils/doclint/generate_types && tsc --version && tsc -p utils/doclint/generate_types/test/", "test-types": "node utils/doclint/generate_types && tsc --version && tsc -p utils/doclint/generate_types/test/",
"update-protocol-d-ts": "node utils/protocol-types-generator update", "update-protocol-d-ts": "node utils/protocol-types-generator update",

View File

@ -22,17 +22,18 @@ import {Events} from './Events';
import {Connection} from './Connection'; import {Connection} from './Connection';
import {Page} from './Page'; import {Page} from './Page';
import {ChildProcess} from 'child_process'; import {ChildProcess} from 'child_process';
import type {Viewport} from './PuppeteerViewport';
type BrowserCloseCallback = () => Promise<void> | void; type BrowserCloseCallback = () => Promise<void> | void;
export class Browser extends EventEmitter { export class Browser extends EventEmitter {
static async create(connection: Connection, contextIds: string[], ignoreHTTPSErrors: boolean, defaultViewport?: Puppeteer.Viewport, process?: ChildProcess, closeCallback?: BrowserCloseCallback): Promise<Browser> { static async create(connection: Connection, contextIds: string[], ignoreHTTPSErrors: boolean, defaultViewport?: Viewport, process?: ChildProcess, closeCallback?: BrowserCloseCallback): Promise<Browser> {
const browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback); const browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback);
await connection.send('Target.setDiscoverTargets', {discover: true}); await connection.send('Target.setDiscoverTargets', {discover: true});
return browser; return browser;
} }
_ignoreHTTPSErrors: boolean; _ignoreHTTPSErrors: boolean;
_defaultViewport?: Puppeteer.Viewport; _defaultViewport?: Viewport;
_process?: ChildProcess; _process?: ChildProcess;
_screenshotTaskQueue = new TaskQueue(); _screenshotTaskQueue = new TaskQueue();
_connection: Connection; _connection: Connection;
@ -42,7 +43,7 @@ export class Browser extends EventEmitter {
// TODO: once Target is in TypeScript we can type this properly. // TODO: once Target is in TypeScript we can type this properly.
_targets: Map<string, Target>; _targets: Map<string, Target>;
constructor(connection: Connection, contextIds: string[], ignoreHTTPSErrors: boolean, defaultViewport?: Puppeteer.Viewport, process?: ChildProcess, closeCallback?: BrowserCloseCallback) { constructor(connection: Connection, contextIds: string[], ignoreHTTPSErrors: boolean, defaultViewport?: Viewport, process?: ChildProcess, closeCallback?: BrowserCloseCallback) {
super(); super();
this._ignoreHTTPSErrors = ignoreHTTPSErrors; this._ignoreHTTPSErrors = ignoreHTTPSErrors;
this._defaultViewport = defaultViewport; this._defaultViewport = defaultViewport;

View File

@ -14,14 +14,12 @@
* limitations under the License. * limitations under the License.
*/ */
import {assert} from './helper'; import {assert} from './helper';
import {Events} from './Events';
import EventsModule = require('./Events'); import * as debug from 'debug';
const {Events} = EventsModule;
import debug = require('debug');
const debugProtocol = debug('puppeteer:protocol'); const debugProtocol = debug('puppeteer:protocol');
import EventEmitter = require('events'); import type {ConnectionTransport} from './ConnectionTransport';
import * as EventEmitter from 'events';
interface ConnectionCallback { interface ConnectionCallback {
resolve: Function; resolve: Function;
@ -33,7 +31,7 @@ interface ConnectionCallback {
export class Connection extends EventEmitter { export class Connection extends EventEmitter {
_url: string; _url: string;
_transport: Puppeteer.ConnectionTransport; _transport: ConnectionTransport;
_delay: number; _delay: number;
_lastId = 0; _lastId = 0;
_sessions: Map<string, CDPSession> = new Map(); _sessions: Map<string, CDPSession> = new Map();
@ -41,12 +39,7 @@ export class Connection extends EventEmitter {
_callbacks: Map<number, ConnectionCallback> = new Map(); _callbacks: Map<number, ConnectionCallback> = new Map();
/** constructor(url: string, transport: ConnectionTransport, delay = 0) {
* @param {string} url
* @param {!Puppeteer.ConnectionTransport} transport
* @param {number=} delay
*/
constructor(url: string, transport: Puppeteer.ConnectionTransport, delay = 0) {
super(); super();
this._url = url; this._url = url;
this._delay = delay; this._delay = delay;

View File

@ -0,0 +1,22 @@
/**
* Copyright 2020 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.
*/
export interface ConnectionTransport {
send(string);
close();
onmessage?: (message: string) => void;
onclose?: () => void;
}

View File

@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
import {CDPSession} from './Connection'; import {CDPSession} from './Connection';
import type {Viewport} from './PuppeteerViewport';
export class EmulationManager { export class EmulationManager {
_client: CDPSession; _client: CDPSession;
@ -24,7 +25,7 @@ export class EmulationManager {
this._client = client; this._client = client;
} }
async emulateViewport(viewport: Puppeteer.Viewport): Promise<boolean> { async emulateViewport(viewport: Viewport): Promise<boolean> {
const mobile = viewport.isMobile || false; const mobile = viewport.isMobile || false;
const width = viewport.width; const width = viewport.width;
const height = viewport.height; const height = viewport.height;

View File

@ -30,8 +30,10 @@ import {Connection} from './Connection';
import {Browser} from './Browser'; import {Browser} from './Browser';
import {helper, assert, debugError} from './helper'; import {helper, assert, debugError} from './helper';
import {TimeoutError} from './Errors'; import {TimeoutError} from './Errors';
import type {ConnectionTransport} from './ConnectionTransport';
import {WebSocketTransport} from './WebSocketTransport'; import {WebSocketTransport} from './WebSocketTransport';
import {PipeTransport} from './PipeTransport'; import {PipeTransport} from './PipeTransport';
import type {Viewport} from './PuppeteerViewport';
const mkdtempAsync = helper.promisify(fs.mkdtemp); const mkdtempAsync = helper.promisify(fs.mkdtemp);
const removeFolderAsync = helper.promisify(removeFolder); const removeFolderAsync = helper.promisify(removeFolder);
@ -67,7 +69,7 @@ export interface LaunchOptions {
export interface BrowserOptions { export interface BrowserOptions {
ignoreHTTPSErrors?: boolean; ignoreHTTPSErrors?: boolean;
defaultViewport?: Puppeteer.Viewport; defaultViewport?: Viewport;
slowMo?: number; slowMo?: number;
} }
@ -344,7 +346,7 @@ class ChromeLauncher implements ProductLauncher {
async connect(options: BrowserOptions & { async connect(options: BrowserOptions & {
browserWSEndpoint?: string; browserWSEndpoint?: string;
browserURL?: string; browserURL?: string;
transport?: Puppeteer.ConnectionTransport; transport?: ConnectionTransport;
}): Promise<Browser> { }): Promise<Browser> {
const { const {
browserWSEndpoint, browserWSEndpoint,
@ -451,7 +453,7 @@ class FirefoxLauncher implements ProductLauncher {
async connect(options: BrowserOptions & { async connect(options: BrowserOptions & {
browserWSEndpoint?: string; browserWSEndpoint?: string;
browserURL?: string; browserURL?: string;
transport?: Puppeteer.ConnectionTransport; transport?: ConnectionTransport;
}): Promise<Browser> { }): Promise<Browser> {
const { const {
browserWSEndpoint, browserWSEndpoint,

View File

@ -30,6 +30,7 @@ import {Worker as PuppeteerWorker} from './Worker';
import {Browser, BrowserContext} from './Browser'; import {Browser, BrowserContext} from './Browser';
import {Target} from './Target'; import {Target} from './Target';
import {createJSHandle, JSHandle, ElementHandle} from './JSHandle'; import {createJSHandle, JSHandle, ElementHandle} from './JSHandle';
import type {Viewport} from './PuppeteerViewport';
import {Request as PuppeteerRequest, Response as PuppeteerResponse, Credentials} from './NetworkManager'; import {Request as PuppeteerRequest, Response as PuppeteerResponse, Credentials} from './NetworkManager';
import {Accessibility} from './Accessibility'; import {Accessibility} from './Accessibility';
import {TimeoutSettings} from './TimeoutSettings'; import {TimeoutSettings} from './TimeoutSettings';
@ -124,7 +125,7 @@ const paperFormats: Record<string, PaperFormat> = {
} as const; } as const;
export class Page extends EventEmitter { export class Page extends EventEmitter {
static async create(client: CDPSession, target: Target, ignoreHTTPSErrors: boolean, defaultViewport: Puppeteer.Viewport | null, screenshotTaskQueue: TaskQueue): Promise<Page> { static async create(client: CDPSession, target: Target, ignoreHTTPSErrors: boolean, defaultViewport: Viewport | null, screenshotTaskQueue: TaskQueue): Promise<Page> {
const page = new Page(client, target, ignoreHTTPSErrors, screenshotTaskQueue); const page = new Page(client, target, ignoreHTTPSErrors, screenshotTaskQueue);
await page._initialize(); await page._initialize();
if (defaultViewport) if (defaultViewport)
@ -146,7 +147,7 @@ export class Page extends EventEmitter {
_pageBindings = new Map<string, Function>(); _pageBindings = new Map<string, Function>();
_coverage: Coverage; _coverage: Coverage;
_javascriptEnabled = true; _javascriptEnabled = true;
_viewport: Puppeteer.Viewport | null; _viewport: Viewport | null;
_screenshotTaskQueue: TaskQueue; _screenshotTaskQueue: TaskQueue;
_workers = new Map<string, PuppeteerWorker>(); _workers = new Map<string, PuppeteerWorker>();
// TODO: improve this typedef - it's a function that takes a file chooser or something? // TODO: improve this typedef - it's a function that takes a file chooser or something?
@ -666,7 +667,7 @@ export class Page extends EventEmitter {
await this._client.send('Page.bringToFront'); await this._client.send('Page.bringToFront');
} }
async emulate(options: {viewport: Puppeteer.Viewport; userAgent: string}): Promise<void> { async emulate(options: {viewport: Viewport; userAgent: string}): Promise<void> {
await Promise.all([ await Promise.all([
this.setViewport(options.viewport), this.setViewport(options.viewport),
this.setUserAgent(options.userAgent) this.setUserAgent(options.userAgent)
@ -712,14 +713,14 @@ export class Page extends EventEmitter {
} }
} }
async setViewport(viewport: Puppeteer.Viewport): Promise<void> { async setViewport(viewport: Viewport): Promise<void> {
const needsReload = await this._emulationManager.emulateViewport(viewport); const needsReload = await this._emulationManager.emulateViewport(viewport);
this._viewport = viewport; this._viewport = viewport;
if (needsReload) if (needsReload)
await this.reload(); await this.reload();
} }
viewport(): Puppeteer.Viewport | null { viewport(): Viewport | null {
return this._viewport; return this._viewport;
} }

View File

@ -14,8 +14,9 @@
* limitations under the License. * limitations under the License.
*/ */
import {helper, debugError, PuppeteerEventListener} from './helper'; import {helper, debugError, PuppeteerEventListener} from './helper';
import type {ConnectionTransport} from './ConnectionTransport';
export class PipeTransport implements Puppeteer.ConnectionTransport { export class PipeTransport implements ConnectionTransport {
_pipeWrite: NodeJS.WritableStream; _pipeWrite: NodeJS.WritableStream;
_pendingMessage: string; _pendingMessage: string;
_eventListeners: PuppeteerEventListener[]; _eventListeners: PuppeteerEventListener[];

View File

@ -17,6 +17,7 @@ import Launcher from './Launcher';
import type {LaunchOptions, ChromeArgOptions, BrowserOptions, ProductLauncher} from './Launcher'; import type {LaunchOptions, ChromeArgOptions, BrowserOptions, ProductLauncher} from './Launcher';
import {BrowserFetcher, BrowserFetcherOptions} from './BrowserFetcher'; import {BrowserFetcher, BrowserFetcherOptions} from './BrowserFetcher';
import {puppeteerErrors, PuppeteerErrors} from './Errors'; import {puppeteerErrors, PuppeteerErrors} from './Errors';
import type {ConnectionTransport} from './ConnectionTransport';
import {devicesMap} from './DeviceDescriptors'; import {devicesMap} from './DeviceDescriptors';
import type {DevicesMap} from './/DeviceDescriptors'; import type {DevicesMap} from './/DeviceDescriptors';
@ -48,7 +49,7 @@ export class Puppeteer {
connect(options: BrowserOptions & { connect(options: BrowserOptions & {
browserWSEndpoint?: string; browserWSEndpoint?: string;
browserURL?: string; browserURL?: string;
transport?: Puppeteer.ConnectionTransport; transport?: ConnectionTransport;
product?: string; product?: string;
}): Promise<Browser> { }): Promise<Browser> {
if (options.product) if (options.product)

23
src/PuppeteerViewport.ts Normal file
View File

@ -0,0 +1,23 @@
/**
* Copyright 2020 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.
*/
export interface Viewport {
width: number;
height: number;
deviceScaleFactor?: number;
isMobile?: boolean;
isLandscape?: boolean;
hasTouch?: boolean;
}

View File

@ -20,6 +20,7 @@ import {Worker as PuppeteerWorker} from './Worker';
import {CDPSession} from './Connection'; import {CDPSession} from './Connection';
import {TaskQueue} from './TaskQueue'; import {TaskQueue} from './TaskQueue';
import {Browser, BrowserContext} from './Browser'; import {Browser, BrowserContext} from './Browser';
import type {Viewport} from './PuppeteerViewport';
export class Target { export class Target {
_targetInfo: Protocol.Target.TargetInfo; _targetInfo: Protocol.Target.TargetInfo;
@ -27,7 +28,7 @@ export class Target {
_targetId: string; _targetId: string;
_sessionFactory: () => Promise<CDPSession>; _sessionFactory: () => Promise<CDPSession>;
_ignoreHTTPSErrors: boolean; _ignoreHTTPSErrors: boolean;
_defaultViewport?: Puppeteer.Viewport; _defaultViewport?: Viewport;
_screenshotTaskQueue: TaskQueue; _screenshotTaskQueue: TaskQueue;
_pagePromise?: Promise<Page>; _pagePromise?: Promise<Page>;
_workerPromise?: Promise<PuppeteerWorker>; _workerPromise?: Promise<PuppeteerWorker>;
@ -37,7 +38,7 @@ export class Target {
_closedCallback: () => void; _closedCallback: () => void;
_isInitialized: boolean; _isInitialized: boolean;
constructor(targetInfo: Protocol.Target.TargetInfo, browserContext: BrowserContext, sessionFactory: () => Promise<CDPSession>, ignoreHTTPSErrors: boolean, defaultViewport: Puppeteer.Viewport | null, screenshotTaskQueue: TaskQueue) { constructor(targetInfo: Protocol.Target.TargetInfo, browserContext: BrowserContext, sessionFactory: () => Promise<CDPSession>, ignoreHTTPSErrors: boolean, defaultViewport: Viewport | null, screenshotTaskQueue: TaskQueue) {
this._targetInfo = targetInfo; this._targetInfo = targetInfo;
this._browserContext = browserContext; this._browserContext = browserContext;
this._targetId = targetInfo.targetId; this._targetId = targetInfo.targetId;

View File

@ -14,8 +14,9 @@
* limitations under the License. * limitations under the License.
*/ */
import * as NodeWebSocket from 'ws'; import * as NodeWebSocket from 'ws';
import type {ConnectionTransport} from './ConnectionTransport';
export class WebSocketTransport implements Puppeteer.ConnectionTransport { export class WebSocketTransport implements ConnectionTransport {
static create(url: string): Promise<WebSocketTransport> { static create(url: string): Promise<WebSocketTransport> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const ws = new NodeWebSocket(url, [], { const ws = new NodeWebSocket(url, [], {

21
src/externs.d.ts vendored
View File

@ -1,21 +0,0 @@
import * as child_process from 'child_process';
declare global {
module Puppeteer {
export interface ConnectionTransport {
send(string);
close();
onmessage?: (message: string) => void,
onclose?: () => void,
}
export type Viewport = {
width: number;
height: number;
deviceScaleFactor?: number;
isMobile?: boolean;
isLandscape?: boolean;
hasTouch?: boolean;
}
}
}

View File

@ -367,6 +367,34 @@ function compareDocumentations(actual, expected) {
actualName: 'Array<Object>', actualName: 'Array<Object>',
expectedName: 'Array<MediaFeature>' expectedName: 'Array<MediaFeature>'
}], }],
['Method Page.emulate() options.viewport', {
actualName: 'Object',
expectedName: 'Viewport'
}],
['Method Page.setViewport() options.viewport', {
actualName: 'Object',
expectedName: 'Viewport'
}],
['Method Page.setViewport() viewport', {
actualName: 'Object',
expectedName: 'Viewport'
}],
['Method Page.connect() options.defaultViewport', {
actualName: 'Object',
expectedName: 'Viewport'
}],
['Method Puppeteer.connect() options.defaultViewport', {
actualName: 'Object',
expectedName: 'Viewport'
}],
['Method Puppeteer.launch() options.defaultViewport', {
actualName: 'Object',
expectedName: 'Viewport'
}],
['Method Page.launch() options.defaultViewport', {
actualName: 'Object',
expectedName: 'Viewport'
}],
['Method Page.goBack() options', { ['Method Page.goBack() options', {
actualName: 'Object', actualName: 'Object',
expectedName: 'WaitForOptions' expectedName: 'WaitForOptions'