fix: explicit HTTPRequest.resourceType type defs (#6882)

We can use the new `Lowercase` util in TS4 to avoid duplicating the type
and instead lowercase it.

Note we still need to do the work so callbacks are typed correctly:

```ts
page.on('request', request => {

})
```

Right now `request` is `any`, whereas it should be a
`puppeteer.HTTPRequest`. You can manually set the type for now, and I
will work on adding types for events so that this is done automatically
by the compiler in a future release.

Fixes #6854.
This commit is contained in:
Jack Franklin 2021-02-17 09:14:38 +00:00 committed by GitHub
parent 8adf5b467d
commit ff26c62647
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -45,6 +45,13 @@ export interface ResponseForRequest {
body: string | Buffer; body: string | Buffer;
} }
/**
* Resource types for HTTPRequests as perceived by the rendering engine.
*
* @public
*/
export type ResourceType = Lowercase<Protocol.Network.ResourceType>;
/** /**
* *
* Represents an HTTP request sent by a page. * Represents an HTTP request sent by a page.
@ -108,7 +115,7 @@ export class HTTPRequest {
private _allowInterception: boolean; private _allowInterception: boolean;
private _interceptionHandled = false; private _interceptionHandled = false;
private _url: string; private _url: string;
private _resourceType: string; private _resourceType: ResourceType;
private _method: string; private _method: string;
private _postData?: string; private _postData?: string;
@ -133,7 +140,7 @@ export class HTTPRequest {
this._interceptionId = interceptionId; this._interceptionId = interceptionId;
this._allowInterception = allowInterception; this._allowInterception = allowInterception;
this._url = event.request.url; this._url = event.request.url;
this._resourceType = event.type.toLowerCase(); this._resourceType = event.type.toLowerCase() as ResourceType;
this._method = event.request.method; this._method = event.request.method;
this._postData = event.request.postData; this._postData = event.request.postData;
this._frame = frame; this._frame = frame;
@ -153,17 +160,8 @@ export class HTTPRequest {
/** /**
* Contains the request's resource type as it was perceived by the rendering * Contains the request's resource type as it was perceived by the rendering
* engine. * engine.
* @remarks
* @returns one of the following: `document`, `stylesheet`, `image`, `media`,
* `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`, `websocket`,
* `manifest`, `other`.
*/ */
resourceType(): string { resourceType(): ResourceType {
// TODO (@jackfranklin): protocol.d.ts has a type for this, but all the
// string values are uppercase. The Puppeteer docs explicitly say the
// potential values are all lower case, and the constructor takes the event
// type and calls toLowerCase() on it, so we can't reuse the type from the
// protocol.d.ts. Why do we lower case?
return this._resourceType; return this._resourceType;
} }