Initial pass
This commit is contained in:
+351
@@ -0,0 +1,351 @@
|
||||
"use strict";
|
||||
const path = require("path");
|
||||
const fs = require("pn/fs");
|
||||
const vm = require("vm");
|
||||
const toughCookie = require("tough-cookie");
|
||||
const request = require("request-promise-native");
|
||||
const sniffHTMLEncoding = require("html-encoding-sniffer");
|
||||
const whatwgURL = require("whatwg-url");
|
||||
const whatwgEncoding = require("whatwg-encoding");
|
||||
const { URL } = require("whatwg-url");
|
||||
const MIMEType = require("whatwg-mimetype");
|
||||
const idlUtils = require("./jsdom/living/generated/utils.js");
|
||||
const VirtualConsole = require("./jsdom/virtual-console.js");
|
||||
const Window = require("./jsdom/browser/Window.js");
|
||||
const { domToHtml } = require("./jsdom/browser/domtohtml.js");
|
||||
const { applyDocumentFeatures } = require("./jsdom/browser/documentfeatures.js");
|
||||
const { wrapCookieJarForRequest } = require("./jsdom/browser/resource-loader.js");
|
||||
const { version: packageVersion } = require("../package.json");
|
||||
|
||||
const DEFAULT_USER_AGENT = `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) ` +
|
||||
`jsdom/${packageVersion}`;
|
||||
|
||||
// This symbol allows us to smuggle a non-public option through to the JSDOM constructor, for use by JSDOM.fromURL.
|
||||
const transportLayerEncodingLabelHiddenOption = Symbol("transportLayerEncodingLabel");
|
||||
|
||||
class CookieJar extends toughCookie.CookieJar {
|
||||
constructor(store, options) {
|
||||
// jsdom cookie jars must be loose by default
|
||||
super(store, Object.assign({ looseMode: true }, options));
|
||||
}
|
||||
}
|
||||
|
||||
const window = Symbol("window");
|
||||
let sharedFragmentDocument = null;
|
||||
|
||||
class JSDOM {
|
||||
constructor(input, options = {}) {
|
||||
const { html, encoding } = normalizeHTML(input, options[transportLayerEncodingLabelHiddenOption]);
|
||||
options = transformOptions(options, encoding);
|
||||
|
||||
this[window] = new Window(options.windowOptions);
|
||||
|
||||
// TODO NEWAPI: the whole "features" infrastructure is horrible and should be re-built. When we switch to newapi
|
||||
// wholesale, or perhaps before, we should re-do it. For now, just adapt the new, nice, public API into the old,
|
||||
// ugly, internal API.
|
||||
const features = {
|
||||
FetchExternalResources: [],
|
||||
SkipExternalResources: false
|
||||
};
|
||||
|
||||
if (options.resources === "usable") {
|
||||
features.FetchExternalResources = ["link", "img", "frame", "iframe"];
|
||||
if (options.windowOptions.runScripts === "dangerously") {
|
||||
features.FetchExternalResources.push("script");
|
||||
}
|
||||
|
||||
// Note that "img" will be ignored by the code in HTMLImageElement-impl.js if canvas is not installed.
|
||||
// TODO NEWAPI: clean that up and centralize the logic here.
|
||||
}
|
||||
|
||||
const documentImpl = idlUtils.implForWrapper(this[window]._document);
|
||||
applyDocumentFeatures(documentImpl, features);
|
||||
|
||||
options.beforeParse(this[window]._globalProxy);
|
||||
|
||||
// TODO NEWAPI: this is still pretty hacky. It's also different than jsdom.jsdom. Does it work? Can it be better?
|
||||
documentImpl._htmlToDom.appendToDocument(html, documentImpl);
|
||||
documentImpl.close();
|
||||
}
|
||||
|
||||
get window() {
|
||||
// It's important to grab the global proxy, instead of just the result of `new Window(...)`, since otherwise things
|
||||
// like `window.eval` don't exist.
|
||||
return this[window]._globalProxy;
|
||||
}
|
||||
|
||||
get virtualConsole() {
|
||||
return this[window]._virtualConsole;
|
||||
}
|
||||
|
||||
get cookieJar() {
|
||||
// TODO NEWAPI move _cookieJar to window probably
|
||||
return idlUtils.implForWrapper(this[window]._document)._cookieJar;
|
||||
}
|
||||
|
||||
serialize() {
|
||||
return domToHtml([idlUtils.implForWrapper(this[window]._document)]);
|
||||
}
|
||||
|
||||
nodeLocation(node) {
|
||||
if (!idlUtils.implForWrapper(this[window]._document)._parseOptions.locationInfo) {
|
||||
throw new Error("Location information was not saved for this jsdom. Use includeNodeLocations during creation.");
|
||||
}
|
||||
|
||||
return idlUtils.implForWrapper(node).__location;
|
||||
}
|
||||
|
||||
runVMScript(script) {
|
||||
if (!vm.isContext(this[window])) {
|
||||
throw new TypeError("This jsdom was not configured to allow script running. " +
|
||||
"Use the runScripts option during creation.");
|
||||
}
|
||||
|
||||
return script.runInContext(this[window]);
|
||||
}
|
||||
|
||||
reconfigure(settings) {
|
||||
if ("windowTop" in settings) {
|
||||
this[window]._top = settings.windowTop;
|
||||
}
|
||||
|
||||
if ("url" in settings) {
|
||||
const document = idlUtils.implForWrapper(this[window]._document);
|
||||
|
||||
const url = whatwgURL.parseURL(settings.url);
|
||||
if (url === null) {
|
||||
throw new TypeError(`Could not parse "${settings.url}" as a URL`);
|
||||
}
|
||||
|
||||
document._URL = url;
|
||||
document.origin = whatwgURL.serializeURLOrigin(document._URL);
|
||||
}
|
||||
}
|
||||
|
||||
static fragment(string) {
|
||||
if (!sharedFragmentDocument) {
|
||||
sharedFragmentDocument = (new JSDOM()).window.document;
|
||||
}
|
||||
|
||||
const template = sharedFragmentDocument.createElement("template");
|
||||
template.innerHTML = string;
|
||||
return template.content;
|
||||
}
|
||||
|
||||
static fromURL(url, options = {}) {
|
||||
return Promise.resolve().then(() => {
|
||||
const parsedURL = new URL(url);
|
||||
url = parsedURL.href;
|
||||
options = normalizeFromURLOptions(options);
|
||||
|
||||
const requestOptions = {
|
||||
resolveWithFullResponse: true,
|
||||
encoding: null, // i.e., give me the raw Buffer
|
||||
gzip: true,
|
||||
headers: {
|
||||
"User-Agent": options.userAgent,
|
||||
Referer: options.referrer,
|
||||
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "en"
|
||||
},
|
||||
jar: wrapCookieJarForRequest(options.cookieJar)
|
||||
};
|
||||
|
||||
return request(url, requestOptions).then(res => {
|
||||
let transportLayerEncodingLabel;
|
||||
if ("content-type" in res.headers) {
|
||||
const mimeType = new MIMEType(res.headers["content-type"]);
|
||||
transportLayerEncodingLabel = mimeType.parameters.get("charset");
|
||||
}
|
||||
|
||||
options = Object.assign(options, {
|
||||
url: res.request.href + parsedURL.hash,
|
||||
contentType: res.headers["content-type"],
|
||||
referrer: res.request.getHeader("referer"),
|
||||
[transportLayerEncodingLabelHiddenOption]: transportLayerEncodingLabel
|
||||
});
|
||||
|
||||
return new JSDOM(res.body, options);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
static fromFile(filename, options = {}) {
|
||||
return Promise.resolve().then(() => {
|
||||
options = normalizeFromFileOptions(filename, options);
|
||||
|
||||
return fs.readFile(filename).then(buffer => {
|
||||
return new JSDOM(buffer, options);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFromURLOptions(options) {
|
||||
// Checks on options that are invalid for `fromURL`
|
||||
if (options.url !== undefined) {
|
||||
throw new TypeError("Cannot supply a url option when using fromURL");
|
||||
}
|
||||
if (options.contentType !== undefined) {
|
||||
throw new TypeError("Cannot supply a contentType option when using fromURL");
|
||||
}
|
||||
|
||||
// Normalization of options which must be done before the rest of the fromURL code can use them, because they are
|
||||
// given to request()
|
||||
const normalized = Object.assign({}, options);
|
||||
if (options.userAgent === undefined) {
|
||||
normalized.userAgent = DEFAULT_USER_AGENT;
|
||||
}
|
||||
|
||||
if (options.referrer !== undefined) {
|
||||
normalized.referrer = (new URL(options.referrer)).href;
|
||||
}
|
||||
|
||||
if (options.cookieJar === undefined) {
|
||||
normalized.cookieJar = new CookieJar();
|
||||
}
|
||||
|
||||
return normalized;
|
||||
|
||||
// All other options don't need to be processed yet, and can be taken care of in the normal course of things when
|
||||
// `fromURL` calls `new JSDOM(html, options)`.
|
||||
}
|
||||
|
||||
function normalizeFromFileOptions(filename, options) {
|
||||
const normalized = Object.assign({}, options);
|
||||
|
||||
if (normalized.contentType === undefined) {
|
||||
const extname = path.extname(filename);
|
||||
if (extname === ".xhtml" || extname === ".xml") {
|
||||
normalized.contentType = "application/xhtml+xml";
|
||||
}
|
||||
}
|
||||
|
||||
if (normalized.url === undefined) {
|
||||
normalized.url = new URL("file:" + path.resolve(filename));
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function transformOptions(options, encoding) {
|
||||
const transformed = {
|
||||
windowOptions: {
|
||||
// Defaults
|
||||
url: "about:blank",
|
||||
referrer: "",
|
||||
contentType: "text/html",
|
||||
parsingMode: "html",
|
||||
userAgent: DEFAULT_USER_AGENT,
|
||||
parseOptions: { locationInfo: false },
|
||||
runScripts: undefined,
|
||||
encoding,
|
||||
pretendToBeVisual: false,
|
||||
storageQuota: 5000000,
|
||||
|
||||
// Defaults filled in later
|
||||
virtualConsole: undefined,
|
||||
cookieJar: undefined
|
||||
},
|
||||
|
||||
// Defaults
|
||||
resources: undefined,
|
||||
beforeParse() { }
|
||||
};
|
||||
|
||||
if (options.contentType !== undefined) {
|
||||
const mimeType = new MIMEType(options.contentType);
|
||||
|
||||
if (!mimeType.isHTML() && !mimeType.isXML()) {
|
||||
throw new RangeError(`The given content type of "${options.contentType}" was not a HTML or XML content type`);
|
||||
}
|
||||
|
||||
transformed.windowOptions.contentType = mimeType.essence;
|
||||
transformed.windowOptions.parsingMode = mimeType.isHTML() ? "html" : "xml";
|
||||
}
|
||||
|
||||
if (options.url !== undefined) {
|
||||
transformed.windowOptions.url = (new URL(options.url)).href;
|
||||
}
|
||||
|
||||
if (options.referrer !== undefined) {
|
||||
transformed.windowOptions.referrer = (new URL(options.referrer)).href;
|
||||
}
|
||||
|
||||
if (options.userAgent !== undefined) {
|
||||
transformed.windowOptions.userAgent = String(options.userAgent);
|
||||
}
|
||||
|
||||
if (options.includeNodeLocations) {
|
||||
if (transformed.windowOptions.parsingMode === "xml") {
|
||||
throw new TypeError("Cannot set includeNodeLocations to true with an XML content type");
|
||||
}
|
||||
|
||||
transformed.windowOptions.parseOptions = { locationInfo: true };
|
||||
}
|
||||
|
||||
transformed.windowOptions.cookieJar = options.cookieJar === undefined ?
|
||||
new CookieJar() :
|
||||
options.cookieJar;
|
||||
|
||||
transformed.windowOptions.virtualConsole = options.virtualConsole === undefined ?
|
||||
(new VirtualConsole()).sendTo(console) :
|
||||
options.virtualConsole;
|
||||
|
||||
if (options.resources !== undefined) {
|
||||
transformed.resources = String(options.resources);
|
||||
if (transformed.resources !== "usable") {
|
||||
throw new RangeError(`resources must be undefined or "usable"`);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.runScripts !== undefined) {
|
||||
transformed.windowOptions.runScripts = String(options.runScripts);
|
||||
if (transformed.windowOptions.runScripts !== "dangerously" &&
|
||||
transformed.windowOptions.runScripts !== "outside-only") {
|
||||
throw new RangeError(`runScripts must be undefined, "dangerously", or "outside-only"`);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.beforeParse !== undefined) {
|
||||
transformed.beforeParse = options.beforeParse;
|
||||
}
|
||||
|
||||
if (options.pretendToBeVisual !== undefined) {
|
||||
transformed.windowOptions.pretendToBeVisual = Boolean(options.pretendToBeVisual);
|
||||
}
|
||||
|
||||
if (options.storageQuota !== undefined) {
|
||||
transformed.windowOptions.storageQuota = Number(options.storageQuota);
|
||||
}
|
||||
|
||||
// concurrentNodeIterators??
|
||||
|
||||
return transformed;
|
||||
}
|
||||
|
||||
function normalizeHTML(html = "", transportLayerEncodingLabel) {
|
||||
let encoding = "UTF-8";
|
||||
|
||||
if (ArrayBuffer.isView(html)) {
|
||||
html = Buffer.from(html.buffer, html.byteOffset, html.byteLength);
|
||||
} else if (html instanceof ArrayBuffer) {
|
||||
html = Buffer.from(html);
|
||||
}
|
||||
|
||||
if (Buffer.isBuffer(html)) {
|
||||
encoding = sniffHTMLEncoding(html, { defaultEncoding: "windows-1252", transportLayerEncodingLabel });
|
||||
html = whatwgEncoding.decode(html, encoding);
|
||||
} else {
|
||||
html = String(html);
|
||||
}
|
||||
|
||||
return { html, encoding };
|
||||
}
|
||||
|
||||
exports.JSDOM = JSDOM;
|
||||
|
||||
exports.VirtualConsole = VirtualConsole;
|
||||
exports.CookieJar = CookieJar;
|
||||
|
||||
exports.toughCookie = toughCookie;
|
||||
+704
File diff suppressed because it is too large
Load Diff
+785
File diff suppressed because it is too large
Load Diff
+55
@@ -0,0 +1,55 @@
|
||||
"use strict";
|
||||
const vm = require("vm");
|
||||
const idlUtils = require("../living/generated/utils");
|
||||
|
||||
exports.availableDocumentFeatures = [
|
||||
"FetchExternalResources",
|
||||
"SkipExternalResources"
|
||||
];
|
||||
|
||||
exports.defaultDocumentFeatures = {
|
||||
FetchExternalResources: ["script", "link"], // omitted by default: "frame"
|
||||
SkipExternalResources: false
|
||||
};
|
||||
|
||||
exports.applyDocumentFeatures = (documentImpl, features = {}) => {
|
||||
for (let i = 0; i < exports.availableDocumentFeatures.length; ++i) {
|
||||
const featureName = exports.availableDocumentFeatures[i];
|
||||
let featureSource;
|
||||
|
||||
if (features[featureName] !== undefined) {
|
||||
featureSource = features[featureName];
|
||||
// We have to check the lowercase version also because the Document feature
|
||||
// methods convert everything to lowercase.
|
||||
} else if (typeof features[featureName.toLowerCase()] !== "undefined") {
|
||||
featureSource = features[featureName.toLowerCase()];
|
||||
} else if (exports.defaultDocumentFeatures[featureName]) {
|
||||
featureSource = exports.defaultDocumentFeatures[featureName];
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
const implImpl = documentImpl._implementation;
|
||||
implImpl._removeFeature(featureName);
|
||||
|
||||
if (featureSource !== undefined) {
|
||||
if (Array.isArray(featureSource)) {
|
||||
for (let j = 0; j < featureSource.length; ++j) {
|
||||
implImpl._addFeature(featureName, featureSource[j]);
|
||||
}
|
||||
} else {
|
||||
implImpl._addFeature(featureName, featureSource);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.contextifyWindow = window => {
|
||||
if (vm.isContext(window)) {
|
||||
return;
|
||||
}
|
||||
|
||||
vm.createContext(window);
|
||||
const documentImpl = idlUtils.implForWrapper(window._document);
|
||||
documentImpl._defaultView = window._globalProxy = vm.runInContext("this", window);
|
||||
};
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
"use strict";
|
||||
const parse5 = require("parse5");
|
||||
const treeAdapter = require("./parse5-adapter-serialization");
|
||||
const NODE_TYPE = require("../living/node-type");
|
||||
|
||||
exports.domToHtml = iterable => {
|
||||
let ret = "";
|
||||
for (const node of iterable) {
|
||||
if (node.nodeType === NODE_TYPE.DOCUMENT_NODE) {
|
||||
ret += parse5.serialize(node, { treeAdapter });
|
||||
} else {
|
||||
// TODO: maybe parse5 can give us a hook where it serializes the node itself too:
|
||||
// https://github.com/inikulin/parse5/issues/230
|
||||
ret += parse5.serialize({ childNodesForSerializing: [node] }, { treeAdapter });
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
+271
@@ -0,0 +1,271 @@
|
||||
"use strict";
|
||||
|
||||
const parse5 = require("parse5");
|
||||
const sax = require("sax");
|
||||
const attributes = require("../living/attributes");
|
||||
const DocumentType = require("../living/generated/DocumentType");
|
||||
const JSDOMParse5Adapter = require("./parse5-adapter-parsing");
|
||||
const { HTML_NS } = require("../living/helpers/namespaces");
|
||||
|
||||
// Horrible monkey-patch to implement https://github.com/inikulin/parse5/issues/237
|
||||
const OpenElementStack = require("parse5/lib/parser/open_element_stack");
|
||||
const originalPop = OpenElementStack.prototype.pop;
|
||||
OpenElementStack.prototype.pop = function (...args) {
|
||||
const before = this.items[this.stackTop];
|
||||
originalPop.apply(this, args);
|
||||
if (before._poppedOffStackOfOpenElements) {
|
||||
before._poppedOffStackOfOpenElements();
|
||||
}
|
||||
};
|
||||
|
||||
const originalPush = OpenElementStack.prototype.push;
|
||||
OpenElementStack.prototype.push = function (...args) {
|
||||
originalPush.apply(this, args);
|
||||
const after = this.items[this.stackTop];
|
||||
if (after._pushedOnStackOfOpenElements) {
|
||||
after._pushedOnStackOfOpenElements();
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = class HTMLToDOM {
|
||||
constructor(parsingMode) {
|
||||
this.parser = parsingMode === "xml" ? sax : parse5;
|
||||
}
|
||||
|
||||
appendToNode(html, node) {
|
||||
html = String(html);
|
||||
|
||||
return this._doParse(html, true, node);
|
||||
}
|
||||
|
||||
appendToDocument(html, documentImpl) {
|
||||
html = String(html);
|
||||
|
||||
return this._doParse(html, false, documentImpl, documentImpl._parseOptions);
|
||||
}
|
||||
|
||||
_doParse(...args) {
|
||||
return this.parser === parse5 ? this._parseWithParse5(...args) : this._parseWithSax(...args);
|
||||
}
|
||||
|
||||
_parseWithParse5(html, isFragment, contextNode, options = {}) {
|
||||
const adapter = new JSDOMParse5Adapter(contextNode._ownerDocument || contextNode);
|
||||
options.treeAdapter = adapter;
|
||||
|
||||
if (isFragment) {
|
||||
const fragment = this.parser.parseFragment(contextNode, html, options);
|
||||
|
||||
if (contextNode._templateContents) {
|
||||
contextNode._templateContents.appendChild(fragment);
|
||||
} else {
|
||||
contextNode.appendChild(fragment);
|
||||
}
|
||||
} else {
|
||||
this.parser.parse(html, options);
|
||||
}
|
||||
|
||||
return contextNode;
|
||||
}
|
||||
|
||||
_parseWithSax(html, isFragment, contextNode) {
|
||||
const SaxParser = this.parser.parser;
|
||||
const parser = new SaxParser(/* strict = */true, { xmlns: true, strictEntities: true });
|
||||
parser.noscript = false;
|
||||
parser.looseCase = "toString";
|
||||
const openStack = [contextNode];
|
||||
parser.ontext = text => {
|
||||
setChildForSax(openStack[openStack.length - 1], {
|
||||
type: "text",
|
||||
data: text
|
||||
});
|
||||
};
|
||||
parser.oncdata = cdata => {
|
||||
setChildForSax(openStack[openStack.length - 1], {
|
||||
type: "cdata",
|
||||
data: cdata
|
||||
});
|
||||
};
|
||||
parser.onopentag = arg => {
|
||||
const attrs = Object.keys(arg.attributes).map(key => {
|
||||
const rawAttribute = arg.attributes[key];
|
||||
|
||||
let { prefix } = rawAttribute;
|
||||
let localName = rawAttribute.local;
|
||||
if (prefix === "xmlns" && localName === "") {
|
||||
// intended weirdness in node-sax, see https://github.com/isaacs/sax-js/issues/165
|
||||
localName = prefix;
|
||||
prefix = null;
|
||||
}
|
||||
|
||||
if (prefix === "") {
|
||||
prefix = null;
|
||||
}
|
||||
|
||||
const namespace = rawAttribute.uri === "" ? null : rawAttribute.uri;
|
||||
|
||||
return { name: rawAttribute.name, value: rawAttribute.value, prefix, localName, namespace };
|
||||
});
|
||||
const tag = {
|
||||
type: "tag",
|
||||
name: arg.local,
|
||||
prefix: arg.prefix,
|
||||
namespace: arg.uri,
|
||||
attributes: attrs
|
||||
};
|
||||
|
||||
if (arg.local === "script" && arg.uri === HTML_NS) {
|
||||
openStack.push(tag);
|
||||
} else {
|
||||
const elem = setChildForSax(openStack[openStack.length - 1], tag);
|
||||
openStack.push(elem);
|
||||
}
|
||||
};
|
||||
parser.onclosetag = () => {
|
||||
const elem = openStack.pop();
|
||||
if (elem.constructor.name === "Object") { // we have an empty script tag
|
||||
setChildForSax(openStack[openStack.length - 1], elem);
|
||||
}
|
||||
};
|
||||
parser.onscript = scriptText => {
|
||||
const tag = openStack.pop();
|
||||
tag.children = [{ type: "text", data: scriptText }];
|
||||
const elem = setChildForSax(openStack[openStack.length - 1], tag);
|
||||
openStack.push(elem);
|
||||
};
|
||||
parser.oncomment = comment => {
|
||||
setChildForSax(openStack[openStack.length - 1], {
|
||||
type: "comment",
|
||||
data: comment
|
||||
});
|
||||
};
|
||||
parser.onprocessinginstruction = pi => {
|
||||
setChildForSax(openStack[openStack.length - 1], {
|
||||
type: "directive",
|
||||
name: "?" + pi.name,
|
||||
data: "?" + pi.name + " " + pi.body + "?"
|
||||
});
|
||||
};
|
||||
parser.ondoctype = dt => {
|
||||
setChildForSax(openStack[openStack.length - 1], {
|
||||
type: "directive",
|
||||
name: "!doctype",
|
||||
data: "!doctype " + dt
|
||||
});
|
||||
|
||||
const entityMatcher = /<!ENTITY ([^ ]+) "([^"]+)">/g;
|
||||
let result;
|
||||
while ((result = entityMatcher.exec(dt))) {
|
||||
const [, name, value] = result;
|
||||
if (!(name in parser.ENTITIES)) {
|
||||
parser.ENTITIES[name] = value;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
parser.onerror = err => {
|
||||
throw err;
|
||||
};
|
||||
parser.write(html).close();
|
||||
}
|
||||
};
|
||||
|
||||
function setChildForSax(parentImpl, node) {
|
||||
const currentDocument = (parentImpl && parentImpl._ownerDocument) || parentImpl;
|
||||
|
||||
let newNode;
|
||||
let isTemplateContents = false;
|
||||
switch (node.type) {
|
||||
case "tag":
|
||||
case "script":
|
||||
case "style":
|
||||
newNode = currentDocument._createElementWithCorrectElementInterface(node.name, node.namespace);
|
||||
newNode._prefix = node.prefix || null;
|
||||
newNode._namespaceURI = node.namespace || null;
|
||||
break;
|
||||
|
||||
case "root":
|
||||
// If we are in <template> then add all children to the parent's _templateContents; skip this virtual root node.
|
||||
if (parentImpl.tagName === "TEMPLATE" && parentImpl._namespaceURI === HTML_NS) {
|
||||
newNode = parentImpl._templateContents;
|
||||
isTemplateContents = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case "text":
|
||||
// HTML entities should already be decoded by the parser, so no need to decode them
|
||||
newNode = currentDocument.createTextNode(node.data);
|
||||
break;
|
||||
|
||||
case "cdata":
|
||||
newNode = currentDocument.createCDATASection(node.data);
|
||||
break;
|
||||
|
||||
case "comment":
|
||||
newNode = currentDocument.createComment(node.data);
|
||||
break;
|
||||
|
||||
case "directive":
|
||||
if (node.name[0] === "?" && node.name.toLowerCase() !== "?xml") {
|
||||
const data = node.data.slice(node.name.length + 1, -1);
|
||||
newNode = currentDocument.createProcessingInstruction(node.name.substring(1), data);
|
||||
} else if (node.name.toLowerCase() === "!doctype") {
|
||||
newNode = parseDocType(currentDocument, "<" + node.data + ">");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (!newNode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (node.attributes) {
|
||||
for (const a of node.attributes) {
|
||||
attributes.setAttributeValue(newNode, a.localName, a.value, a.prefix, a.namespace);
|
||||
}
|
||||
}
|
||||
|
||||
if (node.children) {
|
||||
for (let c = 0; c < node.children.length; c++) {
|
||||
setChildForSax(newNode, node.children[c]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isTemplateContents) {
|
||||
if (parentImpl._templateContents) {
|
||||
// Setting innerHTML on a <template>
|
||||
parentImpl._templateContents.appendChild(newNode);
|
||||
} else {
|
||||
parentImpl.appendChild(newNode);
|
||||
}
|
||||
}
|
||||
|
||||
return newNode;
|
||||
}
|
||||
|
||||
const HTML5_DOCTYPE = /<!doctype html>/i;
|
||||
const PUBLIC_DOCTYPE = /<!doctype\s+([^\s]+)\s+public\s+"([^"]+)"\s+"([^"]+)"/i;
|
||||
const SYSTEM_DOCTYPE = /<!doctype\s+([^\s]+)\s+system\s+"([^"]+)"/i;
|
||||
|
||||
function parseDocType(doc, html) {
|
||||
if (HTML5_DOCTYPE.test(html)) {
|
||||
return createDocumentTypeInternal(doc, "html", "", "");
|
||||
}
|
||||
|
||||
const publicPieces = PUBLIC_DOCTYPE.exec(html);
|
||||
if (publicPieces) {
|
||||
return createDocumentTypeInternal(doc, publicPieces[1], publicPieces[2], publicPieces[3]);
|
||||
}
|
||||
|
||||
const systemPieces = SYSTEM_DOCTYPE.exec(html);
|
||||
if (systemPieces) {
|
||||
return createDocumentTypeInternal(doc, systemPieces[1], "", systemPieces[2]);
|
||||
}
|
||||
|
||||
// Shouldn't get here (the parser shouldn't let us know about invalid doctypes), but our logic likely isn't
|
||||
// real-world perfect, so let's fallback.
|
||||
return createDocumentTypeInternal(doc, "html", "", "");
|
||||
}
|
||||
|
||||
function createDocumentTypeInternal(ownerDocument, name, publicId, systemId) {
|
||||
return DocumentType.createImpl([], { ownerDocument, name, publicId, systemId });
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = function (nameForErrorMessage, window) {
|
||||
if (!window) {
|
||||
// Do nothing for window-less documents.
|
||||
return;
|
||||
}
|
||||
|
||||
const error = new Error(`Not implemented: ${nameForErrorMessage}`);
|
||||
error.type = "not implemented";
|
||||
|
||||
window._virtualConsole.emit("jsdomError", error);
|
||||
};
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
"use strict";
|
||||
const DocumentType = require("../living/generated/DocumentType");
|
||||
const DocumentFragment = require("../living/generated/DocumentFragment");
|
||||
const Text = require("../living/generated/Text");
|
||||
const Comment = require("../living/generated/Comment");
|
||||
const attributes = require("../living/attributes");
|
||||
const nodeTypes = require("../living/node-type");
|
||||
const serializationAdapter = require("./parse5-adapter-serialization");
|
||||
|
||||
module.exports = class JSDOMParse5Adapter {
|
||||
constructor(documentImpl) {
|
||||
this._documentImpl = documentImpl;
|
||||
}
|
||||
|
||||
createDocument() {
|
||||
// parse5's model assumes that parse(html) will call into here to create the new Document, then return it. However,
|
||||
// jsdom's model assumes we can create a Window (and through that create an empty Document), do some other setup
|
||||
// stuff, and then parse, stuffing nodes into that Document as we go. So to adapt between these two models, we just
|
||||
// return the already-created Document when asked by parse5 to "create" a Document.
|
||||
return this._documentImpl;
|
||||
}
|
||||
|
||||
createDocumentFragment() {
|
||||
return DocumentFragment.createImpl([], { ownerDocument: this._documentImpl });
|
||||
}
|
||||
|
||||
createElement(localName, namespace, attrs) {
|
||||
const element = this._documentImpl._createElementWithCorrectElementInterface(localName, namespace);
|
||||
element._namespaceURI = namespace;
|
||||
this.adoptAttributes(element, attrs);
|
||||
|
||||
if ("_parserInserted" in element) {
|
||||
element._parserInserted = true;
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
createCommentNode(data) {
|
||||
return Comment.createImpl([], { data, ownerDocument: this._documentImpl });
|
||||
}
|
||||
|
||||
appendChild(parentNode, newNode) {
|
||||
parentNode.appendChild(newNode);
|
||||
}
|
||||
|
||||
insertBefore(parentNode, newNode, referenceNode) {
|
||||
parentNode.insertBefore(newNode, referenceNode);
|
||||
}
|
||||
|
||||
setTemplateContent(templateElement, contentFragment) {
|
||||
templateElement._templateContents = contentFragment;
|
||||
}
|
||||
|
||||
setDocumentType(document, name, publicId, systemId) {
|
||||
// parse5 sometimes gives us these as null.
|
||||
if (name === null) {
|
||||
name = "";
|
||||
}
|
||||
if (publicId === null) {
|
||||
publicId = "";
|
||||
}
|
||||
if (systemId === null) {
|
||||
systemId = "";
|
||||
}
|
||||
|
||||
const documentType = DocumentType.createImpl([], { name, publicId, systemId, ownerDocument: this._documentImpl });
|
||||
document.appendChild(documentType);
|
||||
}
|
||||
|
||||
setDocumentMode(document, mode) {
|
||||
// TODO: the rest of jsdom ignores this
|
||||
document._mode = mode;
|
||||
}
|
||||
|
||||
detachNode(node) {
|
||||
node.remove();
|
||||
}
|
||||
|
||||
insertText(parentNode, text) {
|
||||
const { lastChild } = parentNode;
|
||||
if (lastChild && lastChild.nodeType === nodeTypes.TEXT_NODE) {
|
||||
lastChild.data += text;
|
||||
} else {
|
||||
const textNode = Text.createImpl([], { data: text, ownerDocument: this._documentImpl });
|
||||
|
||||
parentNode.appendChild(textNode);
|
||||
}
|
||||
}
|
||||
|
||||
insertTextBefore(parentNode, text, referenceNode) {
|
||||
const { previousSibling } = referenceNode;
|
||||
if (previousSibling && previousSibling.nodeType === nodeTypes.TEXT_NODE) {
|
||||
previousSibling.data += text;
|
||||
} else {
|
||||
const textNode = Text.createImpl([], { data: text, ownerDocument: this._documentImpl });
|
||||
|
||||
parentNode.insertBefore(textNode, referenceNode);
|
||||
}
|
||||
}
|
||||
|
||||
adoptAttributes(element, attrs) {
|
||||
for (const attr of attrs) {
|
||||
const prefix = attr.prefix === "" ? null : attr.prefix;
|
||||
attributes.setAttributeValue(element, attr.name, attr.value, prefix, attr.namespace);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Object.assign(module.exports.prototype, serializationAdapter);
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
const idlUtils = require("../living/generated/utils");
|
||||
const nodeTypes = require("../living/node-type");
|
||||
const { domSymbolTree } = require("../living/helpers/internal-constants");
|
||||
// Serialization only requires a subset of the tree adapter interface.
|
||||
|
||||
// Tree traversing
|
||||
exports.getFirstChild = node => node.firstChild;
|
||||
|
||||
exports.getChildNodes = node => node.childNodesForSerializing || domSymbolTree.childrenToArray(node);
|
||||
|
||||
exports.getParentNode = node => node.parentNode;
|
||||
|
||||
exports.getAttrList = node => idlUtils.wrapperForImpl(node._attributes);
|
||||
|
||||
// Node data
|
||||
exports.getTagName = element => element._qualifiedName; // https://github.com/inikulin/parse5/issues/231
|
||||
|
||||
exports.getNamespaceURI = element => element.namespaceURI;
|
||||
|
||||
exports.getTextNodeContent = exports.getCommentNodeContent = node => node.data;
|
||||
|
||||
exports.getDocumentTypeNodeName = node => node.name;
|
||||
|
||||
exports.getDocumentTypeNodePublicId = node => node.publicId;
|
||||
|
||||
exports.getDocumentTypeNodeSystemId = node => node.systemId;
|
||||
|
||||
exports.getTemplateContent = templateElement => templateElement._templateContents;
|
||||
|
||||
exports.getDocumentMode = document => document._mode;
|
||||
|
||||
// Node types
|
||||
|
||||
exports.isTextNode = node => node.nodeType === nodeTypes.TEXT_NODE;
|
||||
|
||||
exports.isCommentNode = node => node.nodeType === nodeTypes.COMMENT_NODE;
|
||||
|
||||
exports.isDocumentTypeNode = node => node.nodeType === nodeTypes.DOCUMENT_TYPE_NODE;
|
||||
|
||||
exports.isElementNode = node => node.nodeType === nodeTypes.ELEMENT_NODE;
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
"use strict";
|
||||
|
||||
const MIMEType = require("whatwg-mimetype");
|
||||
const parseDataURL = require("data-urls");
|
||||
const sniffHTMLEncoding = require("html-encoding-sniffer");
|
||||
const whatwgEncoding = require("whatwg-encoding");
|
||||
const fs = require("fs");
|
||||
const request = require("request");
|
||||
const { documentBaseURLSerialized } = require("../living/helpers/document-base-url");
|
||||
const NODE_TYPE = require("../living/node-type");
|
||||
|
||||
/* eslint-disable no-restricted-modules */
|
||||
// TODO: stop using the built-in URL in favor of the spec-compliant whatwg-url package
|
||||
// This legacy usage is in the process of being purged.
|
||||
const URL = require("url");
|
||||
/* eslint-enable no-restricted-modules */
|
||||
|
||||
const IS_BROWSER = Object.prototype.toString.call(process) !== "[object process]";
|
||||
|
||||
function createResourceLoadHandler(element, resourceUrl, document, loadCallback) {
|
||||
if (loadCallback === undefined) {
|
||||
loadCallback = () => {
|
||||
// do nothing
|
||||
};
|
||||
}
|
||||
return (err, data, response) => {
|
||||
const ev = document.createEvent("HTMLEvents");
|
||||
|
||||
if (!err) {
|
||||
try {
|
||||
loadCallback.call(element, data, resourceUrl, response);
|
||||
ev.initEvent("load", false, false);
|
||||
} catch (e) {
|
||||
err = e;
|
||||
}
|
||||
}
|
||||
|
||||
if (err) {
|
||||
if (!err.isAbortError) {
|
||||
ev.initEvent("error", false, false);
|
||||
ev.error = err;
|
||||
element.dispatchEvent(ev);
|
||||
|
||||
const error = new Error(`Could not load ${element.localName}: "${resourceUrl}"`);
|
||||
error.detail = err;
|
||||
error.type = "resource loading";
|
||||
|
||||
document._defaultView._virtualConsole.emit("jsdomError", error);
|
||||
}
|
||||
} else {
|
||||
element.dispatchEvent(ev);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
exports.readFile = function (filePath, { defaultEncoding, detectMetaCharset }, callback) {
|
||||
const readableStream = fs.createReadStream(filePath);
|
||||
|
||||
let data = Buffer.alloc(0);
|
||||
|
||||
readableStream.on("error", callback);
|
||||
|
||||
readableStream.on("data", chunk => {
|
||||
data = Buffer.concat([data, chunk]);
|
||||
});
|
||||
|
||||
readableStream.on("end", () => {
|
||||
// Not passing default encoding means binary
|
||||
if (defaultEncoding) {
|
||||
const encoding = detectMetaCharset ?
|
||||
sniffHTMLEncoding(data, { defaultEncoding }) :
|
||||
whatwgEncoding.getBOMEncoding(data) || defaultEncoding;
|
||||
const decoded = whatwgEncoding.decode(data, encoding);
|
||||
callback(null, decoded, { headers: { "content-type": "text/plain;charset=" + encoding } });
|
||||
} else {
|
||||
callback(null, data);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
abort() {
|
||||
readableStream.destroy();
|
||||
const error = new Error("request canceled by user");
|
||||
error.isAbortError = true;
|
||||
callback(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
function readDataURL(dataURL, { defaultEncoding, detectMetaCharset }, callback) {
|
||||
try {
|
||||
const parsed = parseDataURL(dataURL);
|
||||
// If default encoding does not exist, pass on binary data.
|
||||
if (defaultEncoding) {
|
||||
const sniffOptions = {
|
||||
transportLayerEncodingLabel: parsed.mimeType.parameters.get("charset"),
|
||||
defaultEncoding
|
||||
};
|
||||
|
||||
const encoding = detectMetaCharset ?
|
||||
sniffHTMLEncoding(parsed.body, sniffOptions) :
|
||||
whatwgEncoding.getBOMEncoding(parsed.body) ||
|
||||
whatwgEncoding.labelToName(parsed.mimeType.parameters.get("charset")) ||
|
||||
defaultEncoding;
|
||||
const decoded = whatwgEncoding.decode(parsed.body, encoding);
|
||||
|
||||
parsed.mimeType.parameters.set("charset", encoding);
|
||||
|
||||
callback(null, decoded, { headers: { "content-type": parsed.mimeType.toString() } });
|
||||
} else {
|
||||
callback(null, parsed.body, { headers: { "content-type": parsed.mimeType.toString() } });
|
||||
}
|
||||
} catch (err) {
|
||||
callback(err, null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// NOTE: request wraps tough-cookie cookie jar
|
||||
// (see: https://github.com/request/request/blob/master/lib/cookies.js).
|
||||
// Therefore, to pass our cookie jar to the request, we need to create
|
||||
// request's wrapper and monkey patch it with our jar.
|
||||
exports.wrapCookieJarForRequest = cookieJar => {
|
||||
const jarWrapper = request.jar();
|
||||
jarWrapper._jar = cookieJar;
|
||||
return jarWrapper;
|
||||
};
|
||||
|
||||
function fetch(urlObj, options, callback) {
|
||||
if (urlObj.protocol === "data:") {
|
||||
return readDataURL(urlObj.href, options, callback);
|
||||
} else if (urlObj.hostname) {
|
||||
return exports.download(urlObj, options, callback);
|
||||
}
|
||||
const filePath = urlObj.pathname
|
||||
.replace(/^file:\/\//, "")
|
||||
.replace(/^\/([a-z]):\//i, "$1:/")
|
||||
.replace(/%20/g, " ");
|
||||
return exports.readFile(filePath, options, callback);
|
||||
}
|
||||
|
||||
exports.enqueue = function (element, resourceUrl, callback) {
|
||||
const document = element.nodeType === NODE_TYPE.DOCUMENT_NODE ? element : element._ownerDocument;
|
||||
|
||||
if (document._queue) {
|
||||
const loadHandler = createResourceLoadHandler(element, resourceUrl || document.URL, document, callback);
|
||||
return document._queue.push(loadHandler);
|
||||
}
|
||||
|
||||
return () => {
|
||||
// do nothing in queue-less documents
|
||||
};
|
||||
};
|
||||
|
||||
exports.download = function (url, options, callback) {
|
||||
const requestOptions = {
|
||||
pool: options.pool,
|
||||
agent: options.agent,
|
||||
agentOptions: options.agentOptions,
|
||||
agentClass: options.agentClass,
|
||||
strictSSL: options.strictSSL,
|
||||
gzip: true,
|
||||
jar: exports.wrapCookieJarForRequest(options.cookieJar),
|
||||
encoding: null,
|
||||
headers: {
|
||||
"User-Agent": options.userAgent,
|
||||
"Accept-Language": "en",
|
||||
Accept: options.accept || "*/*"
|
||||
}
|
||||
};
|
||||
if (options.referrer && !IS_BROWSER) {
|
||||
requestOptions.headers.referer = options.referrer;
|
||||
}
|
||||
if (options.proxy) {
|
||||
requestOptions.proxy = options.proxy;
|
||||
}
|
||||
Object.assign(requestOptions.headers, options.headers);
|
||||
|
||||
const { defaultEncoding, detectMetaCharset } = options;
|
||||
|
||||
const req = request(url, requestOptions, (error, response, bufferData) => {
|
||||
if (!error) {
|
||||
// If default encoding does not exist, pass on binary data.
|
||||
if (defaultEncoding) {
|
||||
const contentType = MIMEType.parse(response.headers["content-type"]) || new MIMEType("text/plain");
|
||||
const sniffOptions = {
|
||||
transportLayerEncodingLabel: contentType.parameters.get("charset"),
|
||||
defaultEncoding
|
||||
};
|
||||
|
||||
const encoding = detectMetaCharset ?
|
||||
sniffHTMLEncoding(bufferData, sniffOptions) :
|
||||
whatwgEncoding.getBOMEncoding(bufferData) ||
|
||||
whatwgEncoding.labelToName(contentType.parameters.get("charset")) ||
|
||||
defaultEncoding;
|
||||
const decoded = whatwgEncoding.decode(bufferData, encoding);
|
||||
|
||||
contentType.parameters.set("charset", encoding);
|
||||
response.headers["content-type"] = contentType.toString();
|
||||
|
||||
callback(null, decoded, response);
|
||||
} else {
|
||||
callback(null, bufferData, response);
|
||||
}
|
||||
} else {
|
||||
callback(error, null, response);
|
||||
}
|
||||
});
|
||||
return {
|
||||
abort() {
|
||||
req.abort();
|
||||
const error = new Error("request canceled by user");
|
||||
error.isAbortError = true;
|
||||
callback(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
exports.load = function (element, urlString, options, callback) {
|
||||
const document = element._ownerDocument;
|
||||
const documentImpl = document.implementation;
|
||||
|
||||
if (!documentImpl._hasFeature("FetchExternalResources", element.tagName.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (documentImpl._hasFeature("SkipExternalResources", urlString)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const urlObj = URL.parse(urlString);
|
||||
const enqueued = exports.enqueue(element, urlString, callback);
|
||||
const customLoader = document._customResourceLoader;
|
||||
const requestManager = document._requestManager;
|
||||
const cookieJar = document._cookieJar;
|
||||
|
||||
options.accept = element._accept;
|
||||
options.cookieJar = cookieJar;
|
||||
options.referrer = document.URL;
|
||||
options.pool = document._pool;
|
||||
options.agentOptions = document._agentOptions;
|
||||
options.strictSSL = document._strictSSL;
|
||||
options.proxy = document._proxy;
|
||||
options.userAgent = document._defaultView.navigator.userAgent;
|
||||
|
||||
let req = null;
|
||||
function wrappedEnqueued() {
|
||||
if (req && requestManager) {
|
||||
requestManager.remove(req);
|
||||
}
|
||||
// do not trigger if the window is closed
|
||||
if (element._ownerDocument && element._ownerDocument.defaultView.document) {
|
||||
enqueued.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
if (typeof customLoader === "function") {
|
||||
req = customLoader(
|
||||
{
|
||||
element,
|
||||
url: urlObj,
|
||||
cookie: cookieJar.getCookieStringSync(urlObj, { http: true }),
|
||||
baseUrl: documentBaseURLSerialized(document),
|
||||
defaultFetch(fetchCallback) {
|
||||
return fetch(urlObj, options, fetchCallback);
|
||||
}
|
||||
},
|
||||
wrappedEnqueued
|
||||
);
|
||||
} else {
|
||||
req = fetch(urlObj, options, wrappedEnqueued);
|
||||
}
|
||||
if (req && requestManager) {
|
||||
requestManager.add(req);
|
||||
}
|
||||
};
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
"use strict";
|
||||
const cssom = require("cssom");
|
||||
const cssstyle = require("cssstyle");
|
||||
|
||||
// http://dev.w3.org/csswg/cssom/#stylesheetlist
|
||||
// TODO: implement using webidl2js
|
||||
function StyleSheetList() {}
|
||||
|
||||
Object.setPrototypeOf(StyleSheetList.prototype, Array.prototype);
|
||||
|
||||
StyleSheetList.prototype.item = function item(i) {
|
||||
return Object.prototype.hasOwnProperty.call(this, i) ? this[i] : null;
|
||||
};
|
||||
|
||||
exports.StyleSheetList = StyleSheetList;
|
||||
|
||||
exports.addToCore = core => {
|
||||
// What works now:
|
||||
// - Accessing the rules defined in individual stylesheets
|
||||
// - Modifications to style content attribute are reflected in style property
|
||||
// - Modifications to style property are reflected in style content attribute
|
||||
// TODO
|
||||
// - Modifications to style element's textContent are reflected in sheet property.
|
||||
// - Modifications to style element's sheet property are reflected in textContent.
|
||||
// - Modifications to link.href property are reflected in sheet property.
|
||||
// - Less-used features of link: disabled
|
||||
// - Less-used features of style: disabled, scoped, title
|
||||
// - CSSOM-View
|
||||
// - getComputedStyle(): requires default stylesheet, cascading, inheritance,
|
||||
// filtering by @media (screen? print?), layout for widths/heights
|
||||
// - Load events are not in the specs, but apparently some browsers
|
||||
// implement something. Should onload only fire after all @imports have been
|
||||
// loaded, or only the primary sheet?
|
||||
|
||||
core.StyleSheet = cssom.StyleSheet;
|
||||
core.MediaList = cssom.MediaList;
|
||||
core.CSSStyleSheet = cssom.CSSStyleSheet;
|
||||
core.CSSRule = cssom.CSSRule;
|
||||
core.CSSStyleRule = cssom.CSSStyleRule;
|
||||
core.CSSMediaRule = cssom.CSSMediaRule;
|
||||
core.CSSImportRule = cssom.CSSImportRule;
|
||||
core.CSSStyleDeclaration = cssstyle.CSSStyleDeclaration;
|
||||
core.StyleSheetList = StyleSheetList;
|
||||
|
||||
// Relavant specs
|
||||
// http://www.w3.org/TR/DOM-Level-2-Style (2000)
|
||||
// http://www.w3.org/TR/cssom-view/ (2008)
|
||||
// http://dev.w3.org/csswg/cssom/ (2010) Meant to replace DOM Level 2 Style
|
||||
// http://www.whatwg.org/specs/web-apps/current-work/multipage/ HTML5, of course
|
||||
// http://dev.w3.org/csswg/css-style-attr/ not sure what's new here
|
||||
|
||||
// Objects that aren't in cssom library but should be:
|
||||
// CSSRuleList (cssom just uses array)
|
||||
// CSSFontFaceRule
|
||||
// CSSPageRule
|
||||
|
||||
// These rules don't really make sense to implement, so CSSOM draft makes them
|
||||
// obsolete.
|
||||
// CSSCharsetRule
|
||||
// CSSUnknownRule
|
||||
|
||||
// These objects are considered obsolete by CSSOM draft, although modern
|
||||
// browsers implement them.
|
||||
// CSSValue
|
||||
// CSSPrimitiveValue
|
||||
// CSSValueList
|
||||
// RGBColor
|
||||
// Rect
|
||||
// Counter
|
||||
};
|
||||
+1874
File diff suppressed because it is too large
Load Diff
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
|
||||
class AbortControllerImpl {
|
||||
constructor(args, privateData) {
|
||||
this.signal = privateData.AbortSignal.createImpl([]);
|
||||
}
|
||||
|
||||
abort() {
|
||||
this.signal._signalAbort();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
implementation: AbortControllerImpl
|
||||
};
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
"use strict";
|
||||
|
||||
const { setupForSimpleEventAccessors } = require("../helpers/create-event-accessor");
|
||||
const EventTargetImpl = require("../events/EventTarget-impl").implementation;
|
||||
|
||||
const Event = require("../generated/Event");
|
||||
|
||||
class AbortSignalImpl extends EventTargetImpl {
|
||||
constructor(args, privateData) {
|
||||
super();
|
||||
|
||||
// make event firing possible
|
||||
this._ownerDocument = privateData.window.document;
|
||||
|
||||
this.aborted = false;
|
||||
this.abortAlgorithms = new Set();
|
||||
}
|
||||
|
||||
_signalAbort() {
|
||||
if (this.aborted) {
|
||||
return;
|
||||
}
|
||||
this.aborted = true;
|
||||
|
||||
for (const algorithm of this.abortAlgorithms) {
|
||||
algorithm();
|
||||
}
|
||||
this.abortAlgorithms.clear();
|
||||
|
||||
this._dispatch(Event.createImpl(
|
||||
[
|
||||
"abort",
|
||||
{ bubbles: false, cancelable: false }
|
||||
],
|
||||
{ isTrusted: true }
|
||||
));
|
||||
}
|
||||
|
||||
_addAlgorithm(algorithm) {
|
||||
if (this.aborted) {
|
||||
return;
|
||||
}
|
||||
this.abortAlgorithms.add(algorithm);
|
||||
}
|
||||
|
||||
_removeAlgorithm(algorithm) {
|
||||
this.abortAlgorithms.delete(algorithm);
|
||||
}
|
||||
}
|
||||
|
||||
setupForSimpleEventAccessors(AbortSignalImpl.prototype, ["abort"]);
|
||||
|
||||
module.exports = {
|
||||
implementation: AbortSignalImpl
|
||||
};
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
"use strict";
|
||||
const DOMException = require("domexception");
|
||||
const attrGenerated = require("./generated/Attr");
|
||||
const { asciiLowercase } = require("./helpers/strings");
|
||||
const { HTML_NS } = require("./helpers/namespaces");
|
||||
|
||||
// The following three are for https://dom.spec.whatwg.org/#concept-element-attribute-has. We don't just have a
|
||||
// predicate tester since removing that kind of flexibility gives us the potential for better future optimizations.
|
||||
|
||||
exports.hasAttribute = function (element, A) {
|
||||
return element._attributeList.includes(A);
|
||||
};
|
||||
|
||||
exports.hasAttributeByName = function (element, name) {
|
||||
return element._attributesByNameMap.has(name);
|
||||
};
|
||||
|
||||
exports.hasAttributeByNameNS = function (element, namespace, localName) {
|
||||
return element._attributeList.some(attribute => {
|
||||
return attribute._localName === localName && attribute._namespace === namespace;
|
||||
});
|
||||
};
|
||||
|
||||
exports.changeAttribute = function (element, attribute, value) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-change
|
||||
|
||||
const oldValue = attribute._value;
|
||||
attribute._value = value;
|
||||
|
||||
// Run jsdom hooks; roughly correspond to spec's "An attribute is set and an attribute is changed."
|
||||
element._attrModified(attribute._qualifiedName, value, oldValue);
|
||||
};
|
||||
|
||||
exports.appendAttribute = function (element, attribute) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-append
|
||||
|
||||
const attributeList = element._attributeList;
|
||||
|
||||
// TODO mutation observer stuff
|
||||
|
||||
attributeList.push(attribute);
|
||||
attribute._element = element;
|
||||
|
||||
// Sync name cache
|
||||
const name = attribute._qualifiedName;
|
||||
const cache = element._attributesByNameMap;
|
||||
let entry = cache.get(name);
|
||||
if (!entry) {
|
||||
entry = [];
|
||||
cache.set(name, entry);
|
||||
}
|
||||
entry.push(attribute);
|
||||
|
||||
// Run jsdom hooks; roughly correspond to spec's "An attribute is set and an attribute is added."
|
||||
element._attrModified(name, attribute._value, null);
|
||||
};
|
||||
|
||||
exports.removeAttribute = function (element, attribute) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-remove
|
||||
|
||||
const attributeList = element._attributeList;
|
||||
|
||||
// TODO mutation observer stuff
|
||||
|
||||
for (let i = 0; i < attributeList.length; ++i) {
|
||||
if (attributeList[i] === attribute) {
|
||||
attributeList.splice(i, 1);
|
||||
attribute._element = null;
|
||||
|
||||
// Sync name cache
|
||||
const name = attribute._qualifiedName;
|
||||
const cache = element._attributesByNameMap;
|
||||
const entry = cache.get(name);
|
||||
entry.splice(entry.indexOf(attribute), 1);
|
||||
if (entry.length === 0) {
|
||||
cache.delete(name);
|
||||
}
|
||||
|
||||
// Run jsdom hooks; roughly correspond to spec's "An attribute is removed."
|
||||
element._attrModified(name, null, attribute._value);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.replaceAttribute = function (element, oldAttr, newAttr) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-replace
|
||||
|
||||
const attributeList = element._attributeList;
|
||||
|
||||
// TODO mutation observer stuff
|
||||
|
||||
for (let i = 0; i < attributeList.length; ++i) {
|
||||
if (attributeList[i] === oldAttr) {
|
||||
attributeList.splice(i, 1, newAttr);
|
||||
oldAttr._element = null;
|
||||
newAttr._element = element;
|
||||
|
||||
// Sync name cache
|
||||
const name = newAttr._qualifiedName;
|
||||
const cache = element._attributesByNameMap;
|
||||
let entry = cache.get(name);
|
||||
if (!entry) {
|
||||
entry = [];
|
||||
cache.set(name, entry);
|
||||
}
|
||||
entry.splice(entry.indexOf(oldAttr), 1, newAttr);
|
||||
|
||||
// Run jsdom hooks; roughly correspond to spec's "An attribute is set and an attribute is changed."
|
||||
element._attrModified(name, newAttr._value, oldAttr._value);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.getAttributeByName = function (element, name) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name
|
||||
|
||||
if (element._namespaceURI === HTML_NS &&
|
||||
element._ownerDocument._parsingMode === "html") {
|
||||
name = asciiLowercase(name);
|
||||
}
|
||||
|
||||
const cache = element._attributesByNameMap;
|
||||
const entry = cache.get(name);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return entry[0];
|
||||
};
|
||||
|
||||
exports.getAttributeByNameNS = function (element, namespace, localName) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace
|
||||
|
||||
if (namespace === "") {
|
||||
namespace = null;
|
||||
}
|
||||
|
||||
const attributeList = element._attributeList;
|
||||
for (let i = 0; i < attributeList.length; ++i) {
|
||||
const attr = attributeList[i];
|
||||
if (attr._namespace === namespace && attr._localName === localName) {
|
||||
return attr;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// Both of the following functions implement https://dom.spec.whatwg.org/#concept-element-attributes-get-value.
|
||||
// Separated them into two to keep symmetry with other functions.
|
||||
exports.getAttributeValue = function (element, localName) {
|
||||
const attr = exports.getAttributeByNameNS(element, null, localName);
|
||||
|
||||
if (!attr) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return attr._value;
|
||||
};
|
||||
|
||||
exports.getAttributeValueNS = function (element, namespace, localName) {
|
||||
const attr = exports.getAttributeByNameNS(element, namespace, localName);
|
||||
|
||||
if (!attr) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return attr._value;
|
||||
};
|
||||
|
||||
exports.setAttribute = function (element, attr) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-set
|
||||
|
||||
if (attr._element !== null && attr._element !== element) {
|
||||
throw new DOMException("The attribute is in use.", "InUseAttributeError");
|
||||
}
|
||||
|
||||
const oldAttr = exports.getAttributeByNameNS(element, attr._namespace, attr._localName);
|
||||
if (oldAttr === attr) {
|
||||
return attr;
|
||||
}
|
||||
|
||||
if (oldAttr !== null) {
|
||||
exports.replaceAttribute(element, oldAttr, attr);
|
||||
} else {
|
||||
exports.appendAttribute(element, attr);
|
||||
}
|
||||
|
||||
return oldAttr;
|
||||
};
|
||||
|
||||
exports.setAttributeValue = function (element, localName, value, prefix, namespace) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-set-value
|
||||
|
||||
if (prefix === undefined) {
|
||||
prefix = null;
|
||||
}
|
||||
if (namespace === undefined) {
|
||||
namespace = null;
|
||||
}
|
||||
|
||||
const attribute = exports.getAttributeByNameNS(element, namespace, localName);
|
||||
if (attribute === null) {
|
||||
const newAttribute = attrGenerated.createImpl([], { namespace, namespacePrefix: prefix, localName, value });
|
||||
exports.appendAttribute(element, newAttribute);
|
||||
return;
|
||||
}
|
||||
|
||||
exports.changeAttribute(element, attribute, value);
|
||||
};
|
||||
|
||||
exports.setAnExistingAttributeValue = (attribute, value) => {
|
||||
if (attribute._element === null) {
|
||||
attribute._value = value;
|
||||
}
|
||||
|
||||
exports.changeAttribute(attribute._element, attribute, value);
|
||||
};
|
||||
|
||||
exports.removeAttributeByName = function (element, name) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name
|
||||
|
||||
const attr = exports.getAttributeByName(element, name);
|
||||
|
||||
if (attr !== null) {
|
||||
exports.removeAttribute(element, attr);
|
||||
}
|
||||
|
||||
return attr;
|
||||
};
|
||||
|
||||
exports.removeAttributeByNameNS = function (element, namespace, localName) {
|
||||
// https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-namespace
|
||||
|
||||
const attr = exports.getAttributeByNameNS(element, namespace, localName);
|
||||
|
||||
if (attr !== null) {
|
||||
exports.removeAttribute(element, attr);
|
||||
}
|
||||
|
||||
return attr;
|
||||
};
|
||||
|
||||
exports.copyAttributeList = function (sourceElement, destElement) {
|
||||
// Needed by https://dom.spec.whatwg.org/#concept-node-clone
|
||||
|
||||
for (const sourceAttr of sourceElement._attributeList) {
|
||||
const destAttr = attrGenerated.createImpl([], {
|
||||
namespace: sourceAttr._namespace,
|
||||
namespacePrefix: sourceAttr._namespacePrefix,
|
||||
localName: sourceAttr._localName,
|
||||
value: sourceAttr._value
|
||||
});
|
||||
|
||||
exports.appendAttribute(destElement, destAttr);
|
||||
}
|
||||
};
|
||||
|
||||
exports.attributeListsEqual = function (elementA, elementB) {
|
||||
// Needed by https://dom.spec.whatwg.org/#concept-node-equals
|
||||
|
||||
const listA = elementA._attributeList;
|
||||
const listB = elementB._attributeList;
|
||||
|
||||
if (listA.length !== listB.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < listA.length; ++i) {
|
||||
const attrA = listA[i];
|
||||
|
||||
if (!listB.some(attrB => equalsA(attrB))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
function equalsA(attrB) {
|
||||
return attrA._namespace === attrB._namespace && attrA._localName === attrB._localName &&
|
||||
attrA._value === attrB._value;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
exports.attributeNames = function (element) {
|
||||
// Needed by https://dom.spec.whatwg.org/#dom-element-getattributenames
|
||||
|
||||
return element._attributeList.map(a => a._qualifiedName);
|
||||
};
|
||||
|
||||
exports.hasAttributes = function (element) {
|
||||
// Needed by https://dom.spec.whatwg.org/#dom-element-hasattributes
|
||||
|
||||
return element._attributeList.length > 0;
|
||||
};
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
"use strict";
|
||||
|
||||
const attributes = require("../attributes.js");
|
||||
|
||||
exports.implementation = class AttrImpl {
|
||||
constructor(_, privateData) {
|
||||
this._namespace = privateData.namespace !== undefined ? privateData.namespace : null;
|
||||
this._namespacePrefix = privateData.namespacePrefix !== undefined ? privateData.namespacePrefix : null;
|
||||
this._localName = privateData.localName;
|
||||
this._value = privateData.value !== undefined ? privateData.value : "";
|
||||
this._element = privateData.element !== undefined ? privateData.element : null;
|
||||
|
||||
this.specified = true;
|
||||
}
|
||||
|
||||
get namespaceURI() {
|
||||
return this._namespace;
|
||||
}
|
||||
|
||||
get prefix() {
|
||||
return this._namespacePrefix;
|
||||
}
|
||||
|
||||
get localName() {
|
||||
return this._localName;
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this._qualifiedName;
|
||||
}
|
||||
|
||||
get nodeName() {
|
||||
return this._qualifiedName;
|
||||
}
|
||||
|
||||
get value() {
|
||||
return this._value;
|
||||
}
|
||||
set value(v) {
|
||||
if (this._element === null) {
|
||||
this._value = v;
|
||||
} else {
|
||||
attributes.changeAttribute(this._element, this, v);
|
||||
}
|
||||
}
|
||||
|
||||
// Delegate to value
|
||||
get nodeValue() {
|
||||
return this.value;
|
||||
}
|
||||
set nodeValue(v) {
|
||||
this.value = v;
|
||||
}
|
||||
|
||||
// Delegate to value
|
||||
get textContent() {
|
||||
return this.value;
|
||||
}
|
||||
set textContent(v) {
|
||||
this.value = v;
|
||||
}
|
||||
|
||||
get ownerElement() {
|
||||
return this._element;
|
||||
}
|
||||
|
||||
get _qualifiedName() {
|
||||
// https://dom.spec.whatwg.org/#concept-attribute-qualified-name
|
||||
if (this._namespacePrefix === null) {
|
||||
return this._localName;
|
||||
}
|
||||
|
||||
return this._namespacePrefix + ":" + this._localName;
|
||||
}
|
||||
};
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
|
||||
const DOMException = require("domexception");
|
||||
const idlUtils = require("../generated/utils.js");
|
||||
const attributes = require("../attributes.js");
|
||||
const { HTML_NS } = require("../helpers/namespaces");
|
||||
|
||||
exports.implementation = class NamedNodeMapImpl {
|
||||
constructor(args, privateData) {
|
||||
this._element = privateData.element;
|
||||
}
|
||||
get _attributeList() {
|
||||
return this._element._attributeList;
|
||||
}
|
||||
|
||||
get [idlUtils.supportedPropertyIndices]() {
|
||||
return this._attributeList.keys();
|
||||
}
|
||||
get length() {
|
||||
return this._attributeList.length;
|
||||
}
|
||||
item(index) {
|
||||
if (index >= this._attributeList.length) {
|
||||
return null;
|
||||
}
|
||||
return this._attributeList[index];
|
||||
}
|
||||
|
||||
get [idlUtils.supportedPropertyNames]() {
|
||||
const names = new Set(this._attributeList.map(a => a._qualifiedName));
|
||||
const el = this._element;
|
||||
if (el._namespaceURI === HTML_NS && el._ownerDocument._parsingMode === "html") {
|
||||
for (const name of names) {
|
||||
const lowercaseName = name.toLowerCase();
|
||||
if (lowercaseName !== name) {
|
||||
names.delete(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
getNamedItem(qualifiedName) {
|
||||
return attributes.getAttributeByName(this._element, qualifiedName);
|
||||
}
|
||||
getNamedItemNS(namespace, localName) {
|
||||
return attributes.getAttributeByNameNS(this._element, namespace, localName);
|
||||
}
|
||||
setNamedItem(attr) {
|
||||
return attributes.setAttribute(this._element, attr);
|
||||
}
|
||||
setNamedItemNS(attr) {
|
||||
return attributes.setAttribute(this._element, attr);
|
||||
}
|
||||
removeNamedItem(qualifiedName) {
|
||||
const attr = attributes.removeAttributeByName(this._element, qualifiedName);
|
||||
if (attr === null) {
|
||||
throw new DOMException("Tried to remove an attribute that was not present", "NotFoundError");
|
||||
}
|
||||
return attr;
|
||||
}
|
||||
removeNamedItemNS(namespace, localName) {
|
||||
const attr = attributes.removeAttributeByNameNS(this._element, namespace, localName);
|
||||
if (attr === null) {
|
||||
throw new DOMException("Tried to remove an attribute that was not present", "NotFoundError");
|
||||
}
|
||||
return attr;
|
||||
}
|
||||
};
|
||||
Generated
Vendored
+73
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
|
||||
const ValidityState = require("../generated/ValidityState");
|
||||
const Event = require("../generated/Event");
|
||||
const { isDisabled } = require("../helpers/form-controls");
|
||||
const { closest } = require("../helpers/traversal");
|
||||
|
||||
exports.implementation = class DefaultConstraintValidationImpl {
|
||||
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-willvalidate
|
||||
get willValidate() {
|
||||
return this._isCandidateForConstraintValidation();
|
||||
}
|
||||
|
||||
get validity() {
|
||||
if (!this._validity) {
|
||||
this._validity = ValidityState.createImpl(this);
|
||||
}
|
||||
return this._validity;
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
|
||||
checkValidity() {
|
||||
if (!this._isCandidateForConstraintValidation()) {
|
||||
return true;
|
||||
}
|
||||
if (this._satisfiesConstraints()) {
|
||||
return true;
|
||||
}
|
||||
this.dispatchEvent(Event.createImpl(["invalid", { cancelable: true }]));
|
||||
return false;
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
|
||||
setCustomValidity(message) {
|
||||
this._customValidityErrorMessage = message;
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
|
||||
// Since jsdom has no user interaction, it's the same as #checkValidity
|
||||
reportValidity() {
|
||||
return this.checkValidity();
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-validationmessage
|
||||
get validationMessage() {
|
||||
const { validity } = this;
|
||||
if (!this._isCandidateForConstraintValidation() || this._satisfiesConstraints()) {
|
||||
return "";
|
||||
}
|
||||
const isSufferingFromCustomError = validity.customError;
|
||||
if (isSufferingFromCustomError) {
|
||||
return this._customValidityErrorMessage;
|
||||
}
|
||||
return "Constraints not satisfied";
|
||||
}
|
||||
|
||||
_isCandidateForConstraintValidation() {
|
||||
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-disabled
|
||||
return !isDisabled(this) &&
|
||||
// If an element has a datalist element ancestor,
|
||||
// it is barred from constraint validation.
|
||||
closest(this, "datalist") === null &&
|
||||
!this._barredFromConstraintValidationSpecialization();
|
||||
}
|
||||
|
||||
_isBarredFromConstraintValidation() {
|
||||
return !this._isCandidateForConstraintValidation();
|
||||
}
|
||||
|
||||
_satisfiesConstraints() {
|
||||
return this.validity.valid;
|
||||
}
|
||||
};
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
|
||||
exports.implementation = class ValidityStateImpl {
|
||||
constructor(element, state = {}) {
|
||||
this._element = element;
|
||||
this._state = state;
|
||||
}
|
||||
|
||||
get badInput() {
|
||||
return this._failsConstraint("badInput");
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-a-custom-error
|
||||
get customError() {
|
||||
return this._element._customValidityErrorMessage !== "";
|
||||
}
|
||||
|
||||
get patternMismatch() {
|
||||
return this._failsConstraint("patternMismatch");
|
||||
}
|
||||
|
||||
get rangeOverflow() {
|
||||
return this._failsConstraint("rangeOverflow");
|
||||
}
|
||||
|
||||
get rangeUnderflow() {
|
||||
return this._failsConstraint("rangeUnderflow");
|
||||
}
|
||||
|
||||
get stepMismatch() {
|
||||
return this._failsConstraint("stepMismatch");
|
||||
}
|
||||
|
||||
get tooLong() {
|
||||
return this._failsConstraint("tooLong");
|
||||
}
|
||||
|
||||
get tooShort() {
|
||||
return this._failsConstraint("tooShort");
|
||||
}
|
||||
|
||||
get typeMismatch() {
|
||||
return this._failsConstraint("typeMismatch");
|
||||
}
|
||||
|
||||
get valueMissing() {
|
||||
return this._failsConstraint("valueMissing");
|
||||
}
|
||||
|
||||
_failsConstraint(method) {
|
||||
const validationMethod = this._state[method];
|
||||
if (validationMethod) {
|
||||
return this._element.willValidate && validationMethod();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
get valid() {
|
||||
return !(this.badInput || this.valueMissing || this.customError ||
|
||||
this.patternMismatch || this.rangeOverflow || this.rangeUnderflow ||
|
||||
this.stepMismatch || this.tooLong || this.tooShort || this.typeMismatch);
|
||||
}
|
||||
};
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
const Document = require("../generated/Document");
|
||||
const { applyDocumentFeatures } = require("../../browser/documentfeatures");
|
||||
|
||||
exports.implementation = class DOMParserImpl {
|
||||
parseFromString(string, contentType) {
|
||||
switch (String(contentType)) {
|
||||
case "text/html": {
|
||||
return createScriptingDisabledDocument("html", contentType, string);
|
||||
}
|
||||
|
||||
case "text/xml":
|
||||
case "application/xml":
|
||||
case "application/xhtml+xml":
|
||||
case "image/svg+xml": {
|
||||
// TODO: use a strict XML parser (sax's strict mode might work?) and create parsererror elements
|
||||
try {
|
||||
return createScriptingDisabledDocument("xml", contentType, string);
|
||||
} catch (error) {
|
||||
const document = createScriptingDisabledDocument("xml", contentType);
|
||||
const element = document.createElementNS("http://www.mozilla.org/newlayout/xml/parsererror.xml", "parsererror");
|
||||
|
||||
element.textContent = error.message;
|
||||
|
||||
document.appendChild(element);
|
||||
return document;
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
throw new TypeError("Invalid contentType");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function createScriptingDisabledDocument(parsingMode, contentType, string) {
|
||||
const document = Document.createImpl([], {
|
||||
options: {
|
||||
parsingMode,
|
||||
encoding: "UTF-8",
|
||||
contentType
|
||||
// TODO: somehow set URL to active document's URL
|
||||
}
|
||||
});
|
||||
|
||||
// "scripting enabled" set to false
|
||||
applyDocumentFeatures(document, {
|
||||
FetchExternalResources: [],
|
||||
SkipExternalResources: false
|
||||
});
|
||||
|
||||
if (string !== undefined) {
|
||||
document._htmlToDom.appendToDocument(string, document);
|
||||
}
|
||||
document.close();
|
||||
return document;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
|
||||
const EventImpl = require("./Event-impl").implementation;
|
||||
|
||||
const CloseEventInit = require("../generated/CloseEventInit");
|
||||
|
||||
class CloseEventImpl extends EventImpl {}
|
||||
CloseEventImpl.defaultInit = CloseEventInit.convert(undefined);
|
||||
|
||||
exports.implementation = CloseEventImpl;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
|
||||
const UIEventImpl = require("./UIEvent-impl").implementation;
|
||||
const CompositionEventInit = require("../generated/CompositionEventInit");
|
||||
|
||||
class CompositionEventImpl extends UIEventImpl {
|
||||
initCompositionEvent(type, bubbles, cancelable, view, data) {
|
||||
if (this._dispatchFlag) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.initUIEvent(type, bubbles, cancelable, view, 0);
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
CompositionEventImpl.defaultInit = CompositionEventInit.convert(undefined);
|
||||
|
||||
module.exports = {
|
||||
implementation: CompositionEventImpl
|
||||
};
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
|
||||
const EventImpl = require("./Event-impl").implementation;
|
||||
|
||||
const CustomEventInit = require("../generated/CustomEventInit");
|
||||
|
||||
class CustomEventImpl extends EventImpl {
|
||||
initCustomEvent(type, bubbles, cancelable, detail) {
|
||||
if (this._dispatchFlag) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.initEvent(type, bubbles, cancelable);
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
CustomEventImpl.defaultInit = CustomEventInit.convert(undefined);
|
||||
|
||||
module.exports = {
|
||||
implementation: CustomEventImpl
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
|
||||
const EventImpl = require("./Event-impl").implementation;
|
||||
|
||||
const ErrorEventInit = require("../generated/ErrorEventInit");
|
||||
|
||||
class ErrorEventImpl extends EventImpl {
|
||||
|
||||
}
|
||||
ErrorEventImpl.defaultInit = ErrorEventInit.convert(undefined);
|
||||
|
||||
module.exports = {
|
||||
implementation: ErrorEventImpl
|
||||
};
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
"use strict";
|
||||
|
||||
const EventInit = require("../generated/EventInit");
|
||||
|
||||
class EventImpl {
|
||||
constructor(args, privateData) {
|
||||
const [type, eventInitDict = this.constructor.defaultInit] = args;
|
||||
|
||||
this.type = type;
|
||||
|
||||
this.bubbles = false;
|
||||
this.cancelable = false;
|
||||
for (const key in eventInitDict) {
|
||||
if (key in this.constructor.defaultInit) {
|
||||
this[key] = eventInitDict[key];
|
||||
}
|
||||
}
|
||||
for (const key in this.constructor.defaultInit) {
|
||||
if (!(key in this)) {
|
||||
this[key] = this.constructor.defaultInit[key];
|
||||
}
|
||||
}
|
||||
|
||||
this.target = null;
|
||||
this.currentTarget = null;
|
||||
this.eventPhase = 0;
|
||||
|
||||
this._initializedFlag = true;
|
||||
this._stopPropagationFlag = false;
|
||||
this._stopImmediatePropagationFlag = false;
|
||||
this._canceledFlag = false;
|
||||
this._dispatchFlag = false;
|
||||
|
||||
this.isTrusted = privateData.isTrusted || false;
|
||||
this.timeStamp = Date.now();
|
||||
}
|
||||
|
||||
get srcElement() {
|
||||
return this.target;
|
||||
}
|
||||
|
||||
get returnValue() {
|
||||
return !this._canceledFlag;
|
||||
}
|
||||
|
||||
set returnValue(v) {
|
||||
if (this.cancelable && v === false) {
|
||||
this._canceledFlag = true;
|
||||
}
|
||||
}
|
||||
|
||||
get defaultPrevented() {
|
||||
return this._canceledFlag;
|
||||
}
|
||||
|
||||
stopPropagation() {
|
||||
this._stopPropagationFlag = true;
|
||||
}
|
||||
|
||||
get cancelBubble() {
|
||||
return this._stopPropagationFlag;
|
||||
}
|
||||
|
||||
set cancelBubble(v) {
|
||||
if (v) {
|
||||
this._stopPropagationFlag = true;
|
||||
}
|
||||
}
|
||||
|
||||
stopImmediatePropagation() {
|
||||
this._stopPropagationFlag = true;
|
||||
this._stopImmediatePropagationFlag = true;
|
||||
}
|
||||
|
||||
preventDefault() {
|
||||
if (this.cancelable) {
|
||||
this._canceledFlag = true;
|
||||
}
|
||||
}
|
||||
|
||||
_initialize(type, bubbles, cancelable) {
|
||||
this.type = type;
|
||||
this._initializedFlag = true;
|
||||
|
||||
this._stopPropagationFlag = false;
|
||||
this._stopImmediatePropagationFlag = false;
|
||||
this._canceledFlag = false;
|
||||
|
||||
this.isTrusted = false;
|
||||
this.target = null;
|
||||
this.bubbles = bubbles;
|
||||
this.cancelable = cancelable;
|
||||
}
|
||||
|
||||
initEvent(type, bubbles, cancelable) {
|
||||
if (this._dispatchFlag) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._initialize(type, bubbles, cancelable);
|
||||
}
|
||||
}
|
||||
EventImpl.defaultInit = EventInit.convert(undefined);
|
||||
|
||||
module.exports = {
|
||||
implementation: EventImpl
|
||||
};
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
"use strict";
|
||||
|
||||
// This mixin doesn't have an IDL equivalent, but since MouseEvent and KeyboardEvent implement getModifierState() the
|
||||
// same way, its implementation is shared here.
|
||||
|
||||
class EventModifierMixinImpl {
|
||||
// Event's constructor assumes all options correspond to IDL attributes with the same names, and sets them on `this`.
|
||||
// That is not the case for these modifier boolean options, but since the options are set on `this` anyway we'll
|
||||
// access them that way. The spec doesn't say much about the case where keyArg is not one of the valid ones
|
||||
// (https://w3c.github.io/uievents-key/#keys-modifier), but at least Chrome returns false for invalid modifiers. Since
|
||||
// these invalid modifiers will be undefined on `this` (thus `false` after casting it to boolean), we don't need to do
|
||||
// extra checking for validity.
|
||||
getModifierState(keyArg) {
|
||||
return Boolean(this[`modifier${keyArg}`]);
|
||||
}
|
||||
}
|
||||
|
||||
exports.implementation = EventModifierMixinImpl;
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
"use strict";
|
||||
const DOMException = require("domexception");
|
||||
const reportException = require("../helpers/runtime-script-errors");
|
||||
const { domSymbolTree } = require("../helpers/internal-constants");
|
||||
const idlUtils = require("../generated/utils");
|
||||
|
||||
const Event = require("../generated/Event").interface;
|
||||
|
||||
class EventTargetImpl {
|
||||
constructor() {
|
||||
this._eventListeners = Object.create(null);
|
||||
}
|
||||
|
||||
addEventListener(type, callback, options) {
|
||||
// webidl2js currently can't handle neither optional arguments nor callback interfaces
|
||||
if (callback === undefined || callback === null) {
|
||||
callback = null;
|
||||
} else if (typeof callback !== "object" && typeof callback !== "function") {
|
||||
throw new TypeError("Only undefined, null, an object, or a function are allowed for the callback parameter");
|
||||
}
|
||||
|
||||
options = normalizeEventHandlerOptions(options, ["capture", "once"]);
|
||||
|
||||
if (callback === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this._eventListeners[type]) {
|
||||
this._eventListeners[type] = [];
|
||||
}
|
||||
|
||||
for (let i = 0; i < this._eventListeners[type].length; ++i) {
|
||||
const listener = this._eventListeners[type][i];
|
||||
if (listener.options.capture === options.capture && listener.callback === callback) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this._eventListeners[type].push({
|
||||
callback,
|
||||
options
|
||||
});
|
||||
}
|
||||
|
||||
removeEventListener(type, callback, options) {
|
||||
if (callback === undefined || callback === null) {
|
||||
callback = null;
|
||||
} else if (typeof callback !== "object" && typeof callback !== "function") {
|
||||
throw new TypeError("Only undefined, null, an object, or a function are allowed for the callback parameter");
|
||||
}
|
||||
|
||||
options = normalizeEventHandlerOptions(options, ["capture"]);
|
||||
|
||||
if (callback === null) {
|
||||
// Optimization, not in the spec.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this._eventListeners[type]) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < this._eventListeners[type].length; ++i) {
|
||||
const listener = this._eventListeners[type][i];
|
||||
if (listener.callback === callback && listener.options.capture === options.capture) {
|
||||
this._eventListeners[type].splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispatchEvent(eventImpl) {
|
||||
if (eventImpl._dispatchFlag || !eventImpl._initializedFlag) {
|
||||
throw new DOMException("Tried to dispatch an uninitialized event", "InvalidStateError");
|
||||
}
|
||||
if (eventImpl.eventPhase !== Event.NONE) {
|
||||
throw new DOMException("Tried to dispatch a dispatching event", "InvalidStateError");
|
||||
}
|
||||
|
||||
eventImpl.isTrusted = false;
|
||||
|
||||
return this._dispatch(eventImpl);
|
||||
}
|
||||
|
||||
_dispatch(eventImpl, targetOverride) {
|
||||
eventImpl._dispatchFlag = true;
|
||||
eventImpl.target = targetOverride || this;
|
||||
|
||||
const eventPath = [];
|
||||
let { target } = eventImpl;
|
||||
let targetParent = domSymbolTree.parent(target);
|
||||
while (targetParent) {
|
||||
eventPath.push(targetParent);
|
||||
target = targetParent;
|
||||
targetParent = domSymbolTree.parent(targetParent);
|
||||
}
|
||||
if (eventImpl.type !== "load" && target._defaultView) {
|
||||
// https://html.spec.whatwg.org/#events-and-the-window-object
|
||||
eventPath.push(idlUtils.implForWrapper(target._defaultView));
|
||||
}
|
||||
|
||||
eventImpl.eventPhase = Event.CAPTURING_PHASE;
|
||||
for (let i = eventPath.length - 1; i >= 0; --i) {
|
||||
if (eventImpl._stopPropagationFlag) {
|
||||
break;
|
||||
}
|
||||
|
||||
const object = eventPath[i];
|
||||
const objectImpl = idlUtils.implForWrapper(object) || object; // window :(
|
||||
const eventListeners = objectImpl._eventListeners[eventImpl.type];
|
||||
invokeEventListeners(eventListeners, object, eventImpl);
|
||||
}
|
||||
|
||||
eventImpl.eventPhase = Event.AT_TARGET;
|
||||
|
||||
if (!eventImpl._stopPropagationFlag) {
|
||||
if (this._eventListeners[eventImpl.type]) {
|
||||
const eventListeners = this._eventListeners[eventImpl.type];
|
||||
invokeEventListeners(eventListeners, eventImpl.target, eventImpl);
|
||||
}
|
||||
}
|
||||
|
||||
if (eventImpl.bubbles) {
|
||||
eventImpl.eventPhase = Event.BUBBLING_PHASE;
|
||||
for (let i = 0; i < eventPath.length; ++i) {
|
||||
if (eventImpl._stopPropagationFlag) {
|
||||
break;
|
||||
}
|
||||
|
||||
const object = eventPath[i];
|
||||
const objectImpl = idlUtils.implForWrapper(object) || object; // window :(
|
||||
const eventListeners = objectImpl._eventListeners[eventImpl.type];
|
||||
invokeEventListeners(eventListeners, object, eventImpl);
|
||||
}
|
||||
}
|
||||
|
||||
eventImpl._dispatchFlag = false;
|
||||
eventImpl._stopPropagationFlag = false;
|
||||
eventImpl._stopImmediatePropagationFlag = false;
|
||||
eventImpl.eventPhase = Event.NONE;
|
||||
eventImpl.currentTarget = null;
|
||||
return !eventImpl._canceledFlag;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
implementation: EventTargetImpl
|
||||
};
|
||||
|
||||
function invokeEventListeners(listeners, target, eventImpl) {
|
||||
const wrapper = idlUtils.wrapperForImpl(target);
|
||||
const document = target._ownerDocument || (wrapper && (wrapper._document || wrapper._ownerDocument));
|
||||
// Will be falsy for windows that have closed
|
||||
if (!document) {
|
||||
return;
|
||||
}
|
||||
|
||||
// workaround for events emitted on window (window-proxy)
|
||||
// the wrapper is the root window instance, but we only want to expose the vm proxy at all times
|
||||
if (wrapper._document && wrapper.constructor.name === "Window") {
|
||||
target = idlUtils.implForWrapper(wrapper._document)._defaultView;
|
||||
}
|
||||
eventImpl.currentTarget = target;
|
||||
if (!listeners) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handlers = listeners.slice();
|
||||
for (let i = 0; i < handlers.length; ++i) {
|
||||
if (eventImpl._stopImmediatePropagationFlag) {
|
||||
return;
|
||||
}
|
||||
|
||||
const listener = handlers[i];
|
||||
const { capture, once/* , passive */ } = listener.options;
|
||||
|
||||
if (listeners.indexOf(listener) === -1 ||
|
||||
(eventImpl.eventPhase === Event.CAPTURING_PHASE && !capture) ||
|
||||
(eventImpl.eventPhase === Event.BUBBLING_PHASE && capture)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (once) {
|
||||
listeners.splice(listeners.indexOf(listener), 1);
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof listener.callback === "object") {
|
||||
if (typeof listener.callback.handleEvent === "function") {
|
||||
listener.callback.handleEvent(idlUtils.wrapperForImpl(eventImpl));
|
||||
}
|
||||
} else {
|
||||
listener.callback.call(idlUtils.wrapperForImpl(eventImpl.currentTarget), idlUtils.wrapperForImpl(eventImpl));
|
||||
}
|
||||
} catch (e) {
|
||||
let window = null;
|
||||
if (wrapper && wrapper._document) {
|
||||
// Triggered by Window
|
||||
window = wrapper;
|
||||
} else if (target._ownerDocument) {
|
||||
// Triggered by most webidl2js'ed instances
|
||||
window = target._ownerDocument._defaultView;
|
||||
} else if (wrapper._ownerDocument) {
|
||||
// Currently triggered by XHR and some other non-webidl2js things
|
||||
window = wrapper._ownerDocument._defaultView;
|
||||
}
|
||||
|
||||
if (window) {
|
||||
reportException(window, e);
|
||||
}
|
||||
// Errors in window-less documents just get swallowed... can you think of anything better?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the event listeners options argument in order to get always a valid options object
|
||||
* @param {Object} options - user defined options
|
||||
* @param {Array} defaultBoolKeys - boolean properties that should belong to the options object
|
||||
* @returns {Object} object containing at least the "defaultBoolKeys"
|
||||
*/
|
||||
function normalizeEventHandlerOptions(options, defaultBoolKeys) {
|
||||
const returnValue = {};
|
||||
|
||||
// no need to go further here
|
||||
if (typeof options === "boolean" || options === null || typeof options === "undefined") {
|
||||
returnValue.capture = Boolean(options);
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
// non objects options so we typecast its value as "capture" value
|
||||
if (typeof options !== "object") {
|
||||
returnValue.capture = Boolean(options);
|
||||
// at this point we don't need to loop the "capture" key anymore
|
||||
defaultBoolKeys = defaultBoolKeys.filter(k => k !== "capture");
|
||||
}
|
||||
|
||||
for (const key of defaultBoolKeys) {
|
||||
returnValue[key] = Boolean(options[key]);
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
const UIEventImpl = require("./UIEvent-impl").implementation;
|
||||
|
||||
const FocusEventInit = require("../generated/FocusEventInit");
|
||||
|
||||
class FocusEventImpl extends UIEventImpl {}
|
||||
FocusEventImpl.defaultInit = FocusEventInit.convert(undefined);
|
||||
|
||||
exports.implementation = FocusEventImpl;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
|
||||
const EventImpl = require("./Event-impl").implementation;
|
||||
|
||||
const HashChangeEventInit = require("../generated/HashChangeEventInit");
|
||||
|
||||
class HashChangeEventImpl extends EventImpl {
|
||||
|
||||
}
|
||||
HashChangeEventImpl.defaultInit = HashChangeEventInit.convert(undefined);
|
||||
|
||||
module.exports = {
|
||||
implementation: HashChangeEventImpl
|
||||
};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
|
||||
const { mixin } = require("../../utils");
|
||||
const EventModifierMixinImpl = require("./EventModifierMixin-impl").implementation;
|
||||
const UIEventImpl = require("./UIEvent-impl").implementation;
|
||||
|
||||
const KeyboardEventInit = require("../generated/KeyboardEventInit");
|
||||
|
||||
class KeyboardEventImpl extends UIEventImpl {
|
||||
initKeyboardEvent(type, bubbles, cancelable, view, key, location, ctrlKey, altKey, shiftKey, metaKey) {
|
||||
if (this._dispatchFlag) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.initUIEvent(type, bubbles, cancelable, view, 0);
|
||||
this.key = key;
|
||||
this.location = location;
|
||||
this.ctrlKey = ctrlKey;
|
||||
this.altKey = altKey;
|
||||
this.shiftKey = shiftKey;
|
||||
this.metaKey = metaKey;
|
||||
}
|
||||
}
|
||||
mixin(KeyboardEventImpl.prototype, EventModifierMixinImpl.prototype);
|
||||
KeyboardEventImpl.defaultInit = KeyboardEventInit.convert(undefined);
|
||||
|
||||
module.exports = {
|
||||
implementation: KeyboardEventImpl
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user