Skip to content

Commit

Permalink
fix: much better TypeScript definitions (#6837)
Browse files Browse the repository at this point in the history
This PR aims to vastly improve our TS types and how we ship them.

Our previous attempt at shipping TypeScript was unfortunately flawed for
many reasons when compared to the @types/puppeteer package:

* It only worked if you needed the default export. If you wanted to
  import a type that Puppeteer uses, you'd have to do `import type X
  from 'puppeteer/lib/...'`. This is not something we want to encourage
  because that means our internal file structure becomes almost public
  API.
* It gave absolutely no help to CommonJS users in JS files because it
  would warn people they needed to do `const pptr =
  require('puppeteer').default, which is not correct.
* I found a bug in the `evaluate` types which mean't you couldn't
  override the types to provide more info, and TS would insist the types
  were all `unknown`.

The goal of this PR is to support:

1. In a `ts` file, `import puppeteer from 'puppeteer'`
1. In a `ts` file, `import type {ElementHandle} from 'puppeteer'`
1. In a `ts` file, referencing a type as `puppeteer.ElementHandle`
1. In a `ts` file, you can get good type inference when running
   `foo.evaluate(x => x.clientHeight)`.
1. In a `js` file using CJS, you can do `const puppeteer =
   require('puppeteer')` and get good type help from VSCode.

To test this I created a new empty repository with two test files in,
one `.ts` file with this in:
https://gist.github.com/jackfranklin/22ba2f390f97c7312cd70025a2096fc8,
and a `js` file with this in:
https://gist.github.com/jackfranklin/06bed136fdb22419cb7a8a9a4d4ef32f.

These files included enough code to check that the types were behaving
as I expected.

The fix for our types was to make use of API Extractor, which we already
use for our docs, to "rollup" all the disparate type files that TS
generates into one large `types.d.ts` which contains all the various
types that we define, such as:

```ts
export declare class ElementHandle {...}

export type EvaluateFn ...
```

If we then update our `package.json` `types` field to point to that file
in `lib/types.d.ts`, this then allows a developer to write:

```
import type {ElementHandle} from 'puppeteer'
```

And get the correct type definitions. However, what the `types.d.ts`
file doesn't do out of the box is declare the default export, so
importing Puppeteer's default export to call a method such as `launch`
on it will get you an error.

That's where the `script/add-default-export-to-types.ts` comes in. It
appends the following to the auto-generated `types.d.ts` file:

```ts
declare const puppeteer: PuppeteerNode;
export = puppeteer;
```

This tells TypeScript what the default export is, and by using the
`export =` syntax, we make sure TS understands both in a TS ESM
environment and in a JS CJS environment.

Now the `build` step, which is run by GitHub Actions when we release,
will generate the `.d.ts` file and then extend it with the default
export code.

To ensure that I was generating a valid package, I created a new
repository locally with the two code samples linked in Gists above. I
then ran:

```
npm init -y
npm install --save-dev typescript
npx tsc --init
```

Which gives me a base to test from. In Puppeteer, I ran `npm pack`,
which packs the module into a tar that's almost identical to what would
be published, so I can be confident that the .d.ts files in there are
what would be published.

I then installed it:

```
npm install --save-dev ../../puppeteer/puppeteer-7.0.1-post.tgz
```

And then reloaded VSCode in my dummy project. By deliberately making
typos and hovering over the code, I could confirm that all the goals
listed above were met, and this seems like a vast improvement on our
types.
  • Loading branch information
jackfranklin committed Feb 9, 2021
1 parent 4e8d074 commit f1b46ab
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 72 deletions.
122 changes: 66 additions & 56 deletions README.md
@@ -1,7 +1,9 @@
# Puppeteer

<!-- [START badges] -->

[![Build status](https://github.com/puppeteer/puppeteer/workflows/run-checks/badge.svg)](https://github.com/puppeteer/puppeteer/actions?query=workflow%3Arun-checks) [![npm puppeteer package](https://img.shields.io/npm/v/puppeteer.svg)](https://npmjs.org/package/puppeteer)

<!-- [END badges] -->

<img src="https://user-images.githubusercontent.com/10379601/29446482-04f7036a-841f-11e7-9872-91d1fc2ea683.png" height="200" align="right">
Expand All @@ -11,21 +13,23 @@
> Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). Puppeteer runs [headless](https://developers.google.com/web/updates/2017/04/headless-chrome) by default, but can be configured to run full (non-headless) Chrome or Chromium.
<!-- [START usecases] -->

###### What can I do?

Most things that you can do manually in the browser can be done using Puppeteer! Here are a few examples to get you started:

* Generate screenshots and PDFs of pages.
* Crawl a SPA (Single-Page Application) and generate pre-rendered content (i.e. "SSR" (Server-Side Rendering)).
* Automate form submission, UI testing, keyboard input, etc.
* Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.
* Capture a [timeline trace](https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference) of your site to help diagnose performance issues.
* Test Chrome Extensions.
- Generate screenshots and PDFs of pages.
- Crawl a SPA (Single-Page Application) and generate pre-rendered content (i.e. "SSR" (Server-Side Rendering)).
- Automate form submission, UI testing, keyboard input, etc.
- Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.
- Capture a [timeline trace](https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference) of your site to help diagnose performance issues.
- Test Chrome Extensions.
<!-- [END usecases] -->

Give it a spin: https://try-puppeteer.appspot.com/

<!-- [START getstarted] -->

## Getting Started

### Installation
Expand All @@ -39,7 +43,6 @@ npm i puppeteer

Note: When you install Puppeteer, it downloads a recent version of Chromium (~170MB Mac, ~282MB Linux, ~280MB Win) that is guaranteed to work with the API. To skip the download, or to download a different browser, see [Environment variables](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#environment-variables).


### puppeteer-core

Since version 1.7.0 we publish the [`puppeteer-core`](https://www.npmjs.com/package/puppeteer-core) package,
Expand All @@ -65,7 +68,7 @@ Node 8.9.0+. Starting from v3.0.0 Puppeteer starts to rely on Node 10.18.1+. All
Puppeteer will be familiar to people using other browser testing frameworks. You create an instance
of `Browser`, open pages, and then manipulate them with [Puppeteer's API](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#).

**Example** - navigating to https://example.com and saving a screenshot as *example.png*:
**Example** - navigating to https://example.com and saving a screenshot as _example.png_:

Save file as **example.js**

Expand All @@ -76,7 +79,7 @@ const puppeteer = require('puppeteer');
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'example.png'});
await page.screenshot({ path: 'example.png' });

await browser.close();
})();
Expand All @@ -88,7 +91,7 @@ Execute script on the command line
node example.js
```

Puppeteer sets an initial page size to 800×600px, which defines the screenshot size. The page size can be customized with [`Page.setViewport()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#pagesetviewportviewport).
Puppeteer sets an initial page size to 800×600px, which defines the screenshot size. The page size can be customized with [`Page.setViewport()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#pagesetviewportviewport).

**Example** - create a PDF.

Expand All @@ -100,8 +103,10 @@ const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});
await page.pdf({path: 'hn.pdf', format: 'A4'});
await page.goto('https://news.ycombinator.com', {
waitUntil: 'networkidle2',
});
await page.pdf({ path: 'hn.pdf', format: 'A4' });

await browser.close();
})();
Expand Down Expand Up @@ -132,7 +137,7 @@ const puppeteer = require('puppeteer');
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio
deviceScaleFactor: window.devicePixelRatio,
};
});

Expand All @@ -153,14 +158,15 @@ See [`Page.evaluate()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/
<!-- [END getstarted] -->

<!-- [START runtimesettings] -->

## Default runtime settings

**1. Uses Headless mode**

Puppeteer launches Chromium in [headless mode](https://developers.google.com/web/updates/2017/04/headless-chrome). To launch a full version of Chromium, set the [`headless` option](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions) when launching a browser:

```js
const browser = await puppeteer.launch({headless: false}); // default is true
const browser = await puppeteer.launch({ headless: false }); // default is true
```

**2. Runs a bundled version of Chromium**
Expand All @@ -170,7 +176,7 @@ is guaranteed to work out of the box. To use Puppeteer with a different version
pass in the executable's path when creating a `Browser` instance:

```js
const browser = await puppeteer.launch({executablePath: '/path/to/Chrome'});
const browser = await puppeteer.launch({ executablePath: '/path/to/Chrome' });
```

You can also use Puppeteer with Firefox Nightly (experimental support). See [`Puppeteer.launch()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions) for more information.
Expand All @@ -189,39 +195,38 @@ Puppeteer creates its own browser user profile which it **cleans up on every run
- [Examples](https://github.com/puppeteer/puppeteer/tree/main/examples/)
- [Community list of Puppeteer resources](https://github.com/transitive-bullshit/awesome-puppeteer)


<!-- [START debugging] -->

## Debugging tips

1. Turn off headless mode - sometimes it's useful to see what the browser is
displaying. Instead of launching in headless mode, launch a full version of
the browser using `headless: false`:
1. Turn off headless mode - sometimes it's useful to see what the browser is
displaying. Instead of launching in headless mode, launch a full version of
the browser using `headless: false`:

```js
const browser = await puppeteer.launch({headless: false});
const browser = await puppeteer.launch({ headless: false });
```

2. Slow it down - the `slowMo` option slows down Puppeteer operations by the
specified amount of milliseconds. It's another way to help see what's going on.
2. Slow it down - the `slowMo` option slows down Puppeteer operations by the
specified amount of milliseconds. It's another way to help see what's going on.

```js
const browser = await puppeteer.launch({
headless: false,
slowMo: 250 // slow down by 250ms
slowMo: 250, // slow down by 250ms
});
```

3. Capture console output - You can listen for the `console` event.
This is also handy when debugging code in `page.evaluate()`:
3. Capture console output - You can listen for the `console` event.
This is also handy when debugging code in `page.evaluate()`:

```js
page.on('console', msg => console.log('PAGE LOG:', msg.text()));
page.on('console', (msg) => console.log('PAGE LOG:', msg.text()));

await page.evaluate(() => console.log(`url is ${location.href}`));
```

4. Use debugger in application code browser
4. Use debugger in application code browser

There are two execution context: node.js that is running test code, and the browser
running application code being tested. This lets you debug code in the
Expand All @@ -230,26 +235,28 @@ Puppeteer creates its own browser user profile which it **cleans up on every run
- Use `{devtools: true}` when launching Puppeteer:

```js
const browser = await puppeteer.launch({devtools: true});
const browser = await puppeteer.launch({ devtools: true });
```

- Change default test timeout:

jest: `jest.setTimeout(100000);`
jest: `jest.setTimeout(100000);`

jasmine: `jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;`
jasmine: `jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;`

mocha: `this.timeout(100000);` (don't forget to change test to use [function and not '=>'](https://stackoverflow.com/a/23492442))
mocha: `this.timeout(100000);` (don't forget to change test to use [function and not '=>'](https://stackoverflow.com/a/23492442))

- Add an evaluate statement with `debugger` inside / add `debugger` to an existing evaluate statement:
- Add an evaluate statement with `debugger` inside / add `debugger` to an existing evaluate statement:

```js
await page.evaluate(() => {debugger;});
await page.evaluate(() => {
debugger;
});
```

The test will now stop executing in the above evaluate statement, and chromium will stop in debug mode.
The test will now stop executing in the above evaluate statement, and chromium will stop in debug mode.

5. Use debugger in node.js
5. Use debugger in node.js

This will let you debug test code. For example, you can step over `await page.click()` in the node.js script and see the click happen in the application code browser.

Expand All @@ -270,37 +277,36 @@ Puppeteer creates its own browser user profile which it **cleans up on every run
- In the newly opened test browser, type `F8` to resume test execution
- Now your `debugger` will be hit and you can debug in the test browser

6. Enable verbose logging - internal DevTools protocol traffic
will be logged via the [`debug`](https://github.com/visionmedia/debug) module under the `puppeteer` namespace.

6. Enable verbose logging - internal DevTools protocol traffic
will be logged via the [`debug`](https://github.com/visionmedia/debug) module under the `puppeteer` namespace.

# Basic verbose logging
env DEBUG="puppeteer:*" node script.js
# Basic verbose logging
env DEBUG="puppeteer:*" node script.js

# Protocol traffic can be rather noisy. This example filters out all Network domain messages
env DEBUG="puppeteer:*" env DEBUG_COLORS=true node script.js 2>&1 | grep -v '"Network'
# Protocol traffic can be rather noisy. This example filters out all Network domain messages
env DEBUG="puppeteer:*" env DEBUG_COLORS=true node script.js 2>&1 | grep -v '"Network'

7. Debug your Puppeteer (node) code easily, using [ndb](https://github.com/GoogleChromeLabs/ndb)
7. Debug your Puppeteer (node) code easily, using [ndb](https://github.com/GoogleChromeLabs/ndb)

- `npm install -g ndb` (or even better, use [npx](https://github.com/zkat/npx)!)
- `npm install -g ndb` (or even better, use [npx](https://github.com/zkat/npx)!)

- add a `debugger` to your Puppeteer (node) code
- add a `debugger` to your Puppeteer (node) code

- add `ndb` (or `npx ndb`) before your test command. For example:
- add `ndb` (or `npx ndb`) before your test command. For example:

`ndb jest` or `ndb mocha` (or `npx ndb jest` / `npx ndb mocha`)
`ndb jest` or `ndb mocha` (or `npx ndb jest` / `npx ndb mocha`)

- debug your test inside chromium like a boss!
- debug your test inside chromium like a boss!

<!-- [END debugging] -->


<!-- [START typescript] -->

## Usage with TypeScript

We have recently completed a migration to move the Puppeteer source code from JavaScript to TypeScript and we're currently working on shipping type definitions for TypeScript with Puppeteer's npm package.
We have recently completed a migration to move the Puppeteer source code from JavaScript to TypeScript and as of version 7.0.1 we ship our own built-in type definitions.

Until this work is complete we recommend installing the Puppeteer type definitions from the [DefinitelyTyped](https://definitelytyped.org/) repository:
If you are on a version older than 7, we recommend installing the Puppeteer type definitions from the [DefinitelyTyped](https://definitelytyped.org/) repository:

```bash
npm install --save-dev @types/puppeteer
Expand All @@ -310,7 +316,6 @@ The types that you'll see appearing in the Puppeteer source code are based off t

<!-- [END typescript] -->


## Contributing to Puppeteer

Check out [contributing guide](https://github.com/puppeteer/puppeteer/blob/main/CONTRIBUTING.md) to get an overview of Puppeteer development.
Expand Down Expand Up @@ -344,6 +349,7 @@ The goals of the project are:
- Learn more about the pain points of automated browser testing and help fill those gaps.

We adapt [Chromium principles](https://www.chromium.org/developers/core-principles) to help us drive product decisions:

- **Speed**: Puppeteer has almost zero performance overhead over an automated page.
- **Security**: Puppeteer operates off-process with respect to Chromium, making it safe to automate potentially malicious pages.
- **Stability**: Puppeteer should not be flaky and should not leak memory.
Expand All @@ -352,6 +358,7 @@ We adapt [Chromium principles](https://www.chromium.org/developers/core-principl
#### Q: Is Puppeteer replacing Selenium/WebDriver?

**No**. Both projects are valuable for very different reasons:

- Selenium/WebDriver focuses on cross-browser automation; its value proposition is a single standard API that works across all major browsers.
- Puppeteer focuses on Chromium; its value proposition is richer functionality and higher reliability.

Expand All @@ -367,13 +374,15 @@ That said, you **can** use Puppeteer to run tests against Chromium, e.g. using t
We see Puppeteer as an **indivisible entity** with Chromium. Each version of Puppeteer bundles a specific version of Chromium – **the only** version it is guaranteed to work with.

This is not an artificial constraint: A lot of work on Puppeteer is actually taking place in the Chromium repository. Here’s a typical story:

- A Puppeteer bug is reported: https://github.com/puppeteer/puppeteer/issues/2709
- It turned out this is an issue with the DevTools protocol, so we’re fixing it in Chromium: https://chromium-review.googlesource.com/c/chromium/src/+/1102154
- Once the upstream fix is landed, we roll updated Chromium into Puppeteer: https://github.com/puppeteer/puppeteer/pull/2769

However, oftentimes it is desirable to use Puppeteer with the official Google Chrome rather than Chromium. For this to work, you should install a `puppeteer-core` version that corresponds to the Chrome version.

For example, in order to drive Chrome 71 with puppeteer-core, use `chrome-71` npm tag:

```bash
npm install puppeteer-core@chrome-71
```
Expand All @@ -382,7 +391,6 @@ npm install puppeteer-core@chrome-71

Look for the `chromium` entry in [revisions.ts](https://github.com/puppeteer/puppeteer/blob/main/src/revisions.ts). To find the corresponding Chromium commit and version number, search for the revision prefixed by an `r` in [OmahaProxy](https://omahaproxy.appspot.com/)'s "Find Releases" section.


#### Q: Which Firefox version does Puppeteer use?

Since Firefox support is experimental, Puppeteer downloads the latest [Firefox Nightly](https://wiki.mozilla.org/Nightly) when the `PUPPETEER_PRODUCT` environment variable is set to `firefox`. That's also why the value of `firefox` in [revisions.ts](https://github.com/puppeteer/puppeteer/blob/main/src/revisions.ts) is `latest` -- Puppeteer isn't tied to a particular Firefox version.
Expand All @@ -409,6 +417,7 @@ In browsers, input events could be divided into two big groups: trusted vs. untr
- **Untrusted event**: events generated by Web APIs, e.g. `document.createEvent` or `element.click()` methods.

Websites can distinguish between these two groups:

- using an [`Event.isTrusted`](https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted) event flag
- sniffing for accompanying events. For example, every trusted `'click'` event is preceded by `'mousedown'` and `'mouseup'` events.

Expand All @@ -424,10 +433,11 @@ await page.evaluate(() => {

You may find that Puppeteer does not behave as expected when controlling pages that incorporate audio and video. (For example, [video playback/screenshots is likely to fail](https://github.com/puppeteer/puppeteer/issues/291).) There are two reasons for this:

* Puppeteer is bundled with Chromium — not Chrome — and so by default, it inherits all of [Chromium's media-related limitations](https://www.chromium.org/audio-video). This means that Puppeteer does not support licensed formats such as AAC or H.264. (However, it is possible to force Puppeteer to use a separately-installed version Chrome instead of Chromium via the [`executablePath` option to `puppeteer.launch`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions). You should only use this configuration if you need an official release of Chrome that supports these media formats.)
* Since Puppeteer (in all configurations) controls a desktop version of Chromium/Chrome, features that are only supported by the mobile version of Chrome are not supported. This means that Puppeteer [does not support HTTP Live Streaming (HLS)](https://caniuse.com/#feat=http-live-streaming).
- Puppeteer is bundled with Chromium — not Chrome — and so by default, it inherits all of [Chromium's media-related limitations](https://www.chromium.org/audio-video). This means that Puppeteer does not support licensed formats such as AAC or H.264. (However, it is possible to force Puppeteer to use a separately-installed version Chrome instead of Chromium via the [`executablePath` option to `puppeteer.launch`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions). You should only use this configuration if you need an official release of Chrome that supports these media formats.)
- Since Puppeteer (in all configurations) controls a desktop version of Chromium/Chrome, features that are only supported by the mobile version of Chrome are not supported. This means that Puppeteer [does not support HTTP Live Streaming (HLS)](https://caniuse.com/#feat=http-live-streaming).

#### Q: I am having trouble installing / running Puppeteer in my test environment. Where should I look for help?

We have a [troubleshooting](https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md) guide for various operating systems that lists the required dependencies.

#### Q: How do I try/test a prerelease version of Puppeteer?
Expand All @@ -443,11 +453,11 @@ Please note that prerelease may be unstable and contain bugs.
#### Q: I have more questions! Where do I ask?

There are many ways to get help on Puppeteer:

- [bugtracker](https://github.com/puppeteer/puppeteer/issues)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/puppeteer)
- [slack channel](https://join.slack.com/t/puppeteer/shared_invite/enQtMzU4MjIyMDA5NTM4LWI0YTE0MjM0NWQzYmE2MTRmNjM1ZTBkN2MxNmJmNTIwNTJjMmFhOWFjMGExMDViYjk2YjU2ZmYzMmE1NmExYzc)

Make sure to search these channels before posting your question.


<!-- [END faq] -->

0 comments on commit f1b46ab

Please sign in to comment.