feat(jsdom): Update to v16.1 (#42200)

* feat(jsdom): Update to v16.1

* test(mozilla‑readability): Remove test dependency on JSDOM

* fix(jsdom): Fix lint errors

* feat(jsdom): Update dependency parse5 to v5
This commit is contained in:
ExE Boss
2020-02-14 09:28:24 -08:00
committed by GitHub
parent 10fe443e0c
commit 7675b526b5
24 changed files with 735 additions and 984 deletions
+1 -3
View File
@@ -2,6 +2,7 @@
"compilerOptions": {
"module": "commonjs",
"lib": [
"dom",
"es6"
],
"noImplicitAny": true,
@@ -12,9 +13,6 @@
"typeRoots": [
"../"
],
"paths": {
"parse5": [ "parse5/v4" ]
},
"esModuleInterop": true,
"types": [],
"noEmit": true,
+419 -289
View File
@@ -1,308 +1,438 @@
// Type definitions for jsdom 12.2
// Type definitions for jsdom 16.1
// Project: https://github.com/jsdom/jsdom
// Definitions by: Leonard Thieu <https://github.com/leonard-thieu>
// Johan Palmfjord <https://github.com/palmfjord>
// ExE Boss <https://github.com/ExE-Boss>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 3.0
/// <reference types="node" />
import { EventEmitter } from 'events';
import { MarkupData } from 'parse5';
import { ElementLocation } from 'parse5';
import { Context } from 'vm';
import * as tough from 'tough-cookie';
import { Script } from 'vm';
export class JSDOM {
static fromURL(url: string, options?: FromUrlOptions): Promise<JSDOM>;
// Needed to allow adding properties to `DOMWindow` that are only supported
// in newer TypeScript versions:
// tslint:disable-next-line: no-declare-current-package
declare module 'jsdom' {
const toughCookie: typeof tough;
class CookieJar extends tough.CookieJar {}
static fromFile(url: string, options?: FromFileOptions): Promise<JSDOM>;
class JSDOM {
constructor(html?: string | Buffer | BinaryData, options?: ConstructorOptions);
static fragment(html: string): DocumentFragment;
static fromURL(url: string, options?: BaseOptions): Promise<JSDOM>;
static fromFile(url: string, options?: FileOptions): Promise<JSDOM>;
static fragment(html: string): DocumentFragment;
constructor(html?: string | Buffer | BinaryData, options?: ConstructorOptions);
readonly window: DOMWindow;
readonly virtualConsole: VirtualConsole;
readonly cookieJar: CookieJar;
readonly window: DOMWindow;
readonly virtualConsole: VirtualConsole;
readonly cookieJar: CookieJar;
/**
* The serialize() method will return the HTML serialization of the document, including the doctype.
*/
serialize(): string;
/**
* The serialize() method will return the HTML serialization of the document, including the doctype.
*/
serialize(): string;
/**
* The nodeLocation() method will find where a DOM node is within the source document, returning the parse5 location info for the node.
*/
nodeLocation(node: Node): ElementLocation | null;
/**
* The nodeLocation() method will find where a DOM node is within the source document, returning the parse5 location info for the node.
*/
nodeLocation(node: Node): MarkupData.ElementLocation | null;
/**
* The built-in `vm` module of Node.js is what underpins jsdom's script-running magic.
* Some advanced use cases, like pre-compiling a script and then running it multiple
* times, benefit from using the `vm` module directly with a jsdom-created `Window`.
*
* @throws
* Note that this method will throw an exception if the `JSDOM` instance was created
* without `runScripts` set, or if you are using JSDOM in a web browser.
*/
getInternalVMContext(): DOMWindow;
/**
* The built-in vm module of Node.js allows you to create Script instances,
* which can be compiled ahead of time and then run multiple times on a given "VM context".
* Behind the scenes, a jsdom Window is indeed a VM context.
* To get access to this ability, use the runVMScript() method.
*/
runVMScript(script: Script): any;
/**
* The reconfigure method allows changing the `window.top` and url from the outside.
*/
reconfigure(settings: ReconfigureSettings): void;
}
reconfigure(settings: ReconfigureSettings): void;
}
export interface Options {
/**
* referrer just affects the value read from document.referrer.
* It defaults to no referrer (which reflects as the empty string).
*/
referrer?: string;
/**
* userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources.
* It defaults to `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`.
*/
userAgent?: string;
/**
* includeNodeLocations preserves the location info produced by the HTML parser,
* allowing you to retrieve it with the nodeLocation() method (described below).
* It defaults to false to give the best performance,
* and cannot be used with an XML content type since our XML parser does not support location info.
*/
includeNodeLocations?: boolean;
runScripts?: 'dangerously' | 'outside-only';
resources?: 'usable' | ResourceLoader;
virtualConsole?: VirtualConsole;
cookieJar?: CookieJar;
/**
* jsdom does not have the capability to render visual content, and will act like a headless browser by default.
* It provides hints to web pages through APIs such as document.hidden that their content is not visible.
*
* When the pretendToBeVisual option is set to true, jsdom will pretend that it is rendering and displaying
* content.
*/
pretendToBeVisual?: boolean;
beforeParse?(window: DOMWindow): void;
}
export type FromUrlOptions = Options;
export type FromFileOptions = Options & {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It will default to a file URL corresponding to the given filename, instead of to "about:blank".
*/
url?: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It will default to "application/xhtml+xml" if
* the given filename ends in .xhtml or .xml; otherwise it will continue to default to "text/html".
*/
contentType?: string;
};
export type ConstructorOptions = Options & {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It defaults to "about:blank".
*/
url?: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It defaults to "text/html".
*/
contentType?: string;
/**
* The maximum size in code units for the separate storage areas used by localStorage and sessionStorage.
* Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set
* to 5,000,000 code units per origin, as inspired by the HTML specification.
*/
storageQuota?: number
};
export interface DOMWindow extends Window {
eval(script: string): void;
/* node_modules/jsdom/living/index.js */
DOMException: typeof DOMException;
Attr: typeof Attr;
Node: typeof Node;
Element: typeof Element;
DocumentFragment: typeof DocumentFragment;
Document: typeof Document;
HTMLDocument: typeof HTMLDocument;
XMLDocument: typeof XMLDocument;
CharacterData: typeof CharacterData;
Text: typeof Text;
CDATASection: typeof CDATASection;
ProcessingInstruction: typeof ProcessingInstruction;
Comment: typeof Comment;
DocumentType: typeof DocumentType;
DOMImplementation: typeof DOMImplementation;
NodeList: typeof NodeList;
HTMLCollection: typeof HTMLCollection;
HTMLOptionsCollection: typeof HTMLOptionsCollection;
DOMStringMap: typeof DOMStringMap;
DOMTokenList: typeof DOMTokenList;
Event: typeof Event;
CustomEvent: typeof CustomEvent;
MessageEvent: typeof MessageEvent;
ErrorEvent: typeof ErrorEvent;
HashChangeEvent: typeof HashChangeEvent;
FocusEvent: typeof FocusEvent;
PopStateEvent: typeof PopStateEvent;
UIEvent: typeof UIEvent;
MouseEvent: typeof MouseEvent;
KeyboardEvent: typeof KeyboardEvent;
TouchEvent: typeof TouchEvent;
ProgressEvent: typeof ProgressEvent;
CompositionEvent: typeof CompositionEvent;
WheelEvent: typeof WheelEvent;
EventTarget: typeof EventTarget;
Location: typeof Location;
History: typeof History;
Blob: typeof Blob;
File: typeof File;
FileList: typeof FileList;
DOMParser: typeof DOMParser;
FormData: typeof FormData;
XMLHttpRequestEventTarget: XMLHttpRequestEventTarget;
XMLHttpRequestUpload: typeof XMLHttpRequestUpload;
NodeIterator: typeof NodeIterator;
TreeWalker: typeof TreeWalker;
NamedNodeMap: typeof NamedNodeMap;
URL: typeof URL;
URLSearchParams: typeof URLSearchParams;
/* node_modules/jsdom/living/register-elements.js */
HTMLElement: typeof HTMLElement;
HTMLAnchorElement: typeof HTMLAnchorElement;
HTMLAppletElement: typeof HTMLAppletElement;
HTMLAreaElement: typeof HTMLAreaElement;
HTMLAudioElement: typeof HTMLAudioElement;
HTMLBaseElement: typeof HTMLBaseElement;
HTMLBodyElement: typeof HTMLBodyElement;
HTMLBRElement: typeof HTMLBRElement;
HTMLButtonElement: typeof HTMLButtonElement;
HTMLCanvasElement: typeof HTMLCanvasElement;
HTMLDataElement: typeof HTMLDataElement;
HTMLDataListElement: typeof HTMLDataListElement;
// HTMLDetailsElement: typeof HTMLDetailsElement;
// HTMLDialogElement: typeof HTMLDialogElement;
HTMLDirectoryElement: typeof HTMLDirectoryElement;
HTMLDivElement: typeof HTMLDivElement;
HTMLDListElement: typeof HTMLDListElement;
HTMLEmbedElement: typeof HTMLEmbedElement;
HTMLFieldSetElement: typeof HTMLFieldSetElement;
HTMLFontElement: typeof HTMLFontElement;
HTMLFormElement: typeof HTMLFormElement;
HTMLFrameElement: typeof HTMLFrameElement;
HTMLFrameSetElement: typeof HTMLFrameSetElement;
HTMLHeadingElement: typeof HTMLHeadingElement;
HTMLHeadElement: typeof HTMLHeadElement;
HTMLHRElement: typeof HTMLHRElement;
HTMLHtmlElement: typeof HTMLHtmlElement;
HTMLIFrameElement: typeof HTMLIFrameElement;
HTMLImageElement: typeof HTMLImageElement;
HTMLInputElement: typeof HTMLInputElement;
HTMLLabelElement: typeof HTMLLabelElement;
HTMLLegendElement: typeof HTMLLegendElement;
HTMLLIElement: typeof HTMLLIElement;
HTMLLinkElement: typeof HTMLLinkElement;
HTMLMapElement: typeof HTMLMapElement;
HTMLMarqueeElement: typeof HTMLMarqueeElement;
HTMLMediaElement: typeof HTMLMediaElement;
HTMLMenuElement: typeof HTMLMenuElement;
HTMLMetaElement: typeof HTMLMetaElement;
HTMLMeterElement: typeof HTMLMeterElement;
HTMLModElement: typeof HTMLModElement;
HTMLObjectElement: typeof HTMLObjectElement;
HTMLOListElement: typeof HTMLOListElement;
HTMLOptGroupElement: typeof HTMLOptGroupElement;
HTMLOptionElement: typeof HTMLOptionElement;
HTMLOutputElement: typeof HTMLOutputElement;
HTMLParagraphElement: typeof HTMLParagraphElement;
HTMLParamElement: typeof HTMLParamElement;
HTMLPictureElement: typeof HTMLPictureElement;
HTMLPreElement: typeof HTMLPreElement;
HTMLProgressElement: typeof HTMLProgressElement;
HTMLQuoteElement: typeof HTMLQuoteElement;
HTMLScriptElement: typeof HTMLScriptElement;
HTMLSelectElement: typeof HTMLSelectElement;
HTMLSourceElement: typeof HTMLSourceElement;
HTMLSpanElement: typeof HTMLSpanElement;
HTMLStyleElement: typeof HTMLStyleElement;
HTMLTableCaptionElement: typeof HTMLTableCaptionElement;
HTMLTableCellElement: typeof HTMLTableCellElement;
HTMLTableColElement: typeof HTMLTableColElement;
HTMLTableElement: typeof HTMLTableElement;
HTMLTimeElement: typeof HTMLTimeElement;
HTMLTitleElement: typeof HTMLTitleElement;
HTMLTableRowElement: typeof HTMLTableRowElement;
HTMLTableSectionElement: typeof HTMLTableSectionElement;
HTMLTemplateElement: typeof HTMLTemplateElement;
HTMLTextAreaElement: typeof HTMLTextAreaElement;
HTMLTrackElement: typeof HTMLTrackElement;
HTMLUListElement: typeof HTMLUListElement;
HTMLUnknownElement: typeof HTMLUnknownElement;
HTMLVideoElement: typeof HTMLVideoElement;
/* node_modules/jsdom/level2/style.js */
StyleSheet: typeof StyleSheet;
MediaList: typeof MediaList;
CSSStyleSheet: typeof CSSStyleSheet;
CSSRule: typeof CSSRule;
CSSStyleRule: typeof CSSStyleRule;
CSSMediaRule: typeof CSSMediaRule;
CSSImportRule: typeof CSSImportRule;
CSSStyleDeclaration: typeof CSSStyleDeclaration;
StyleSheetList: typeof StyleSheetList;
/* node_modules/jsdom/level3/xpath.js */
// XPathException: typeof XPathException;
XPathExpression: typeof XPathExpression;
XPathResult: typeof XPathResult;
XPathEvaluator: typeof XPathEvaluator;
/* node_modules/jsdom/living/node-filter.js */
NodeFilter: typeof NodeFilter;
}
export type BinaryData = ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;
export class VirtualConsole extends EventEmitter {
on<K extends keyof Console>(method: K, callback: Console[K]): this;
on(event: 'jsdomError', callback: (e: Error) => void): this;
sendTo(console: Console, options?: VirtualConsoleSendToOptions): this;
}
export interface VirtualConsoleSendToOptions {
omitJSDOMErrors: boolean;
}
export class CookieJar extends tough.CookieJar { }
export const toughCookie: typeof tough;
export interface ReconfigureSettings {
windowTop?: DOMWindow;
url?: string;
}
export interface FetchOptions {
cookieJar?: CookieJar;
referrer?: string;
accept?: string;
element?: HTMLScriptElement | HTMLLinkElement | HTMLIFrameElement | HTMLImageElement;
}
export interface ResourceLoaderConstructorOptions {
strictSSL?: boolean;
proxy?: string;
userAgent?: string;
}
export class ResourceLoader {
fetch(url: string, options: FetchOptions): Promise<Buffer> | null;
constructor(obj?: ResourceLoaderConstructorOptions);
class ResourceLoader {
fetch(url: string, options: FetchOptions): Promise<Buffer>;
constructor(obj?: ResourceLoaderConstructorOptions);
}
class VirtualConsole extends EventEmitter {
on<K extends keyof Console>(method: K, callback: Console[K]): this;
on(event: 'jsdomError', callback: (e: Error) => void): this;
sendTo(console: Console, options?: VirtualConsoleSendToOptions): this;
}
type BinaryData =
| ArrayBuffer
| DataView
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array;
interface BaseOptions {
/**
* referrer just affects the value read from document.referrer.
* It defaults to no referrer (which reflects as the empty string).
*/
referrer?: string;
/**
* userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources.
* It defaults to `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`.
*/
userAgent?: string;
/**
* includeNodeLocations preserves the location info produced by the HTML parser,
* allowing you to retrieve it with the nodeLocation() method (described below).
* It defaults to false to give the best performance,
* and cannot be used with an XML content type since our XML parser does not support location info.
*/
includeNodeLocations?: boolean;
runScripts?: 'dangerously' | 'outside-only';
resources?: 'usable' | ResourceLoader;
virtualConsole?: VirtualConsole;
cookieJar?: CookieJar;
/**
* jsdom does not have the capability to render visual content, and will act like a headless browser by default.
* It provides hints to web pages through APIs such as document.hidden that their content is not visible.
*
* When the pretendToBeVisual option is set to true, jsdom will pretend that it is rendering and displaying
* content.
*/
pretendToBeVisual?: boolean;
beforeParse?(window: DOMWindow): void;
}
interface FileOptions extends BaseOptions {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It will default to a file URL corresponding to the given filename, instead of to "about:blank".
*/
url?: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It will default to "application/xhtml+xml" if
* the given filename ends in .xhtml or .xml; otherwise it will continue to default to "text/html".
*/
contentType?: string;
}
interface ConstructorOptions extends BaseOptions {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It defaults to "about:blank".
*/
url?: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It defaults to "text/html".
*/
contentType?: string;
/**
* The maximum size in code units for the separate storage areas used by localStorage and sessionStorage.
* Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set
* to 5,000,000 code units per origin, as inspired by the HTML specification.
*
* @default 5_000_000
*/
storageQuota?: number;
}
interface VirtualConsoleSendToOptions {
omitJSDOMErrors: boolean;
}
interface ReconfigureSettings {
windowTop?: DOMWindow;
url?: string;
}
interface FetchOptions {
cookieJar?: CookieJar;
referrer?: string;
accept?: string;
element?: HTMLScriptElement | HTMLLinkElement | HTMLIFrameElement | HTMLImageElement;
}
interface ResourceLoaderConstructorOptions {
strictSSL?: boolean;
proxy?: string;
userAgent?: string;
}
interface DOMWindow extends Pick<Window, Exclude<keyof Window, 'top' | 'self' | 'window'>>, Context {
/* node_modules/jsdom/browser/Window.js */
Window: typeof Window;
readonly top: DOMWindow;
readonly self: DOMWindow;
readonly window: DOMWindow;
/* ECMAScript Globals */
globalThis: DOMWindow;
readonly ['Infinity']: number;
readonly ['NaN']: number;
readonly undefined: undefined;
eval(script: string): any;
parseInt(s: string, radix?: number): number;
parseFloat(string: string): number;
isNaN(number: number): boolean;
isFinite(number: number): boolean;
decodeURI(encodedURI: string): string;
decodeURIComponent(encodedURIComponent: string): string;
encodeURI(uri: string): string;
encodeURIComponent(uriComponent: string | number | boolean): string;
escape(string: string): string;
unescape(string: string): string;
Array: typeof Array;
ArrayBuffer: typeof ArrayBuffer;
Boolean: typeof Boolean;
DataView: typeof DataView;
Date: typeof Date;
Error: typeof Error;
EvalError: typeof EvalError;
Float32Array: typeof Float32Array;
Float64Array: typeof Float64Array;
Function: typeof Function;
Int16Array: typeof Int16Array;
Int32Array: typeof Int32Array;
Int8Array: typeof Int8Array;
Intl: typeof Intl;
JSON: typeof JSON;
Map: typeof Map;
Math: typeof Math;
Number: typeof Number;
Object: typeof Object;
Promise: typeof Promise;
Proxy: typeof Proxy;
RangeError: typeof RangeError;
ReferenceError: typeof ReferenceError;
Reflect: typeof Reflect;
RegExp: typeof RegExp;
Set: typeof Set;
String: typeof String;
Symbol: typeof Symbol;
SyntaxError: typeof SyntaxError;
TypeError: typeof TypeError;
URIError: typeof URIError;
Uint16Array: typeof Uint16Array;
Uint32Array: typeof Uint32Array;
Uint8Array: typeof Uint8Array;
Uint8ClampedArray: typeof Uint8ClampedArray;
WeakMap: typeof WeakMap;
WeakSet: typeof WeakSet;
/* node_modules/jsdom/living/interfaces.js */
DOMException: typeof DOMException;
URL: typeof URL;
URLSearchParams: typeof URLSearchParams;
EventTarget: typeof EventTarget;
NamedNodeMap: typeof NamedNodeMap;
Node: typeof Node;
Attr: typeof Attr;
Element: typeof Element;
DocumentFragment: typeof DocumentFragment;
Document: typeof Document;
XMLDocument: typeof XMLDocument;
CharacterData: typeof CharacterData;
Text: typeof Text;
CDATASection: typeof CDATASection;
ProcessingInstruction: typeof ProcessingInstruction;
Comment: typeof Comment;
DocumentType: typeof DocumentType;
DOMImplementation: typeof DOMImplementation;
NodeList: typeof NodeList;
HTMLCollection: typeof HTMLCollection;
HTMLOptionsCollection: typeof HTMLOptionsCollection;
DOMStringMap: typeof DOMStringMap;
DOMTokenList: typeof DOMTokenList;
HTMLElement: typeof HTMLElement;
HTMLHeadElement: typeof HTMLHeadElement;
HTMLTitleElement: typeof HTMLTitleElement;
HTMLBaseElement: typeof HTMLBaseElement;
HTMLLinkElement: typeof HTMLLinkElement;
HTMLMetaElement: typeof HTMLMetaElement;
HTMLStyleElement: typeof HTMLStyleElement;
HTMLBodyElement: typeof HTMLBodyElement;
HTMLHeadingElement: typeof HTMLHeadingElement;
HTMLParagraphElement: typeof HTMLParagraphElement;
HTMLHRElement: typeof HTMLHRElement;
HTMLPreElement: typeof HTMLPreElement;
HTMLUListElement: typeof HTMLUListElement;
HTMLOListElement: typeof HTMLOListElement;
HTMLLIElement: typeof HTMLLIElement;
HTMLMenuElement: typeof HTMLMenuElement;
HTMLDListElement: typeof HTMLDListElement;
HTMLDivElement: typeof HTMLDivElement;
HTMLAnchorElement: typeof HTMLAnchorElement;
HTMLAreaElement: typeof HTMLAreaElement;
HTMLBRElement: typeof HTMLBRElement;
HTMLButtonElement: typeof HTMLButtonElement;
HTMLCanvasElement: typeof HTMLCanvasElement;
HTMLDataElement: typeof HTMLDataElement;
HTMLDataListElement: typeof HTMLDataListElement;
HTMLDetailsElement: typeof HTMLDetailsElement;
HTMLDialogElement: typeof HTMLDialogElement;
HTMLDirectoryElement: typeof HTMLDirectoryElement;
HTMLFieldSetElement: typeof HTMLFieldSetElement;
HTMLFontElement: typeof HTMLFontElement;
HTMLFormElement: typeof HTMLFormElement;
HTMLHtmlElement: typeof HTMLHtmlElement;
HTMLImageElement: typeof HTMLImageElement;
HTMLInputElement: typeof HTMLInputElement;
HTMLLabelElement: typeof HTMLLabelElement;
HTMLLegendElement: typeof HTMLLegendElement;
HTMLMapElement: typeof HTMLMapElement;
HTMLMarqueeElement: typeof HTMLMarqueeElement;
HTMLMediaElement: typeof HTMLMediaElement;
HTMLMeterElement: typeof HTMLMeterElement;
HTMLModElement: typeof HTMLModElement;
HTMLOptGroupElement: typeof HTMLOptGroupElement;
HTMLOptionElement: typeof HTMLOptionElement;
HTMLOutputElement: typeof HTMLOutputElement;
HTMLPictureElement: typeof HTMLPictureElement;
HTMLProgressElement: typeof HTMLProgressElement;
HTMLQuoteElement: typeof HTMLQuoteElement;
HTMLScriptElement: typeof HTMLScriptElement;
HTMLSelectElement: typeof HTMLSelectElement;
HTMLSourceElement: typeof HTMLSourceElement;
HTMLSpanElement: typeof HTMLSpanElement;
HTMLTableCaptionElement: typeof HTMLTableCaptionElement;
HTMLTableCellElement: typeof HTMLTableCellElement;
HTMLTableColElement: typeof HTMLTableColElement;
HTMLTableElement: typeof HTMLTableElement;
HTMLTimeElement: typeof HTMLTimeElement;
HTMLTableRowElement: typeof HTMLTableRowElement;
HTMLTableSectionElement: typeof HTMLTableSectionElement;
HTMLTemplateElement: typeof HTMLTemplateElement;
HTMLTextAreaElement: typeof HTMLTextAreaElement;
HTMLUnknownElement: typeof HTMLUnknownElement;
HTMLFrameElement: typeof HTMLFrameElement;
HTMLFrameSetElement: typeof HTMLFrameSetElement;
HTMLIFrameElement: typeof HTMLIFrameElement;
HTMLEmbedElement: typeof HTMLEmbedElement;
HTMLObjectElement: typeof HTMLObjectElement;
HTMLParamElement: typeof HTMLParamElement;
HTMLVideoElement: typeof HTMLVideoElement;
HTMLAudioElement: typeof HTMLAudioElement;
HTMLTrackElement: typeof HTMLTrackElement;
SVGElement: typeof SVGElement;
SVGGraphicsElement: typeof SVGGraphicsElement;
SVGSVGElement: typeof SVGSVGElement;
SVGTitleElement: typeof SVGTitleElement;
SVGAnimatedString: typeof SVGAnimatedString;
SVGNumber: typeof SVGNumber;
SVGStringList: typeof SVGStringList;
Event: typeof Event;
CloseEvent: typeof CloseEvent;
CustomEvent: typeof CustomEvent;
MessageEvent: typeof MessageEvent;
ErrorEvent: typeof ErrorEvent;
HashChangeEvent: typeof HashChangeEvent;
PopStateEvent: typeof PopStateEvent;
StorageEvent: typeof StorageEvent;
ProgressEvent: typeof ProgressEvent;
PageTransitionEvent: typeof PageTransitionEvent;
UIEvent: typeof UIEvent;
FocusEvent: typeof FocusEvent;
MouseEvent: typeof MouseEvent;
KeyboardEvent: typeof KeyboardEvent;
TouchEvent: typeof TouchEvent;
CompositionEvent: typeof CompositionEvent;
WheelEvent: typeof WheelEvent;
BarProp: typeof BarProp;
Location: typeof Location;
History: typeof History;
Screen: typeof Screen;
Performance: typeof Performance;
Navigator: typeof Navigator;
PluginArray: typeof PluginArray;
MimeTypeArray: typeof MimeTypeArray;
Plugin: typeof Plugin;
MimeType: typeof MimeType;
FileReader: typeof FileReader;
Blob: typeof Blob;
File: typeof File;
FileList: typeof FileList;
ValidityState: typeof ValidityState;
DOMParser: typeof DOMParser;
XMLSerializer: typeof XMLSerializer;
FormData: typeof FormData;
XMLHttpRequestEventTarget: typeof XMLHttpRequestEventTarget;
XMLHttpRequestUpload: typeof XMLHttpRequestUpload;
XMLHttpRequest: typeof XMLHttpRequest;
WebSocket: typeof WebSocket;
NodeIterator: typeof NodeIterator;
TreeWalker: typeof TreeWalker;
Range: typeof Range;
Selection: typeof Selection;
Storage: typeof Storage;
MutationObserver: typeof MutationObserver;
MutationRecord: typeof MutationRecord;
Headers: typeof Headers;
AbortController: typeof AbortController;
AbortSignal: typeof AbortSignal;
/* node_modules/jsdom/living/node-filter.js */
NodeFilter: typeof NodeFilter;
/* node_modules/jsdom/level2/style.js */
StyleSheet: typeof StyleSheet;
MediaList: typeof MediaList;
CSSStyleSheet: typeof CSSStyleSheet;
CSSRule: typeof CSSRule;
CSSStyleRule: typeof CSSStyleRule;
CSSMediaRule: typeof CSSMediaRule;
CSSImportRule: typeof CSSImportRule;
CSSStyleDeclaration: typeof CSSStyleDeclaration;
StyleSheetList: typeof StyleSheetList;
/* node_modules/jsdom/level3/xpath.js */
// XPathException: typeof XPathException;
XPathExpression: typeof XPathExpression;
XPathResult: typeof XPathResult;
XPathEvaluator: typeof XPathEvaluator;
}
}
+119 -111
View File
@@ -1,191 +1,199 @@
import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow, ResourceLoader, FetchOptions, ConstructorOptions } from 'jsdom';
import {
JSDOM,
VirtualConsole,
CookieJar,
BaseOptions,
FileOptions,
DOMWindow,
ResourceLoader,
FetchOptions,
ConstructorOptions,
} from 'jsdom';
import { CookieJar as ToughCookieJar, MemoryCookieStore } from 'tough-cookie';
import { Script } from 'vm';
function test_basic_usage() {
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector('p')!.textContent); // "Hello world"
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector('p')!.textContent); // "Hello world"
const { window } = new JSDOM(`...`);
// or even
const { document } = (new JSDOM(`...`)).window;
const { window } = new JSDOM(`...`);
// or even
const { document } = new JSDOM(`...`).window;
}
function test_executing_scripts1() {
const dom = new JSDOM(`<body>
const dom = new JSDOM(`<body>
<script>document.body.appendChild(document.createElement("hr"));</script>
</body>`);
// The script will not be executed, by default:
dom.window.document.body.children.length === 1;
// The script will not be executed, by default:
dom.window.document.body.children.length === 1;
}
function test_executing_scripts2() {
const dom = new JSDOM(`<body>
const dom = new JSDOM(
`<body>
<script>document.body.appendChild(document.createElement("hr"));</script>
</body>`, { runScripts: 'dangerously' });
</body>`,
{ runScripts: 'dangerously' },
);
// The script will be executed and modify the DOM:
dom.window.document.body.children.length === 2;
// The script will be executed and modify the DOM:
dom.window.document.body.children.length === 2;
}
function test_executing_scripts3() {
const window = (new JSDOM(``, { runScripts: 'outside-only' })).window;
const window = new JSDOM(``, { runScripts: 'outside-only' }).window;
window.eval(`document.body.innerHTML = "<p>Hello, world!</p>";`);
window.document.body.children.length === 1;
window.eval(`document.body.innerHTML = "<p>Hello, world!</p>";`);
window.document.body.children.length === 1;
}
function test_virtualConsole() {
const virtualConsole = new VirtualConsole();
const dom = new JSDOM(``, { virtualConsole });
const virtualConsole = new VirtualConsole();
const dom = new JSDOM(``, { virtualConsole });
virtualConsole.on('error', () => { });
virtualConsole.on('warn', () => { });
virtualConsole.on('info', () => { });
virtualConsole.on('dir', () => { });
// ... etc. See https://console.spec.whatwg.org/#logging
virtualConsole.on('error', () => {});
virtualConsole.on('warn', () => {});
virtualConsole.on('info', () => {});
virtualConsole.on('dir', () => {});
// ... etc. See https://console.spec.whatwg.org/#logging
virtualConsole.sendTo(console);
virtualConsole.sendTo(console);
const c = console;
virtualConsole.sendTo(c, { omitJSDOMErrors: true });
const c = console;
virtualConsole.sendTo(c, { omitJSDOMErrors: true });
}
function test_cookieJar() {
const store = {} as MemoryCookieStore;
const options = {} as ToughCookieJar.Options;
const cookieJar: CookieJar = new CookieJar(store, options);
const constructorOptions: ConstructorOptions = { cookieJar };
const dom = new JSDOM(``, constructorOptions);
function test_cookieJar(store: MemoryCookieStore, options: ToughCookieJar.Options) {
const cookieJar: CookieJar = new CookieJar(store, options);
const constructorOptions: ConstructorOptions = { cookieJar };
const dom = new JSDOM(``, constructorOptions);
}
function test_beforeParse() {
const dom = new JSDOM(`<p>Hello</p>`, {
beforeParse(window) {
window.document.childNodes.length === 0;
}
});
const dom = new JSDOM(`<p>Hello</p>`, {
beforeParse(window) {
window.document.childNodes.length === 0;
},
});
}
function test_storageQuota() {
new JSDOM('', { storageQuota: 1337 });
new JSDOM('', { storageQuota: 1337 });
}
function test_pretendToBeVisual() {
new JSDOM('', { pretendToBeVisual: true });
new JSDOM('', { pretendToBeVisual: true });
}
function test_serialize() {
const dom = new JSDOM(`<!DOCTYPE html>hello`);
const dom = new JSDOM(`<!DOCTYPE html>hello`);
dom.serialize() === '<!DOCTYPE html><html><head></head><body>hello</body></html>';
dom.serialize() === '<!DOCTYPE html><html><head></head><body>hello</body></html>';
// Contrast with:
// tslint:disable-next-line no-unnecessary-type-assertion
dom.window.document.documentElement!.outerHTML === '<html><head></head><body>hello</body></html>';
// Contrast with:
// tslint:disable-next-line no-unnecessary-type-assertion
dom.window.document.documentElement!.outerHTML === '<html><head></head><body>hello</body></html>';
}
function test_nodeLocation() {
const dom = new JSDOM(
`<p>Hello
const dom = new JSDOM(
`<p>Hello
<img src="foo.jpg">
</p>`,
{ includeNodeLocations: true }
);
{ includeNodeLocations: true },
);
const document = dom.window.document;
const bodyEl = document.body; // implicitly created
const pEl = document.querySelector('p')!;
const textNode = pEl.firstChild!;
const imgEl = document.querySelector('img')!;
const document = dom.window.document;
const bodyEl = document.body; // implicitly created
const pEl = document.querySelector('p')!;
const textNode = pEl.firstChild!;
const imgEl = document.querySelector('img')!;
console.log(dom.nodeLocation(bodyEl)); // null; it's not in the source
console.log(dom.nodeLocation(pEl)); // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... }
console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 }
console.log(dom.nodeLocation(imgEl)); // { startOffset: 13, endOffset: 32 }
console.log(dom.nodeLocation(bodyEl)); // null; it's not in the source
console.log(dom.nodeLocation(pEl)); // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... }
console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 }
console.log(dom.nodeLocation(imgEl)); // { startOffset: 13, endOffset: 32 }
}
function test_runVMScript() {
const dom = new JSDOM(``, { runScripts: 'outside-only' });
const s = new Script(`
if (!this.ran) {
this.ran = 0;
}
const dom = new JSDOM(``, { runScripts: 'outside-only' });
const script = new Script(`
if (!this.ran) {
this.ran = 0;
}
++this.ran;
++this.ran;
`);
dom.runVMScript(s);
dom.runVMScript(s);
dom.runVMScript(s);
const vmContext = dom.getInternalVMContext();
(dom.window as any).ran === 3;
script.runInContext(vmContext);
script.runInContext(vmContext);
script.runInContext(vmContext);
dom.window.ran === 3;
}
function test_reconfigure() {
const myFakeTopForTesting = {} as DOMWindow;
function test_reconfigure(myFakeTopForTesting: DOMWindow) {
const dom = new JSDOM();
const dom = new JSDOM();
dom.window.top === dom.window;
dom.window.location.href === 'about:blank';
dom.window.top === dom.window;
dom.window.location.href === 'about:blank';
dom.reconfigure({ windowTop: myFakeTopForTesting, url: 'https://example.com/' });
dom.reconfigure({ windowTop: myFakeTopForTesting, url: 'https://example.com/' });
dom.window.top === myFakeTopForTesting;
dom.window.location.href === 'https://example.com/';
dom.window.top === myFakeTopForTesting;
dom.window.location.href === 'https://example.com/';
}
function test_fromURL() {
const options = {} as FromUrlOptions;
const options: BaseOptions = {};
JSDOM.fromURL('https://example.com/', options).then(dom => {
console.log(dom.serialize());
});
JSDOM.fromURL('https://example.com/', options).then(dom => {
console.log(dom.serialize());
});
function pretendToBeVisual() {
JSDOM.fromURL("https://github.com", {
pretendToBeVisual: true
});
}
function pretendToBeVisual() {
JSDOM.fromURL('https://github.com', {
pretendToBeVisual: true,
});
}
}
function test_fromFile() {
const options = {} as FromFileOptions;
JSDOM.fromFile('stuff.html', options).then(dom => {
console.log(dom.serialize());
});
function test_fromFile(options: FileOptions) {
JSDOM.fromFile('stuff.html', options).then(dom => {
console.log(dom.serialize());
});
}
function test_fragment() {
const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`);
const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`);
frag.childNodes.length === 2;
frag.querySelector('strong')!.textContent = 'Why hello there!';
// etc.
frag.childNodes.length === 2;
frag.querySelector('strong')!.textContent = 'Why hello there!';
// etc.
}
function test_fragment_serialization() {
const frag = JSDOM.fragment(`<p>Hello</p>`);
if (frag instanceof Element) {
if (frag.firstChild instanceof Element) {
console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>"
}
}
const frag = JSDOM.fragment(`<p>Hello</p>`);
if (frag instanceof Element) {
if (frag.firstChild instanceof Element) {
console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>"
}
}
}
function test_custom_resource_loader() {
class CustomResourceLoader extends ResourceLoader {
fetch(url: string, options: FetchOptions) {
if (options.element) {
console.log(`Element ${options.element.localName} is requesting the url ${url}`);
}
class CustomResourceLoader extends ResourceLoader {
fetch(url: string, options: FetchOptions) {
if (options.element) {
console.log(`Element ${options.element.localName} is requesting the url ${url}`);
}
return super.fetch(url, options);
}
}
new JSDOM('', { resources: new CustomResourceLoader() });
return super.fetch(url, options);
}
}
new JSDOM('', { resources: new CustomResourceLoader() });
}
+8 -12
View File
@@ -1,14 +1,10 @@
{
"private": true,
"dependencies": {
"parse5": "^4.0.0"
},
"types": "index",
"typesVersions": {
">=3.1.0-0": {
"*": [
"ts3.1/*"
]
}
}
"private": true,
"types": "index",
"typesVersions": {
">=3.1.0-0": { "*": ["ts3.1/*"] }
,">=3.4.0-0": { "*": ["ts3.4/*"] }
,">=3.5.0-0": { "*": ["ts3.5/*"] }
,">=3.6.0-0": { "*": ["ts3.6/*"] }
}
}
+8 -318
View File
@@ -1,320 +1,10 @@
/// <reference lib="dom" />
/// <reference types="node" />
import '../index';
import { EventEmitter } from "events";
import { MarkupData } from "parse5";
import * as tough from "tough-cookie";
import { Script } from "vm";
export class JSDOM {
static fromURL(url: string, options?: FromUrlOptions): Promise<JSDOM>;
static fromFile(url: string, options?: FromFileOptions): Promise<JSDOM>;
static fragment(html: string): DocumentFragment;
constructor(
html?: string | Buffer | BinaryData,
options?: ConstructorOptions
);
readonly window: DOMWindow;
readonly virtualConsole: VirtualConsole;
readonly cookieJar: CookieJar;
/**
* The serialize() method will return the HTML serialization of the document, including the doctype.
*/
serialize(): string;
/**
* The nodeLocation() method will find where a DOM node is within the source document, returning the parse5 location info for the node.
*/
nodeLocation(node: Node): MarkupData.ElementLocation | null;
/**
* The built-in vm module of Node.js allows you to create Script instances,
* which can be compiled ahead of time and then run multiple times on a given "VM context".
* Behind the scenes, a jsdom Window is indeed a VM context.
* To get access to this ability, use the runVMScript() method.
*/
runVMScript(script: Script): void;
reconfigure(settings: ReconfigureSettings): void;
}
export interface Options {
/**
* referrer just affects the value read from document.referrer.
* It defaults to no referrer (which reflects as the empty string).
*/
referrer?: string;
/**
* userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources.
* It defaults to `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`.
*/
userAgent?: string;
/**
* includeNodeLocations preserves the location info produced by the HTML parser,
* allowing you to retrieve it with the nodeLocation() method (described below).
* It defaults to false to give the best performance,
* and cannot be used with an XML content type since our XML parser does not support location info.
*/
includeNodeLocations?: boolean;
runScripts?: "dangerously" | "outside-only";
resources?: "usable" | ResourceLoader;
virtualConsole?: VirtualConsole;
cookieJar?: CookieJar;
/**
* jsdom does not have the capability to render visual content, and will act like a headless browser by default.
* It provides hints to web pages through APIs such as document.hidden that their content is not visible.
*
* When the pretendToBeVisual option is set to true, jsdom will pretend that it is rendering and displaying
* content.
*/
pretendToBeVisual?: boolean;
beforeParse?(window: DOMWindow): void;
}
export type FromUrlOptions = Options;
export type FromFileOptions = Options & {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It will default to a file URL corresponding to the given filename, instead of to "about:blank".
*/
url?: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It will default to "application/xhtml+xml" if
* the given filename ends in .xhtml or .xml; otherwise it will continue to default to "text/html".
*/
contentType?: string;
};
export type ConstructorOptions = Options & {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It defaults to "about:blank".
*/
url?: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It defaults to "text/html".
*/
contentType?: string;
/**
* The maximum size in code units for the separate storage areas used by localStorage and sessionStorage.
* Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set
* to 5,000,000 code units per origin, as inspired by the HTML specification.
*/
storageQuota?: number;
};
export interface DOMWindow extends Window {
eval(script: string): void;
/* node_modules/jsdom/living/index.js */
DOMException: typeof DOMException;
Attr: typeof Attr;
Node: typeof Node;
Element: typeof Element;
DocumentFragment: typeof DocumentFragment;
Document: typeof Document;
HTMLDocument: typeof HTMLDocument;
XMLDocument: typeof XMLDocument;
CharacterData: typeof CharacterData;
Text: typeof Text;
CDATASection: typeof CDATASection;
ProcessingInstruction: typeof ProcessingInstruction;
Comment: typeof Comment;
DocumentType: typeof DocumentType;
DOMImplementation: typeof DOMImplementation;
NodeList: typeof NodeList;
HTMLCollection: typeof HTMLCollection;
HTMLOptionsCollection: typeof HTMLOptionsCollection;
DOMStringMap: typeof DOMStringMap;
DOMTokenList: typeof DOMTokenList;
Event: typeof Event;
CustomEvent: typeof CustomEvent;
MessageEvent: typeof MessageEvent;
ErrorEvent: typeof ErrorEvent;
HashChangeEvent: typeof HashChangeEvent;
FocusEvent: typeof FocusEvent;
PopStateEvent: typeof PopStateEvent;
UIEvent: typeof UIEvent;
MouseEvent: typeof MouseEvent;
KeyboardEvent: typeof KeyboardEvent;
TouchEvent: typeof TouchEvent;
ProgressEvent: typeof ProgressEvent;
CompositionEvent: typeof CompositionEvent;
WheelEvent: typeof WheelEvent;
EventTarget: typeof EventTarget;
Location: typeof Location;
History: typeof History;
Blob: typeof Blob;
File: typeof File;
FileList: typeof FileList;
DOMParser: typeof DOMParser;
FormData: typeof FormData;
XMLHttpRequestEventTarget: XMLHttpRequestEventTarget;
XMLHttpRequestUpload: typeof XMLHttpRequestUpload;
NodeIterator: typeof NodeIterator;
TreeWalker: typeof TreeWalker;
NamedNodeMap: typeof NamedNodeMap;
URL: typeof URL;
URLSearchParams: typeof URLSearchParams;
/* node_modules/jsdom/living/register-elements.js */
HTMLElement: typeof HTMLElement;
HTMLAnchorElement: typeof HTMLAnchorElement;
HTMLAppletElement: typeof HTMLAppletElement;
HTMLAreaElement: typeof HTMLAreaElement;
HTMLAudioElement: typeof HTMLAudioElement;
HTMLBaseElement: typeof HTMLBaseElement;
HTMLBodyElement: typeof HTMLBodyElement;
HTMLBRElement: typeof HTMLBRElement;
HTMLButtonElement: typeof HTMLButtonElement;
HTMLCanvasElement: typeof HTMLCanvasElement;
HTMLDataElement: typeof HTMLDataElement;
HTMLDataListElement: typeof HTMLDataListElement;
// HTMLDetailsElement: typeof HTMLDetailsElement;
// HTMLDialogElement: typeof HTMLDialogElement;
HTMLDirectoryElement: typeof HTMLDirectoryElement;
HTMLDivElement: typeof HTMLDivElement;
HTMLDListElement: typeof HTMLDListElement;
HTMLEmbedElement: typeof HTMLEmbedElement;
HTMLFieldSetElement: typeof HTMLFieldSetElement;
HTMLFontElement: typeof HTMLFontElement;
HTMLFormElement: typeof HTMLFormElement;
HTMLFrameElement: typeof HTMLFrameElement;
HTMLFrameSetElement: typeof HTMLFrameSetElement;
HTMLHeadingElement: typeof HTMLHeadingElement;
HTMLHeadElement: typeof HTMLHeadElement;
HTMLHRElement: typeof HTMLHRElement;
HTMLHtmlElement: typeof HTMLHtmlElement;
HTMLIFrameElement: typeof HTMLIFrameElement;
HTMLImageElement: typeof HTMLImageElement;
HTMLInputElement: typeof HTMLInputElement;
HTMLLabelElement: typeof HTMLLabelElement;
HTMLLegendElement: typeof HTMLLegendElement;
HTMLLIElement: typeof HTMLLIElement;
HTMLLinkElement: typeof HTMLLinkElement;
HTMLMapElement: typeof HTMLMapElement;
HTMLMarqueeElement: typeof HTMLMarqueeElement;
HTMLMediaElement: typeof HTMLMediaElement;
HTMLMenuElement: typeof HTMLMenuElement;
HTMLMetaElement: typeof HTMLMetaElement;
HTMLMeterElement: typeof HTMLMeterElement;
HTMLModElement: typeof HTMLModElement;
HTMLObjectElement: typeof HTMLObjectElement;
HTMLOListElement: typeof HTMLOListElement;
HTMLOptGroupElement: typeof HTMLOptGroupElement;
HTMLOptionElement: typeof HTMLOptionElement;
HTMLOutputElement: typeof HTMLOutputElement;
HTMLParagraphElement: typeof HTMLParagraphElement;
HTMLParamElement: typeof HTMLParamElement;
HTMLPictureElement: typeof HTMLPictureElement;
HTMLPreElement: typeof HTMLPreElement;
HTMLProgressElement: typeof HTMLProgressElement;
HTMLQuoteElement: typeof HTMLQuoteElement;
HTMLScriptElement: typeof HTMLScriptElement;
HTMLSelectElement: typeof HTMLSelectElement;
HTMLSourceElement: typeof HTMLSourceElement;
HTMLSpanElement: typeof HTMLSpanElement;
HTMLStyleElement: typeof HTMLStyleElement;
HTMLTableCaptionElement: typeof HTMLTableCaptionElement;
HTMLTableCellElement: typeof HTMLTableCellElement;
HTMLTableColElement: typeof HTMLTableColElement;
HTMLTableElement: typeof HTMLTableElement;
HTMLTimeElement: typeof HTMLTimeElement;
HTMLTitleElement: typeof HTMLTitleElement;
HTMLTableRowElement: typeof HTMLTableRowElement;
HTMLTableSectionElement: typeof HTMLTableSectionElement;
HTMLTemplateElement: typeof HTMLTemplateElement;
HTMLTextAreaElement: typeof HTMLTextAreaElement;
HTMLTrackElement: typeof HTMLTrackElement;
HTMLUListElement: typeof HTMLUListElement;
HTMLUnknownElement: typeof HTMLUnknownElement;
HTMLVideoElement: typeof HTMLVideoElement;
/* node_modules/jsdom/level2/style.js */
StyleSheet: typeof StyleSheet;
MediaList: typeof MediaList;
CSSStyleSheet: typeof CSSStyleSheet;
CSSRule: typeof CSSRule;
CSSStyleRule: typeof CSSStyleRule;
CSSMediaRule: typeof CSSMediaRule;
CSSImportRule: typeof CSSImportRule;
CSSStyleDeclaration: typeof CSSStyleDeclaration;
StyleSheetList: typeof StyleSheetList;
/* node_modules/jsdom/level3/xpath.js */
// XPathException: typeof XPathException;
XPathExpression: typeof XPathExpression;
XPathResult: typeof XPathResult;
XPathEvaluator: typeof XPathEvaluator;
/* node_modules/jsdom/living/node-filter.js */
NodeFilter: typeof NodeFilter;
}
export type BinaryData =
| ArrayBuffer
| DataView
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array;
export class VirtualConsole extends EventEmitter {
on<K extends keyof Console>(method: K, callback: Console[K]): this;
on(event: "jsdomError", callback: (e: Error) => void): this;
sendTo(console: Console, options?: VirtualConsoleSendToOptions): this;
}
export interface VirtualConsoleSendToOptions {
omitJSDOMErrors: boolean;
}
export class CookieJar extends tough.CookieJar {}
export const toughCookie: typeof tough;
export interface ReconfigureSettings {
windowTop?: DOMWindow;
url?: string;
}
export interface FetchOptions {
cookieJar?: CookieJar;
referrer?: string;
accept?: string;
element?:
| HTMLScriptElement
| HTMLLinkElement
| HTMLIFrameElement
| HTMLImageElement;
}
export interface ResourceLoaderConstructorOptions {
strictSSL?: boolean;
proxy?: string;
userAgent?: string;
}
export class ResourceLoader {
fetch(url: string, options: FetchOptions): Promise<Buffer> | null;
constructor(obj?: ResourceLoaderConstructorOptions);
// tslint:disable-next-line: no-declare-current-package
declare module 'jsdom' {
interface DOMWindow {
HTMLSlotElement: typeof HTMLSlotElement;
AbstractRange: typeof AbstractRange;
StaticRange: typeof StaticRange;
}
}
+6 -188
View File
@@ -1,190 +1,8 @@
import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow, ResourceLoader, FetchOptions } from 'jsdom';
import { CookieJar as ToughCookieJar, MemoryCookieStore } from 'tough-cookie';
import { Script } from 'vm';
import '../jsdom-tests';
import jsdom = require('jsdom');
function test_basic_usage() {
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector('p')!.textContent); // "Hello world"
declare const domWindow: jsdom.DOMWindow;
const { window } = new JSDOM(`...`);
// or even
const { document } = (new JSDOM(`...`)).window;
}
function test_executing_scripts1() {
const dom = new JSDOM(`<body>
<script>document.body.appendChild(document.createElement("hr"));</script>
</body>`);
// The script will not be executed, by default:
dom.window.document.body.children.length === 1;
}
function test_executing_scripts2() {
const dom = new JSDOM(`<body>
<script>document.body.appendChild(document.createElement("hr"));</script>
</body>`, { runScripts: 'dangerously' });
// The script will be executed and modify the DOM:
dom.window.document.body.children.length === 2;
}
function test_executing_scripts3() {
const window = (new JSDOM(``, { runScripts: 'outside-only' })).window;
window.eval(`document.body.innerHTML = "<p>Hello, world!</p>";`);
window.document.body.children.length === 1;
}
function test_virtualConsole() {
const virtualConsole = new VirtualConsole();
const dom = new JSDOM(``, { virtualConsole });
virtualConsole.on('error', () => { });
virtualConsole.on('warn', () => { });
virtualConsole.on('info', () => { });
virtualConsole.on('dir', () => { });
// ... etc. See https://console.spec.whatwg.org/#logging
virtualConsole.sendTo(console);
const c = console;
virtualConsole.sendTo(c, { omitJSDOMErrors: true });
}
function test_cookieJar() {
const store = {} as MemoryCookieStore;
const options = {} as ToughCookieJar.Options;
const cookieJar = new CookieJar(store, options);
const dom = new JSDOM(``, { cookieJar });
}
function test_beforeParse() {
const dom = new JSDOM(`<p>Hello</p>`, {
beforeParse(window) {
window.document.childNodes.length === 0;
}
});
}
function test_storageQuota() {
new JSDOM('', { storageQuota: 1337 });
}
function test_pretendToBeVisual() {
new JSDOM('', { pretendToBeVisual: true });
}
function test_serialize() {
const dom = new JSDOM(`<!DOCTYPE html>hello`);
dom.serialize() === '<!DOCTYPE html><html><head></head><body>hello</body></html>';
// Contrast with:
// tslint:disable-next-line no-unnecessary-type-assertion
dom.window.document.documentElement!.outerHTML === '<html><head></head><body>hello</body></html>';
}
function test_nodeLocation() {
const dom = new JSDOM(
`<p>Hello
<img src="foo.jpg">
</p>`,
{ includeNodeLocations: true }
);
const document = dom.window.document;
const bodyEl = document.body; // implicitly created
const pEl = document.querySelector('p')!;
const textNode = pEl.firstChild!;
const imgEl = document.querySelector('img')!;
console.log(dom.nodeLocation(bodyEl)); // null; it's not in the source
console.log(dom.nodeLocation(pEl)); // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... }
console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 }
console.log(dom.nodeLocation(imgEl)); // { startOffset: 13, endOffset: 32 }
}
function test_runVMScript() {
const dom = new JSDOM(``, { runScripts: 'outside-only' });
const s = new Script(`
if (!this.ran) {
this.ran = 0;
}
++this.ran;
`);
dom.runVMScript(s);
dom.runVMScript(s);
dom.runVMScript(s);
(<any> dom.window).ran === 3;
}
function test_reconfigure() {
const myFakeTopForTesting = {} as DOMWindow;
const dom = new JSDOM();
dom.window.top === dom.window;
dom.window.location.href === 'about:blank';
dom.reconfigure({ windowTop: myFakeTopForTesting, url: 'https://example.com/' });
dom.window.top === myFakeTopForTesting;
dom.window.location.href === 'https://example.com/';
}
function test_fromURL() {
const options = {} as FromUrlOptions;
JSDOM.fromURL('https://example.com/', options).then(dom => {
console.log(dom.serialize());
});
function pretendToBeVisual() {
JSDOM.fromURL("https://github.com", {
pretendToBeVisual: true
});
}
}
function test_fromFile() {
const options = {} as FromFileOptions;
JSDOM.fromFile('stuff.html', options).then(dom => {
console.log(dom.serialize());
});
}
function test_fragment() {
const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`);
frag.childNodes.length === 2;
frag.querySelector('strong')!.textContent = 'Why hello there!';
// etc.
}
function test_fragment_serialization() {
const frag = JSDOM.fragment(`<p>Hello</p>`);
if (frag instanceof Element) {
if (frag.firstChild instanceof Element) {
console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>"
}
}
}
function test_custom_resource_loader() {
class CustomResourceLoader extends ResourceLoader {
fetch(url: string, options: FetchOptions) {
if (options.element) {
console.log(`Element ${options.element.localName} is requesting the url ${url}`);
}
return super.fetch(url, options);
}
}
new JSDOM('', { resources: new CustomResourceLoader() });
}
domWindow.document.querySelector('slot'); // $ExpectType HTMLSlotElement | null
domWindow.AbstractRange.prototype; // $ExpectType AbstractRange
domWindow.StaticRange.prototype; // $ExpectType StaticRange
+17 -17
View File
@@ -1,19 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": ["../../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"parse5": ["parse5/v4"]
}
},
"files": ["index.d.ts", "jsdom-tests.ts"]
"compilerOptions": {
"module": "commonjs",
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": ["../../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"jsdom-tests.ts",
"index.d.ts"
]
}
+1 -8
View File
@@ -1,8 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
// TODOs
"no-empty-interface": false,
"no-object-literal-type-assertion": false
}
}
{ "extends": "dtslint/dt.json" }
+8
View File
@@ -0,0 +1,8 @@
import '../ts3.1/index';
// tslint:disable-next-line: no-declare-current-package
declare module 'jsdom' {
interface DOMWindow {
ShadowRoot: typeof ShadowRoot;
}
}
+9
View File
@@ -0,0 +1,9 @@
import '../ts3.1/jsdom-tests';
import jsdom = require('jsdom');
declare const domWindow: jsdom.DOMWindow;
domWindow.document.querySelector('slot'); // $ExpectType HTMLSlotElement | null
domWindow.AbstractRange.prototype; // $ExpectType AbstractRange
domWindow.StaticRange.prototype; // $ExpectType StaticRange
domWindow.ShadowRoot.prototype; // $ExpectType ShadowRoot
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": ["../../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"jsdom-tests.ts",
"index.d.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+13
View File
@@ -0,0 +1,13 @@
import '../ts3.4/index';
// tslint:disable-next-line: no-declare-current-package
declare module 'jsdom' {
interface DOMWindow {
Atomics: typeof Atomics;
BigInt: typeof BigInt;
BigInt64Array: typeof BigInt64Array;
BigUint64Array: typeof BigUint64Array;
SharedArrayBuffer: typeof SharedArrayBuffer;
WebAssembly: typeof WebAssembly;
}
}
+16
View File
@@ -0,0 +1,16 @@
import '../ts3.4/jsdom-tests';
import jsdom = require('jsdom');
declare const domWindow: jsdom.DOMWindow;
domWindow.document.querySelector('slot'); // $ExpectType HTMLSlotElement | null
domWindow.AbstractRange.prototype; // $ExpectType AbstractRange
domWindow.StaticRange.prototype; // $ExpectType StaticRange
domWindow.ShadowRoot.prototype; // $ExpectType ShadowRoot
domWindow.Atomics; // $ExpectType Atomics
domWindow.BigInt; // $ExpectType BigIntConstructor
domWindow.BigInt64Array; // $ExpectType BigInt64ArrayConstructor
domWindow.BigUint64Array; // $ExpectType BigUint64ArrayConstructor
domWindow.SharedArrayBuffer; // $ExpectType SharedArrayBufferConstructor
domWindow.WebAssembly; // $ExpectType typeof WebAssembly
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": ["../../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"jsdom-tests.ts",
"index.d.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+9
View File
@@ -0,0 +1,9 @@
import '../ts3.5/index';
// tslint:disable-next-line: no-declare-current-package
declare module 'jsdom' {
interface DOMWindow {
InputEvent: typeof InputEvent;
External: typeof External;
}
}
+16
View File
@@ -0,0 +1,16 @@
import '../ts3.5/jsdom-tests';
import jsdom = require('jsdom');
declare const domWindow: jsdom.DOMWindow;
domWindow.document.querySelector('slot'); // $ExpectType HTMLSlotElement | null
domWindow.AbstractRange.prototype; // $ExpectType AbstractRange
domWindow.StaticRange.prototype; // $ExpectType StaticRange
domWindow.ShadowRoot.prototype; // $ExpectType ShadowRoot
domWindow.Atomics; // $ExpectType Atomics
domWindow.BigInt; // $ExpectType BigIntConstructor
domWindow.BigInt64Array; // $ExpectType BigInt64ArrayConstructor
domWindow.BigUint64Array; // $ExpectType BigUint64ArrayConstructor
domWindow.SharedArrayBuffer; // $ExpectType SharedArrayBufferConstructor
domWindow.WebAssembly; // $ExpectType typeof WebAssembly
domWindow.external; // $ExpectType External
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": ["../../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"jsdom-tests.ts",
"index.d.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+17 -25
View File
@@ -1,27 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"parse5": [ "parse5/v4" ]
}
},
"files": [
"index.d.ts",
"jsdom-tests.ts"
]
"compilerOptions": {
"module": "commonjs",
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"jsdom-tests.ts",
"index.d.ts"
]
}
+1 -8
View File
@@ -1,8 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
// TODOs
"no-empty-interface": false,
"no-object-literal-type-assertion": false
}
}
{ "extends": "dtslint/dt.json" }
@@ -1,5 +1,10 @@
import Readability = require('mozilla-readability');
import { JSDOM } from 'jsdom';
declare class JSDOM {
constructor(html?: string);
readonly window: Window;
}
// Compiling requires `--noImplicitUseStrict`
// because issue https://github.com/mozilla/readability/issues/346
+1 -4
View File
@@ -15,10 +15,7 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"parse5": [ "parse5/v4" ]
}
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",