From b581a1a0b27eccc7dc790061aec4e2c8f8b9e365 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Sat, 31 Aug 2024 07:14:47 +0200 Subject: [PATCH 01/13] fix: sync conventions and error types and export enum DOMExceptionName --- examples/typescript-node-es6/src/index.ts | 42 ++++ index.d.ts | 254 ++++++++++++++++++---- lib/errors.js | 4 +- lib/index.js | 3 +- 4 files changed, 263 insertions(+), 40 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index 31a28b42e..69c79588c 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -1,10 +1,52 @@ import { DOMParser, + hasDefaultHTMLNamespace, + isHTMLMimeType, + isValidMimeType, MIME_TYPE, + NAMESPACE, onWarningStopParsing, XMLSerializer, + DOMImplementation, + DOMException, + DOMExceptionName, + ExceptionCode, + ParseError, } from '@xmldom/xmldom'; +isHTMLMimeType(MIME_TYPE.HTML); +hasDefaultHTMLNamespace(MIME_TYPE.XML_XHTML_APPLICATION); +isValidMimeType(MIME_TYPE.XML_SVG_IMAGE); +isValidMimeType(MIME_TYPE.XML_APPLICATION); + +const impl = new DOMImplementation(); +impl.createDocument(null, 'qualifiedName'); +impl.createDocument( + NAMESPACE.XML, + 'qualifiedName', + impl.createDocumentType('qualifiedName') +); +impl.createDocumentType('qualifiedName', 'publicId', 'systemId'); +impl.createDocumentType('qualifiedName', 'publicId'); +impl.createHTMLDocument(); +impl.createHTMLDocument(false); +impl.createHTMLDocument('title'); + +const domException = new DOMException(); +domException.code; // 0 +domException.name; // "Error" +domException.message; // "" +domException.INDEX_SIZE_ERR; +new DOMException('message', DOMExceptionName.SyntaxError); +new DOMException(DOMException.DATA_CLONE_ERR); +new DOMException(ExceptionCode.INDEX_SIZE_ERR, 'message'); + +const parseError = new ParseError('message'); +parseError.message; +parseError.cause; +parseError.locator; +new ParseError('message', {}, domException); + const source = ` test diff --git a/index.d.ts b/index.d.ts index 922eb989e..ab280d70f 100644 --- a/index.d.ts +++ b/index.d.ts @@ -12,6 +12,17 @@ declare module '@xmldom/xmldom' { * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign */ function assign(target: T, source: S): T & S; + /** + * For both the `text/html` and the `application/xhtml+xml` namespace the spec defines that the + * HTML namespace is provided as the default. + * + * @param {string} mimeType + * @returns {boolean} + * @see https://dom.spec.whatwg.org/#dom-document-createelement + * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument + * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument + */ + function hasDefaultHTMLNamespace(mimeType: string): mimeType is MIME_TYPE.HTML | MIME_TYPE.XML_XHTML_APPLICATION; /** * Only returns true if `value` matches MIME_TYPE.HTML, which indicates an HTML document. * @@ -114,28 +125,206 @@ declare module '@xmldom/xmldom' { */ XMLNS = 'http://www.w3.org/2000/xmlns/', } - - /** - * A custom error that will not be caught by XMLReader aka the SAX parser. - */ - class ParseError extends Error { - constructor(message: string, locator?: any); - } // END ./lib/conventions.js - // START ./lib/dom.js + // START ./lib/errors.js + enum DOMExceptionName { + /** + * the default value as defined by the spec + */ + Error = 'Error', + /** + * @deprecated + * Use RangeError instead. + */ + IndexSizeError = 'IndexSizeError', + /** + * @deprecated + * Just to match the related static code, not part of the spec. + */ + DomstringSizeError = 'DomstringSizeError', + HierarchyRequestError = 'HierarchyRequestError', + WrongDocumentError = 'WrongDocumentError', + InvalidCharacterError = 'InvalidCharacterError', + /** + * @deprecated + * Just to match the related static code, not part of the spec. + */ + NoDataAllowedError = 'NoDataAllowedError', + NoModificationAllowedError = 'NoModificationAllowedError', + NotFoundError = 'NotFoundError', + NotSupportedError = 'NotSupportedError', + InUseAttributeError = 'InUseAttributeError', + InvalidStateError = 'InvalidStateError', + SyntaxError = 'SyntaxError', + InvalidModificationError = 'InvalidModificationError', + NamespaceError = 'NamespaceError', + /** + * @deprecated + * Use TypeError for invalid arguments, + * "NotSupportedError" DOMException for unsupported operations, + * and "NotAllowedError" DOMException for denied requests instead. + */ + InvalidAccessError = 'InvalidAccessError', + /** + * @deprecated + * Just to match the related static code, not part of the spec. + */ + ValidationError = 'ValidationError', + /** + * @deprecated + * Use TypeError instead. + */ + TypeMismatchError = 'TypeMismatchError', + SecurityError = 'SecurityError', + NetworkError = 'NetworkError', + AbortError = 'AbortError', + /** + * @deprecated + * Just to match the related static code, not part of the spec. + */ + URLMismatchError = 'URLMismatchError', + QuotaExceededError = 'QuotaExceededError', + TimeoutError = 'TimeoutError', + InvalidNodeTypeError = 'InvalidNodeTypeError', + DataCloneError = 'DataCloneError', + EncodingError = 'EncodingError', + NotReadableError = 'NotReadableError', + UnknownError = 'UnknownError', + ConstraintError = 'ConstraintError', + DataError = 'DataError', + TransactionInactiveError = 'TransactionInactiveError', + ReadOnlyError = 'ReadOnlyError', + VersionError = 'VersionError', + OperationError = 'OperationError', + NotAllowedError = 'NotAllowedError', + OptOutError = 'OptOutError', +} + enum ExceptionCode { + INDEX_SIZE_ERR = 1, + DOMSTRING_SIZE_ERR = 2, + HIERARCHY_REQUEST_ERR = 3, + WRONG_DOCUMENT_ERR = 4, + INVALID_CHARACTER_ERR = 5, + NO_DATA_ALLOWED_ERR = 6, + NO_MODIFICATION_ALLOWED_ERR = 7, + NOT_FOUND_ERR = 8, + NOT_SUPPORTED_ERR = 9, + INUSE_ATTRIBUTE_ERR = 10, + INVALID_STATE_ERR = 11, + SYNTAX_ERR = 12, + INVALID_MODIFICATION_ERR = 13, + NAMESPACE_ERR = 14, + INVALID_ACCESS_ERR = 15, + VALIDATION_ERR = 16, + TYPE_MISMATCH_ERR = 17, + SECURITY_ERR = 18, + NETWORK_ERR = 19, + ABORT_ERR = 20, + URL_MISMATCH_ERR = 21, + QUOTA_EXCEEDED_ERR = 22, + TIMEOUT_ERR = 23, + INVALID_NODE_TYPE_ERR = 24, + DATA_CLONE_ERR = 25, + }; /** - * The error class for errors reported by the DOM API. + * DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation + * is impossible to perform (either for logical reasons, because data is lost, or because the + * implementation has become unstable). In general, DOM methods return specific error values in + * ordinary processing situations, such as out-of-bound errors when using NodeList. + * + * Implementations should raise other exceptions under other circumstances. For example, + * implementations should raise an implementation-dependent exception if a null argument is + * passed when null was not expected. * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException + * This implementation supports the following usages: + * 1. according to the living standard (both arguments are optional): + * ``` + * new DOMException("message (can be empty)", DOMExceptionNames.HierarchyRequestError) + * ``` + * 2. according to previous xmldom implementation (only the first argument is required): + * ``` + * new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "optional message") + * ``` + * both result in the proper name being set. + * + * @see https://webidl.spec.whatwg.org/#idl-DOMException + * @see https://webidl.spec.whatwg.org/#dfn-error-names-table + * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-17189187 * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html */ class DOMException extends Error { - constructor(code: number, message: string); + constructor(message?: string, name?: DOMExceptionName | string); + constructor(code?: ExceptionCode, message?: string); + readonly name: DOMExceptionName; + readonly code: ExceptionCode | 0; + static readonly INDEX_SIZE_ERR: 1; + static readonly DOMSTRING_SIZE_ERR: 2; + static readonly HIERARCHY_REQUEST_ERR: 3; + static readonly WRONG_DOCUMENT_ERR: 4; + static readonly INVALID_CHARACTER_ERR: 5; + static readonly NO_DATA_ALLOWED_ERR: 6; + static readonly NO_MODIFICATION_ALLOWED_ERR: 7; + static readonly NOT_FOUND_ERR: 8; + static readonly NOT_SUPPORTED_ERR: 9; + static readonly INUSE_ATTRIBUTE_ERR: 10; + static readonly INVALID_STATE_ERR: 11; + static readonly SYNTAX_ERR: 12; + static readonly INVALID_MODIFICATION_ERR: 13; + static readonly NAMESPACE_ERR: 14; + static readonly INVALID_ACCESS_ERR: 15; + static readonly VALIDATION_ERR: 16; + static readonly TYPE_MISMATCH_ERR: 17; + static readonly SECURITY_ERR: 18; + static readonly NETWORK_ERR: 19; + static readonly ABORT_ERR: 20; + static readonly URL_MISMATCH_ERR: 21; + static readonly QUOTA_EXCEEDED_ERR: 22; + static readonly TIMEOUT_ERR: 23; + static readonly INVALID_NODE_TYPE_ERR: 24; + static readonly DATA_CLONE_ERR: 25; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; } - interface DOMImplementation { + /** + * Creates an error that will not be caught by XMLReader aka the SAX parser. + */ + class ParseError extends Error { + constructor(message: string, locator?: any, cause?: Error); + readonly message: string; + readonly locator?: any; + readonly cause?: Error; + } + // END ./lib/errors.js + + // START ./lib/dom.js + + class DOMImplementation { /** * The DOMImplementation interface represents an object providing methods which are not * dependent on any particular document. @@ -151,7 +340,7 @@ declare module '@xmldom/xmldom' { * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard */ - new (): DOMImplementation; + constructor(); /** * Creates an XML Document object of the specified type with its document element. @@ -226,15 +415,23 @@ declare module '@xmldom/xmldom' { hasFeature(feature: string, version?: string): true; } - var XMLSerializer: XMLSerializerStatic; - interface XMLSerializerStatic { - new (): XMLSerializer; + class XMLSerializer { + serializeToString(node: Node, nodeFilter?: (node: Node) => boolean): string; } // END ./lib/dom.js // START ./lib/dom-parser.js - var DOMParser: DOMParserStatic; - interface DOMParserStatic { + /** + * The DOMParser interface provides the ability to parse XML or HTML source code from a string + * into a DOM `Document`. + * + * _xmldom is different from the spec in that it allows an `options` parameter, + * to control the behavior._. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization + */ + class DOMParser { /** * The DOMParser interface provides the ability to parse XML or HTML source code from a * string into a DOM `Document`. @@ -247,20 +444,7 @@ declare module '@xmldom/xmldom' { * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization */ - new (options?: DOMParserOptions): DOMParser; - } - - /** - * The DOMParser interface provides the ability to parse XML or HTML source code from a string - * into a DOM `Document`. - * - * _xmldom is different from the spec in that it allows an `options` parameter, - * to control the behavior._. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization - */ - interface DOMParser { + constructor(options?: DOMParserOptions); /** * Parses `source` using the options in the way configured by the `DOMParserOptions` of * `this` @@ -288,17 +472,13 @@ declare module '@xmldom/xmldom' { ): Document; } - interface XMLSerializer { - serializeToString(node: Node, nodeFilter?: (node: Node) => boolean): string; - } - interface DOMParserOptions { /** * The method to use instead of `Object.assign` (defaults to `conventions.assign`), * which is used to copy values from the options before they are used for parsing. * * @private - * @see {@link conventions.assign} + * @see {@link assign} */ readonly assign?: typeof Object.assign; /** diff --git a/lib/errors.js b/lib/errors.js index f614889e8..b802f45be 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -100,7 +100,7 @@ function endsWithError(value) { * passed when null was not expected. * * This implementation supports the following usages: - * 1. according to the living standard (both arguments are mandatory): + * 1. according to the living standard (both arguments are optional): * ``` * new DOMException("message (can be empty)", DOMExceptionNames.HierarchyRequestError) * ``` @@ -202,5 +202,5 @@ extendError(ParseError); exports.DOMException = DOMException; exports.DOMExceptionName = DOMExceptionName; -exports.ParseError = ParseError; exports.ExceptionCode = ExceptionCode; +exports.ParseError = ParseError; diff --git a/lib/index.js b/lib/index.js index 992bfa4f1..d4330e1c1 100644 --- a/lib/index.js +++ b/lib/index.js @@ -8,9 +8,10 @@ exports.MIME_TYPE = conventions.MIME_TYPE; exports.NAMESPACE = conventions.NAMESPACE; var errors = require('./errors'); -exports.ParseError = errors.ParseError; exports.DOMException = errors.DOMException; +exports.DOMExceptionName = errors.DOMExceptionName; exports.ExceptionCode = errors.ExceptionCode; +exports.ParseError = errors.ParseError; var dom = require('./dom'); exports.DOMImplementation = dom.DOMImplementation; From af5a5b54131820c24f3b3527ca86b9a9662df0a2 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Sat, 31 Aug 2024 08:45:14 +0200 Subject: [PATCH 02/13] fix: Add Node, Document and DocumentType types and drop Element methods from Node prototype --- examples/typescript-node-es6/src/index.ts | 56 ++-- index.d.ts | 357 ++++++++++++++++++++++ lib/dom.js | 26 +- lib/index.js | 2 +- 4 files changed, 404 insertions(+), 37 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index 69c79588c..a42e61cb8 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -1,36 +1,28 @@ import { + Document, + DOMImplementation, + DOMException, + DOMExceptionName, DOMParser, + ExceptionCode, hasDefaultHTMLNamespace, isHTMLMimeType, isValidMimeType, MIME_TYPE, NAMESPACE, onWarningStopParsing, - XMLSerializer, - DOMImplementation, - DOMException, - DOMExceptionName, - ExceptionCode, ParseError, -} from '@xmldom/xmldom'; + XMLSerializer, Node, DocumentType +} from "@xmldom/xmldom"; + +// lib/conventions isHTMLMimeType(MIME_TYPE.HTML); hasDefaultHTMLNamespace(MIME_TYPE.XML_XHTML_APPLICATION); isValidMimeType(MIME_TYPE.XML_SVG_IMAGE); isValidMimeType(MIME_TYPE.XML_APPLICATION); -const impl = new DOMImplementation(); -impl.createDocument(null, 'qualifiedName'); -impl.createDocument( - NAMESPACE.XML, - 'qualifiedName', - impl.createDocumentType('qualifiedName') -); -impl.createDocumentType('qualifiedName', 'publicId', 'systemId'); -impl.createDocumentType('qualifiedName', 'publicId'); -impl.createHTMLDocument(); -impl.createHTMLDocument(false); -impl.createHTMLDocument('title'); +// lib/errors const domException = new DOMException(); domException.code; // 0 @@ -47,6 +39,34 @@ parseError.cause; parseError.locator; new ParseError('message', {}, domException); +// lib/dom +Node.ATTRIBUTE_NODE +Node.DOCUMENT_POSITION_CONTAINS + + +const impl = new DOMImplementation(); +const document = impl.createDocument(null, 'qualifiedName'); +document.contentType; +document.type; +document.ATTRIBUTE_NODE; +document.DOCUMENT_POSITION_CONTAINS; +document instanceof Node; +document instanceof Document; + +impl.createDocument( + NAMESPACE.XML, + 'qualifiedName', + impl.createDocumentType('qualifiedName') +); +const doctype = impl.createDocumentType('qualifiedName', 'publicId', 'systemId'); +document instanceof Node; +document instanceof DocumentType; + +impl.createDocumentType('qualifiedName', 'publicId'); +impl.createHTMLDocument(); +impl.createHTMLDocument(false); +impl.createHTMLDocument('title'); + const source = ` test diff --git a/index.d.ts b/index.d.ts index ab280d70f..57234467e 100644 --- a/index.d.ts +++ b/index.d.ts @@ -323,7 +323,364 @@ declare module '@xmldom/xmldom' { // END ./lib/errors.js // START ./lib/dom.js + /** + * The DOM Node interface is an abstract base class upon which many other DOM API objects are + * based, thus letting those object types to be used similarly and often interchangeably. As an + * abstract class, there is no such thing as a plain Node object. All objects that implement + * Node functionality are based on one of its subclasses. Most notable are Document, Element, + * and DocumentFragment. + * + * In addition, every kind of DOM node is represented by an interface based on Node. These + * include Attr, CharacterData (which Text, Comment, CDATASection and ProcessingInstruction are + * all based on), and DocumentType. + * + * In some cases, a particular feature of the base Node interface may not apply to one of its + * child interfaces; in that case, the inheriting node may return null or throw an exception, + * depending on circumstances. For example, attempting to add children to a node type that + * cannot have children will throw an exception. + * + * **This behavior is slightly different from the in the specs**: + * - undeclared properties: nodeType, baseURI, isConnected, parentElement, textContent + * - missing methods: contains, getRootNode, isEqualNode, isSameNode + * + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 + * @see https://dom.spec.whatwg.org/#node + * @prettierignore + */ + interface Node { + /** + * Returns the children. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/childNodes) + */ + readonly childNodes: NodeListOf; + /** + * Returns the first child. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/firstChild) + */ + readonly firstChild: ChildNode | null; + /** + * Returns the last child. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/lastChild) + */ + readonly lastChild: ChildNode | null; + /** + * The local part of the qualified name of this node. + */ + localName: string | null, + /** + * The namespace URI of this node. + */ + readonly namespaceURI: string | null, + /** + * Returns the next sibling. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/nextSibling) + */ + readonly nextSibling: ChildNode | null; + /** + * Returns a string appropriate for the type of node. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/nodeName) + */ + readonly nodeName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/nodeValue) */ + nodeValue: string | null; + /** + * Returns the node document. Returns null for documents. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/ownerDocument) + */ + readonly ownerDocument: Document | null; + /** + * Returns the parent. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/parentNode) + */ + readonly parentNode: ParentNode | null; + /** + * The prefix of the namespace for this node. + */ + prefix: string | null, + /** + * Returns the previous sibling. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/previousSibling) + */ + readonly previousSibling: ChildNode | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/appendChild) */ + appendChild(node: T): T; + /** + * Returns a copy of node. If deep is true, the copy also includes the node's descendants. + * + * @throws {DOMException} + * May throw a DOMException if operations within {@link Element#setAttributeNode} or + * {@link Node#appendChild} (which are potentially invoked in this method) do not meet their + * specific constraints. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/cloneNode) + */ + cloneNode(deep?: boolean): Node; + /** + * Returns a bitmask indicating the position of other relative to node. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/compareDocumentPosition) + */ + compareDocumentPosition(other: Node): number; + /** + * Returns whether node has children. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/hasChildNodes) + */ + hasChildNodes(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/insertBefore) */ + insertBefore(node: T, child: Node | null): T; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/isDefaultNamespace) */ + isDefaultNamespace(namespace: string | null): boolean; + /** + * Checks whether the DOM implementation implements a specific feature and its version. + * + * @deprecated + * Since `DOMImplementation.hasFeature` is deprecated and always returns true. + * @param feature + * The package name of the feature to test. This is the same name that can be passed to the + * method `hasFeature` on `DOMImplementation`. + * @param version + * This is the version number of the package name to test. + * @since Introduced in DOM Level 2 + * @see {@link DOMImplementation.hasFeature} + */ + isSupported(feature:string, version:string): true; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/lookupNamespaceURI) */ + lookupNamespaceURI(prefix: string | null): string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/lookupPrefix) */ + lookupPrefix(namespace: string | null): string | null; + /** + * Removes empty exclusive Text nodes and concatenates the data of remaining contiguous exclusive Text nodes into the first of their nodes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/normalize) + */ + normalize(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/removeChild) */ + removeChild(child: T): T; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/replaceChild) */ + replaceChild(node: Node, child: T): T; + /** node is an element. */ + readonly ELEMENT_NODE: 1; + readonly ATTRIBUTE_NODE: 2; + /** node is a Text node. */ + readonly TEXT_NODE: 3; + /** node is a CDATASection node. */ + readonly CDATA_SECTION_NODE: 4; + readonly ENTITY_REFERENCE_NODE: 5; + readonly ENTITY_NODE: 6; + /** node is a ProcessingInstruction node. */ + readonly PROCESSING_INSTRUCTION_NODE: 7; + /** node is a Comment node. */ + readonly COMMENT_NODE: 8; + /** node is a document. */ + readonly DOCUMENT_NODE: 9; + /** node is a doctype. */ + readonly DOCUMENT_TYPE_NODE: 10; + /** node is a DocumentFragment node. */ + readonly DOCUMENT_FRAGMENT_NODE: 11; + readonly NOTATION_NODE: 12; + /** Set when node and other are not in the same tree. */ + readonly DOCUMENT_POSITION_DISCONNECTED: 0x01; + /** Set when other is preceding node. */ + readonly DOCUMENT_POSITION_PRECEDING: 0x02; + /** Set when other is following node. */ + readonly DOCUMENT_POSITION_FOLLOWING: 0x04; + /** Set when other is an ancestor of node. */ + readonly DOCUMENT_POSITION_CONTAINS: 0x08; + /** Set when other is a descendant of node. */ + readonly DOCUMENT_POSITION_CONTAINED_BY: 0x10; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 0x20; + } + var Node: { + prototype: Node; + // from ts 5.3 + [Symbol.hasInstance](val: unknown): val is Node + /** node is an element. */ + readonly ELEMENT_NODE: 1; + readonly ATTRIBUTE_NODE: 2; + /** node is a Text node. */ + readonly TEXT_NODE: 3; + /** node is a CDATASection node. */ + readonly CDATA_SECTION_NODE: 4; + readonly ENTITY_REFERENCE_NODE: 5; + readonly ENTITY_NODE: 6; + /** node is a ProcessingInstruction node. */ + readonly PROCESSING_INSTRUCTION_NODE: 7; + /** node is a Comment node. */ + readonly COMMENT_NODE: 8; + /** node is a document. */ + readonly DOCUMENT_NODE: 9; + /** node is a doctype. */ + readonly DOCUMENT_TYPE_NODE: 10; + /** node is a DocumentFragment node. */ + readonly DOCUMENT_FRAGMENT_NODE: 11; + readonly NOTATION_NODE: 12; + /** Set when node and other are not in the same tree. */ + readonly DOCUMENT_POSITION_DISCONNECTED: 0x01; + /** Set when other is preceding node. */ + readonly DOCUMENT_POSITION_PRECEDING: 0x02; + /** Set when other is following node. */ + readonly DOCUMENT_POSITION_FOLLOWING: 0x04; + /** Set when other is an ancestor of node. */ + readonly DOCUMENT_POSITION_CONTAINS: 0x08; + /** Set when other is a descendant of node. */ + readonly DOCUMENT_POSITION_CONTAINED_BY: 0x10; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 0x20; + }; + + interface Document extends Node { + /** + * The mime type of the document is determined at creation time and can not be modified. + * + * @see https://dom.spec.whatwg.org/#concept-document-content-type + * @see {@link DOMImplementation} + * @see {@link MIME_TYPE} + */ + readonly contentType:MIME_TYPE; + /** + * @see https://dom.spec.whatwg.org/#concept-document-type + * @see {@link DOMImplementation} + */ + readonly type: 'html' | 'xml'; + /** + * The implementation that created this document. + * + * @type DOMImplementation + * @readonly + */ + readonly implementation: DOMImplementation; + readonly ownerDocument: Document; + readonly nodeName: '#document', + readonly nodeType: typeof Node.DOCUMENT_NODE, + readonly doctype: DocumentType | null + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createAttribute) + */ + createAttribute(localName: string): Attr; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createAttributeNS) */ + createAttributeNS(namespace: string | null, qualifiedName: string): Attr; + /** + * Returns a CDATASection node whose data is data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createCDATASection) + */ + createCDATASection(data: string): CDATASection; + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createComment) + */ + createComment(data: string): Comment; + /** + * Creates a new document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createDocumentFragment) + */ + createDocumentFragment(): DocumentFragment; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElement) + */ + createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; + /** @deprecated */ + createElement(tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; + createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; + /** + * Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after ":" (U+003E) in qualifiedName or qualifiedName. + * + * If localName does not match the Name production an "InvalidCharacterError" DOMException will be thrown. + * + * If one of the following conditions is true a "NamespaceError" DOMException will be thrown: + * + * localName does not match the QName production. + * Namespace prefix is not null and namespace is the empty string. + * Namespace prefix is "xml" and namespace is not the XML namespace. + * qualifiedName or namespace prefix is "xmlns" and namespace is not the XMLNS namespace. + * namespace is the XMLNS namespace and neither qualifiedName nor namespace prefix is "xmlns". + * + * When supplied, options's is can be used to create a customized built-in element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElementNS) + */ + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: K): SVGElementTagNameMap[K]; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; + createElementNS(namespaceURI: "http://www.w3.org/1998/Math/MathML", qualifiedName: K): MathMLElementTagNameMap[K]; + createElementNS(namespaceURI: "http://www.w3.org/1998/Math/MathML", qualifiedName: string): MathMLElement; + createElementNS(namespaceURI: string | null, qualifiedName: string, options?: ElementCreationOptions): Element; + createElementNS(namespace: string | null, qualifiedName: string, options?: string | ElementCreationOptions): Element; + /** + * Returns a ProcessingInstruction node whose target is target and data is data. If target does not match the Name production an "InvalidCharacterError" DOMException will be thrown. If data contains "?>" an "InvalidCharacterError" DOMException will be thrown. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction) + */ + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createTextNode) + */ + createTextNode(data: string): Text; + /** + * Returns a reference to the first object with the specified value of the ID attribute. + * @param elementId String that specifies the ID value. + */ + getElementById(elementId: string): HTMLElement | null; + /** + * Returns a HTMLCollection of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getElementsByClassName) + */ + getElementsByClassName(classNames: string): HTMLCollectionOf; + /** + * Returns a copy of node. If deep is true, the copy also includes the node's descendants. + * + * If node is a document or a shadow root, throws a "NotSupportedError" DOMException. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/importNode) + */ + importNode(node: T, deep?: boolean): T; + } + var Document: { + prototype: Document; + // from ts 5.3 + [Symbol.hasInstance](val: unknown): val is Document; + } + /** + * A Node containing a doctype. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentType) + */ + interface DocumentType extends Node { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentType/name) */ + readonly name: string; + readonly internalSubset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentType/publicId) */ + readonly publicId: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentType/systemId) */ + readonly systemId: string; + } + var DocumentType: { + prototype: DocumentType; + // from ts 5.3 + [Symbol.hasInstance](val: unknown): val is DocumentType; + }; class DOMImplementation { /** * The DOMImplementation interface represents an object providing methods which are not diff --git a/lib/dom.js b/lib/dom.js index c009028c1..c8a6c9504 100644 --- a/lib/dom.js +++ b/lib/dom.js @@ -980,7 +980,7 @@ DOMImplementation.prototype = { * * **This behavior is slightly different from the in the specs**: * - undeclared properties: nodeType, baseURI, isConnected, parentElement, textContent - * - missing methods: nodeType, baseURI, isConnected, parentElement, textContent + * - missing methods: contains, getRootNode, isEqualNode, isSameNode * * @class * @abstract @@ -1018,12 +1018,6 @@ Node.prototype = { * @type {Node | null} */ nextSibling: null, - /** - * The attributes of this node. - * - * @type {NamedNodeMap | null} - */ - attributes: null, /** * The parent node of this node. * @@ -1213,16 +1207,6 @@ Node.prototype = { isSupported: function (feature, version) { return this.ownerDocument.implementation.hasFeature(feature, version); }, - /** - * Determines if the node has any attributes. - * - * @returns {boolean} - * Returns true if the node has any attributes, and false otherwise. - * @since Introduced in DOM Level 2 - */ - hasAttributes: function () { - return this.attributes.length > 0; - }, /** * Look up the prefix associated to the given namespace URI, starting from this node. * **The default namespace declarations are ignored by this method.** @@ -1966,7 +1950,7 @@ Document.prototype = { insertBefore: function (newChild, refChild) { //raises - if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) { + if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) { var child = newChild.firstChild; while (child) { var next = child.nextSibling; @@ -2206,6 +2190,12 @@ function Element(symbol) { } Element.prototype = { nodeType: ELEMENT_NODE, + /** + * The attributes of this element. + * + * @type {NamedNodeMap | null} + */ + attributes: null, getQualifiedName: function () { return this.prefix ? this.prefix + ':' + this.localName : this.localName; }, diff --git a/lib/index.js b/lib/index.js index d4330e1c1..3c4b29fa1 100644 --- a/lib/index.js +++ b/lib/index.js @@ -15,7 +15,6 @@ exports.ParseError = errors.ParseError; var dom = require('./dom'); exports.DOMImplementation = dom.DOMImplementation; -exports.XMLSerializer = dom.XMLSerializer; exports.Attr = dom.Attr; exports.CDATASection = dom.CDATASection; exports.CharacterData = dom.CharacterData; @@ -32,6 +31,7 @@ exports.NodeList = dom.NodeList; exports.Notation = dom.Notation; exports.ProcessingInstruction = dom.ProcessingInstruction; exports.Text = dom.Text; +exports.XMLSerializer = dom.XMLSerializer; var domParser = require('./dom-parser'); exports.DOMParser = domParser.DOMParser; From 001c7fe3c4592d02235d4428b680eb90038e6359 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Sat, 31 Aug 2024 08:52:43 +0200 Subject: [PATCH 03/13] fix: drop reference to dom lib from typescript fixes #285 --- index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/index.d.ts b/index.d.ts index 57234467e..9704b70e2 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,5 +1,3 @@ -/// - declare module '@xmldom/xmldom' { // START ./lib/conventions.js /** From 361466701d79d811a22b699ee122629527401f3b Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Sat, 31 Aug 2024 09:08:08 +0200 Subject: [PATCH 04/13] fix: allow instanceof for old ts versions --- examples/typescript-node-es6/tsconfig.json | 2 +- index.d.ts | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/examples/typescript-node-es6/tsconfig.json b/examples/typescript-node-es6/tsconfig.json index 1c747f619..0a948a678 100644 --- a/examples/typescript-node-es6/tsconfig.json +++ b/examples/typescript-node-es6/tsconfig.json @@ -13,7 +13,7 @@ /* Language and Environment */ "target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, "lib": [ - "ES5" + "ES5", ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */, // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ diff --git a/index.d.ts b/index.d.ts index 9704b70e2..8862cfdc0 100644 --- a/index.d.ts +++ b/index.d.ts @@ -498,9 +498,10 @@ declare module '@xmldom/xmldom' { readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 0x20; } var Node: { - prototype: Node; - // from ts 5.3 - [Symbol.hasInstance](val: unknown): val is Node + // instanceof pre ts 5.3 + (val: unknown): val is Node; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is Node; /** node is an element. */ readonly ELEMENT_NODE: 1; readonly ATTRIBUTE_NODE: 2; @@ -655,8 +656,9 @@ declare module '@xmldom/xmldom' { importNode(node: T, deep?: boolean): T; } var Document: { - prototype: Document; - // from ts 5.3 + // instanceof pre ts 5.3 + (val: unknown): val is Document; + // instanceof post ts 5.3 [Symbol.hasInstance](val: unknown): val is Document; } /** @@ -675,8 +677,9 @@ declare module '@xmldom/xmldom' { } var DocumentType: { - prototype: DocumentType; - // from ts 5.3 + // instanceof pre ts 5.3 + (val: unknown): val is DocumentType; + // instanceof post ts 5.3 [Symbol.hasInstance](val: unknown): val is DocumentType; }; class DOMImplementation { From 2224bf46460cc8fd0de08fca20ba7b18c29ca980 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Sat, 31 Aug 2024 13:50:32 +0200 Subject: [PATCH 05/13] fix: add `@ypes/node` devDependency for supporting `console.*` --- examples/typescript-node-es6/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/typescript-node-es6/package.json b/examples/typescript-node-es6/package.json index 9b403fe6a..3cdcc5d6a 100644 --- a/examples/typescript-node-es6/package.json +++ b/examples/typescript-node-es6/package.json @@ -14,6 +14,7 @@ ], "license": "MIT", "devDependencies": { + "@types/node": "14.14.31", "typescript": "*" }, "dependencies": { From 936e84b193b5bc1c15ff703f0e3ce8f3a55591e7 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Sat, 31 Aug 2024 14:53:54 +0200 Subject: [PATCH 06/13] fix: add assertions to examples to avoid CodeQL warning. This revealed some issues in the implementation and types, which were fixed along the way - drop `ParseError.cause` since it never worked --- examples/typescript-node-es6/package.json | 2 +- examples/typescript-node-es6/src/index.ts | 89 +++++++++++++--------- examples/typescript-node-es6/tsconfig.json | 2 +- index.d.ts | 29 +------ lib/errors.js | 8 +- 5 files changed, 60 insertions(+), 70 deletions(-) diff --git a/examples/typescript-node-es6/package.json b/examples/typescript-node-es6/package.json index 3cdcc5d6a..8b4532f5e 100644 --- a/examples/typescript-node-es6/package.json +++ b/examples/typescript-node-es6/package.json @@ -6,7 +6,7 @@ "type": "module", "scripts": { "tsc": "tsc", - "test": "node dist/index.js" + "test": "tsc && node dist/index.js" }, "keywords": [ "test", diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index a42e61cb8..19ee28ec2 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -12,60 +12,81 @@ import { NAMESPACE, onWarningStopParsing, ParseError, - XMLSerializer, Node, DocumentType -} from "@xmldom/xmldom"; + XMLSerializer, + Node, + DocumentType, +} from '@xmldom/xmldom'; + +const failedAssertions: Error[] = []; +let assertions = 0; +const assert = ( + actual: T, + expected: T, + message: string = `#${++assertions}` +) => { + if (actual === expected) { + console.error(`assert ${message} passed: ${actual}`); + } else { + failedAssertions.push( + new Error( + `assert ${message} failed: expected ${JSON.stringify(expected)}, but was ${JSON.stringify( + actual + )}` + ) + ); + } +}; // lib/conventions -isHTMLMimeType(MIME_TYPE.HTML); -hasDefaultHTMLNamespace(MIME_TYPE.XML_XHTML_APPLICATION); -isValidMimeType(MIME_TYPE.XML_SVG_IMAGE); -isValidMimeType(MIME_TYPE.XML_APPLICATION); +assert(isHTMLMimeType(MIME_TYPE.HTML), true); +assert(hasDefaultHTMLNamespace(MIME_TYPE.XML_XHTML_APPLICATION), true); +assert(isValidMimeType(MIME_TYPE.XML_SVG_IMAGE), true); +assert(isValidMimeType(MIME_TYPE.XML_APPLICATION), true); // lib/errors const domException = new DOMException(); -domException.code; // 0 -domException.name; // "Error" -domException.message; // "" -domException.INDEX_SIZE_ERR; +assert(domException.code, 0); +assert(domException.name, 'Error'); +assert(domException.message, undefined); new DOMException('message', DOMExceptionName.SyntaxError); new DOMException(DOMException.DATA_CLONE_ERR); new DOMException(ExceptionCode.INDEX_SIZE_ERR, 'message'); const parseError = new ParseError('message'); -parseError.message; -parseError.cause; -parseError.locator; +assert(parseError.message, 'message'); new ParseError('message', {}, domException); // lib/dom -Node.ATTRIBUTE_NODE -Node.DOCUMENT_POSITION_CONTAINS - +assert(Node.ATTRIBUTE_NODE, 2); +assert(Node.DOCUMENT_POSITION_CONTAINS, 8); const impl = new DOMImplementation(); const document = impl.createDocument(null, 'qualifiedName'); -document.contentType; -document.type; -document.ATTRIBUTE_NODE; -document.DOCUMENT_POSITION_CONTAINS; -document instanceof Node; -document instanceof Document; +assert(document.contentType, MIME_TYPE.XML_APPLICATION); +assert(document.type, 'xml'); +assert(document.ATTRIBUTE_NODE, 2); +assert(document.DOCUMENT_POSITION_CONTAINS, 8); +assert(document instanceof Node, true); +assert(document instanceof Document, true); impl.createDocument( NAMESPACE.XML, 'qualifiedName', impl.createDocumentType('qualifiedName') ); -const doctype = impl.createDocumentType('qualifiedName', 'publicId', 'systemId'); -document instanceof Node; -document instanceof DocumentType; - +const doctype = impl.createDocumentType( + 'qualifiedName', + 'publicId', + 'systemId' +); +assert(doctype instanceof Node, true); +assert(doctype instanceof DocumentType, true); impl.createDocumentType('qualifiedName', 'publicId'); -impl.createHTMLDocument(); -impl.createHTMLDocument(false); -impl.createHTMLDocument('title'); +assert(impl.createHTMLDocument().type, 'html'); +assert(impl.createHTMLDocument(false).childNodes.length, 0); +assert(impl.createHTMLDocument('title').childNodes.length, 2); const source = ` test @@ -74,11 +95,9 @@ const source = ` const doc = new DOMParser({ onError: onWarningStopParsing, }).parseFromString(source, MIME_TYPE.XML_TEXT); +assert(new XMLSerializer().serializeToString(doc), source); -const serialized = new XMLSerializer().serializeToString(doc); - -if (source !== serialized) { - throw `expected\n${source}\nbut was\n${serialized}`; -} else { - console.log(serialized); +if (failedAssertions.length > 0) { + failedAssertions.forEach((error) => console.error(error)); + process.exit(1); } diff --git a/examples/typescript-node-es6/tsconfig.json b/examples/typescript-node-es6/tsconfig.json index 0a948a678..1c747f619 100644 --- a/examples/typescript-node-es6/tsconfig.json +++ b/examples/typescript-node-es6/tsconfig.json @@ -13,7 +13,7 @@ /* Language and Environment */ "target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, "lib": [ - "ES5", + "ES5" ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */, // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ diff --git a/index.d.ts b/index.d.ts index 8862cfdc0..f49a376cc 100644 --- a/index.d.ts +++ b/index.d.ts @@ -282,31 +282,6 @@ declare module '@xmldom/xmldom' { static readonly TIMEOUT_ERR: 23; static readonly INVALID_NODE_TYPE_ERR: 24; static readonly DATA_CLONE_ERR: 25; - readonly INDEX_SIZE_ERR: 1; - readonly DOMSTRING_SIZE_ERR: 2; - readonly HIERARCHY_REQUEST_ERR: 3; - readonly WRONG_DOCUMENT_ERR: 4; - readonly INVALID_CHARACTER_ERR: 5; - readonly NO_DATA_ALLOWED_ERR: 6; - readonly NO_MODIFICATION_ALLOWED_ERR: 7; - readonly NOT_FOUND_ERR: 8; - readonly NOT_SUPPORTED_ERR: 9; - readonly INUSE_ATTRIBUTE_ERR: 10; - readonly INVALID_STATE_ERR: 11; - readonly SYNTAX_ERR: 12; - readonly INVALID_MODIFICATION_ERR: 13; - readonly NAMESPACE_ERR: 14; - readonly INVALID_ACCESS_ERR: 15; - readonly VALIDATION_ERR: 16; - readonly TYPE_MISMATCH_ERR: 17; - readonly SECURITY_ERR: 18; - readonly NETWORK_ERR: 19; - readonly ABORT_ERR: 20; - readonly URL_MISMATCH_ERR: 21; - readonly QUOTA_EXCEEDED_ERR: 22; - readonly TIMEOUT_ERR: 23; - readonly INVALID_NODE_TYPE_ERR: 24; - readonly DATA_CLONE_ERR: 25; } /** @@ -316,7 +291,6 @@ declare module '@xmldom/xmldom' { constructor(message: string, locator?: any, cause?: Error); readonly message: string; readonly locator?: any; - readonly cause?: Error; } // END ./lib/errors.js @@ -749,7 +723,8 @@ declare module '@xmldom/xmldom' { * __It behaves slightly different from the description in the living standard__: * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs are * omitted) - * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. + * - several properties and methods are missing + * - Nothing related to events is implemented * * @see {@link DOMImplementation.createDocument} * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument diff --git a/lib/errors.js b/lib/errors.js index b802f45be..2e20ffb5c 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -179,8 +179,7 @@ var ExceptionCode = { var entries = Object.entries(ExceptionCode); for (var i = 0; i < entries.length; i++) { var key = entries[i][0]; - var value = entries[i][1]; - DOMException[key] = value; + DOMException[key] = entries[i][1]; } /** @@ -189,13 +188,10 @@ for (var i = 0; i < entries.length; i++) { * @class * @param {string} message * @param {any} [locator] - * @param {Error} [cause] - * Optional, can provide details about the location in the source. */ -function ParseError(message, locator, cause) { +function ParseError(message, locator) { this.message = message; this.locator = locator; - this.cause = cause; if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError); } extendError(ParseError); From 5c19d297d3d95e70f9310b6bef4fdb95d2f25203 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Mon, 2 Sep 2024 07:54:29 +0200 Subject: [PATCH 07/13] fix: replace enum with literal types and allow any string instead of just the enum values to be passed --- examples/typescript-node-es6/src/index.ts | 8 +- index.d.ts | 434 ++++++++++++++-------- 2 files changed, 290 insertions(+), 152 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index 19ee28ec2..316a8502b 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -38,9 +38,13 @@ const assert = ( }; // lib/conventions - +// widen type to string to check that any string can be passed +const mimeHtml: string = MIME_TYPE.HTML; +assert(isHTMLMimeType(mimeHtml), true); assert(isHTMLMimeType(MIME_TYPE.HTML), true); +assert(hasDefaultHTMLNamespace(mimeHtml), true); assert(hasDefaultHTMLNamespace(MIME_TYPE.XML_XHTML_APPLICATION), true); +assert(isValidMimeType(mimeHtml), true); assert(isValidMimeType(MIME_TYPE.XML_SVG_IMAGE), true); assert(isValidMimeType(MIME_TYPE.XML_APPLICATION), true); @@ -88,6 +92,8 @@ assert(impl.createHTMLDocument().type, 'html'); assert(impl.createHTMLDocument(false).childNodes.length, 0); assert(impl.createHTMLDocument('title').childNodes.length, 2); +assert(new DOMParser().parseFromString(`
`, mimeHtml).childNodes.length, 1) + const source = ` test diff --git a/index.d.ts b/index.d.ts index f49a376cc..4a649c34d 100644 --- a/index.d.ts +++ b/index.d.ts @@ -10,9 +10,10 @@ declare module '@xmldom/xmldom' { * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign */ function assign(target: T, source: S): T & S; + /** - * For both the `text/html` and the `application/xhtml+xml` namespace the spec defines that the - * HTML namespace is provided as the default. + * For both the `text/html` and the `application/xhtml+xml` namespace the spec defines that + * the HTML namespace is provided as the default. * * @param {string} mimeType * @returns {boolean} @@ -20,7 +21,10 @@ declare module '@xmldom/xmldom' { * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument */ - function hasDefaultHTMLNamespace(mimeType: string): mimeType is MIME_TYPE.HTML | MIME_TYPE.XML_XHTML_APPLICATION; + function hasDefaultHTMLNamespace( + mimeType: string + ): mimeType is typeof MIME_TYPE.HTML | typeof MIME_TYPE.XML_XHTML_APPLICATION; + /** * Only returns true if `value` matches MIME_TYPE.HTML, which indicates an HTML document. * @@ -29,7 +33,8 @@ declare module '@xmldom/xmldom' { * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */ - function isHTMLMimeType(mimeType: string): mimeType is MIME_TYPE.HTML; + function isHTMLMimeType(mimeType: string): mimeType is typeof MIME_TYPE.HTML; + /** * Only returns true if `mimeType` is one of the allowed values for `DOMParser.parseFromString`. */ @@ -41,10 +46,20 @@ declare module '@xmldom/xmldom' { * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 * MDN * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype - * WHATWG HTML Spec + * WHATWG HTML Spec + * @see {@link DOMParser.prototype.parseFromString} + */ + type MIME_TYPE = (typeof MIME_TYPE)[keyof typeof MIME_TYPE]; + /** + * All mime types that are allowed as input to `DOMParser.parseFromString` + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 + * MDN + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype + * WHATWG HTML Spec * @see {@link DOMParser.prototype.parseFromString} */ - enum MIME_TYPE { + var MIME_TYPE: { /** * `text/html`, the only mime type that triggers treating an XML document as HTML. * @@ -52,9 +67,9 @@ declare module '@xmldom/xmldom' { * @see https://en.wikipedia.org/wiki/HTML Wikipedia * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring - * WHATWG HTML Spec + * WHATWG HTML Spec */ - HTML = 'text/html', + readonly HTML: 'text/html'; /** * `application/xml`, the standard mime type for XML documents. * @@ -63,7 +78,7 @@ declare module '@xmldom/xmldom' { * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303 * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia */ - XML_APPLICATION = 'application/xml', + readonly XML_APPLICATION: 'application/xml'; /** * `text/html`, an alias for `application/xml`. * @@ -71,7 +86,7 @@ declare module '@xmldom/xmldom' { * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia */ - XML_TEXT = 'text/xml', + readonly XML_TEXT: 'text/xml'; /** * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace, * but is parsed as an XML document. @@ -81,155 +96,169 @@ declare module '@xmldom/xmldom' { * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec * @see https://en.wikipedia.org/wiki/XHTML Wikipedia */ - XML_XHTML_APPLICATION = 'application/xhtml+xml', + readonly XML_XHTML_APPLICATION: 'application/xhtml+xml'; /** * `image/svg+xml`, * - * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration + * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType + * registration * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1 * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia */ - XML_SVG_IMAGE = 'image/svg+xml', - } + readonly XML_SVG_IMAGE: 'image/svg+xml'; + }; /** * Namespaces that are used in xmldom. * * @see http://www.w3.org/TR/REC-xml-names */ - enum NAMESPACE { + type NAMESPACE = (typeof NAMESPACE)[keyof typeof NAMESPACE]; + /** + * Namespaces that are used in xmldom. + * + * @see http://www.w3.org/TR/REC-xml-names + */ + var NAMESPACE: { /** * The XHTML namespace. * * @see http://www.w3.org/1999/xhtml */ - HTML = 'http://www.w3.org/1999/xhtml', + readonly HTML: 'http://www.w3.org/1999/xhtml'; /** * The SVG namespace. * * @see http://www.w3.org/2000/svg */ - SVG = 'http://www.w3.org/2000/svg', + readonly SVG: 'http://www.w3.org/2000/svg'; /** * The `xml:` namespace. * * @see http://www.w3.org/XML/1998/namespace */ - XML = 'http://www.w3.org/XML/1998/namespace', + readonly XML: 'http://www.w3.org/XML/1998/namespace'; /** * The `xmlns:` namespace. * * @see https://www.w3.org/2000/xmlns/ */ - XMLNS = 'http://www.w3.org/2000/xmlns/', - } + readonly XMLNS: 'http://www.w3.org/2000/xmlns/'; + }; + // END ./lib/conventions.js // START ./lib/errors.js - enum DOMExceptionName { + type DOMExceptionName = + (typeof DOMExceptionName)[keyof typeof DOMExceptionName]; + var DOMExceptionName: { /** * the default value as defined by the spec */ - Error = 'Error', + readonly Error: 'Error'; /** * @deprecated * Use RangeError instead. */ - IndexSizeError = 'IndexSizeError', + readonly IndexSizeError: 'IndexSizeError'; /** * @deprecated * Just to match the related static code, not part of the spec. */ - DomstringSizeError = 'DomstringSizeError', - HierarchyRequestError = 'HierarchyRequestError', - WrongDocumentError = 'WrongDocumentError', - InvalidCharacterError = 'InvalidCharacterError', + readonly DomstringSizeError: 'DomstringSizeError'; + readonly HierarchyRequestError: 'HierarchyRequestError'; + readonly WrongDocumentError: 'WrongDocumentError'; + readonly InvalidCharacterError: 'InvalidCharacterError'; /** * @deprecated * Just to match the related static code, not part of the spec. */ - NoDataAllowedError = 'NoDataAllowedError', - NoModificationAllowedError = 'NoModificationAllowedError', - NotFoundError = 'NotFoundError', - NotSupportedError = 'NotSupportedError', - InUseAttributeError = 'InUseAttributeError', - InvalidStateError = 'InvalidStateError', - SyntaxError = 'SyntaxError', - InvalidModificationError = 'InvalidModificationError', - NamespaceError = 'NamespaceError', + readonly NoDataAllowedError: 'NoDataAllowedError'; + readonly NoModificationAllowedError: 'NoModificationAllowedError'; + readonly NotFoundError: 'NotFoundError'; + readonly NotSupportedError: 'NotSupportedError'; + readonly InUseAttributeError: 'InUseAttributeError'; + readonly InvalidStateError: 'InvalidStateError'; + readonly SyntaxError: 'SyntaxError'; + readonly InvalidModificationError: 'InvalidModificationError'; + readonly NamespaceError: 'NamespaceError'; /** * @deprecated * Use TypeError for invalid arguments, * "NotSupportedError" DOMException for unsupported operations, * and "NotAllowedError" DOMException for denied requests instead. */ - InvalidAccessError = 'InvalidAccessError', + readonly InvalidAccessError: 'InvalidAccessError'; /** * @deprecated * Just to match the related static code, not part of the spec. */ - ValidationError = 'ValidationError', + readonly ValidationError: 'ValidationError'; /** * @deprecated * Use TypeError instead. */ - TypeMismatchError = 'TypeMismatchError', - SecurityError = 'SecurityError', - NetworkError = 'NetworkError', - AbortError = 'AbortError', + readonly TypeMismatchError: 'TypeMismatchError'; + readonly SecurityError: 'SecurityError'; + readonly NetworkError: 'NetworkError'; + readonly AbortError: 'AbortError'; /** * @deprecated * Just to match the related static code, not part of the spec. */ - URLMismatchError = 'URLMismatchError', - QuotaExceededError = 'QuotaExceededError', - TimeoutError = 'TimeoutError', - InvalidNodeTypeError = 'InvalidNodeTypeError', - DataCloneError = 'DataCloneError', - EncodingError = 'EncodingError', - NotReadableError = 'NotReadableError', - UnknownError = 'UnknownError', - ConstraintError = 'ConstraintError', - DataError = 'DataError', - TransactionInactiveError = 'TransactionInactiveError', - ReadOnlyError = 'ReadOnlyError', - VersionError = 'VersionError', - OperationError = 'OperationError', - NotAllowedError = 'NotAllowedError', - OptOutError = 'OptOutError', -} - enum ExceptionCode { - INDEX_SIZE_ERR = 1, - DOMSTRING_SIZE_ERR = 2, - HIERARCHY_REQUEST_ERR = 3, - WRONG_DOCUMENT_ERR = 4, - INVALID_CHARACTER_ERR = 5, - NO_DATA_ALLOWED_ERR = 6, - NO_MODIFICATION_ALLOWED_ERR = 7, - NOT_FOUND_ERR = 8, - NOT_SUPPORTED_ERR = 9, - INUSE_ATTRIBUTE_ERR = 10, - INVALID_STATE_ERR = 11, - SYNTAX_ERR = 12, - INVALID_MODIFICATION_ERR = 13, - NAMESPACE_ERR = 14, - INVALID_ACCESS_ERR = 15, - VALIDATION_ERR = 16, - TYPE_MISMATCH_ERR = 17, - SECURITY_ERR = 18, - NETWORK_ERR = 19, - ABORT_ERR = 20, - URL_MISMATCH_ERR = 21, - QUOTA_EXCEEDED_ERR = 22, - TIMEOUT_ERR = 23, - INVALID_NODE_TYPE_ERR = 24, - DATA_CLONE_ERR = 25, + readonly URLMismatchError: 'URLMismatchError'; + readonly QuotaExceededError: 'QuotaExceededError'; + readonly TimeoutError: 'TimeoutError'; + readonly InvalidNodeTypeError: 'InvalidNodeTypeError'; + readonly DataCloneError: 'DataCloneError'; + readonly EncodingError: 'EncodingError'; + readonly NotReadableError: 'NotReadableError'; + readonly UnknownError: 'UnknownError'; + readonly ConstraintError: 'ConstraintError'; + readonly DataError: 'DataError'; + readonly TransactionInactiveError: 'TransactionInactiveError'; + readonly ReadOnlyError: 'ReadOnlyError'; + readonly VersionError: 'VersionError'; + readonly OperationError: 'OperationError'; + readonly NotAllowedError: 'NotAllowedError'; + readonly OptOutError: 'OptOutError'; + }; + type ExceptionCode = (typeof ExceptionCode)[keyof typeof ExceptionCode]; + + var ExceptionCode: { + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; }; + /** - * DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation - * is impossible to perform (either for logical reasons, because data is lost, or because the - * implementation has become unstable). In general, DOM methods return specific error values in - * ordinary processing situations, such as out-of-bound errors when using NodeList. + * DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an + * operation is impossible to perform (either for logical reasons, because data is lost, or + * because the implementation has become unstable). In general, DOM methods return specific + * error values in ordinary processing situations, such as out-of-bound errors when using + * NodeList. * * Implementations should raise other exceptions under other circumstances. For example, * implementations should raise an implementation-dependent exception if a null argument is @@ -255,6 +284,7 @@ declare module '@xmldom/xmldom' { class DOMException extends Error { constructor(message?: string, name?: DOMExceptionName | string); constructor(code?: ExceptionCode, message?: string); + readonly name: DOMExceptionName; readonly code: ExceptionCode | 0; static readonly INDEX_SIZE_ERR: 1; @@ -289,9 +319,11 @@ declare module '@xmldom/xmldom' { */ class ParseError extends Error { constructor(message: string, locator?: any, cause?: Error); + readonly message: string; readonly locator?: any; } + // END ./lib/errors.js // START ./lib/dom.js @@ -341,11 +373,11 @@ declare module '@xmldom/xmldom' { /** * The local part of the qualified name of this node. */ - localName: string | null, + localName: string | null; /** * The namespace URI of this node. */ - readonly namespaceURI: string | null, + readonly namespaceURI: string | null; /** * Returns the next sibling. * @@ -375,42 +407,49 @@ declare module '@xmldom/xmldom' { /** * The prefix of the namespace for this node. */ - prefix: string | null, + prefix: string | null; /** * Returns the previous sibling. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/previousSibling) */ readonly previousSibling: ChildNode | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/appendChild) */ appendChild(node: T): T; + /** * Returns a copy of node. If deep is true, the copy also includes the node's descendants. * * @throws {DOMException} * May throw a DOMException if operations within {@link Element#setAttributeNode} or - * {@link Node#appendChild} (which are potentially invoked in this method) do not meet their - * specific constraints. + * {@link Node#appendChild} (which are potentially invoked in this method) do not meet + * their specific constraints. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/cloneNode) */ cloneNode(deep?: boolean): Node; + /** * Returns a bitmask indicating the position of other relative to node. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/compareDocumentPosition) */ compareDocumentPosition(other: Node): number; + /** * Returns whether node has children. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/hasChildNodes) */ hasChildNodes(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/insertBefore) */ insertBefore(node: T, child: Node | null): T; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/isDefaultNamespace) */ isDefaultNamespace(namespace: string | null): boolean; + /** * Checks whether the DOM implementation implements a specific feature and its version. * @@ -424,21 +463,28 @@ declare module '@xmldom/xmldom' { * @since Introduced in DOM Level 2 * @see {@link DOMImplementation.hasFeature} */ - isSupported(feature:string, version:string): true; + isSupported(feature: string, version: string): true; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/lookupNamespaceURI) */ lookupNamespaceURI(prefix: string | null): string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/lookupPrefix) */ lookupPrefix(namespace: string | null): string | null; + /** - * Removes empty exclusive Text nodes and concatenates the data of remaining contiguous exclusive Text nodes into the first of their nodes. + * Removes empty exclusive Text nodes and concatenates the data of remaining contiguous + * exclusive Text nodes into the first of their nodes. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/normalize) */ normalize(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/removeChild) */ removeChild(child: T): T; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/replaceChild) */ replaceChild(node: Node, child: T): T; + /** node is an element. */ readonly ELEMENT_NODE: 1; readonly ATTRIBUTE_NODE: 2; @@ -471,6 +517,7 @@ declare module '@xmldom/xmldom' { readonly DOCUMENT_POSITION_CONTAINED_BY: 0x10; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 0x20; } + var Node: { // instanceof pre ts 5.3 (val: unknown): val is Node; @@ -517,7 +564,7 @@ declare module '@xmldom/xmldom' { * @see {@link DOMImplementation} * @see {@link MIME_TYPE} */ - readonly contentType:MIME_TYPE; + readonly contentType: MIME_TYPE; /** * @see https://dom.spec.whatwg.org/#concept-document-type * @see {@link DOMImplementation} @@ -531,51 +578,80 @@ declare module '@xmldom/xmldom' { */ readonly implementation: DOMImplementation; readonly ownerDocument: Document; - readonly nodeName: '#document', - readonly nodeType: typeof Node.DOCUMENT_NODE, - readonly doctype: DocumentType | null + readonly nodeName: '#document'; + readonly nodeType: typeof Node.DOCUMENT_NODE; + readonly doctype: DocumentType | null; + /** * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. + * + * @param name + * String that sets the attribute object's name. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createAttribute) */ createAttribute(localName: string): Attr; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createAttributeNS) */ createAttributeNS(namespace: string | null, qualifiedName: string): Attr; + /** * Returns a CDATASection node whose data is data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createCDATASection) */ createCDATASection(data: string): CDATASection; + /** * Creates a comment object with the specified data. - * @param data Sets the comment object's data. + * + * @param data + * Sets the comment object's data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createComment) */ createComment(data: string): Comment; + /** * Creates a new document. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createDocumentFragment) */ createDocumentFragment(): DocumentFragment; + /** * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. + * + * @param tagName + * The name of an element. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElement) */ - createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; - /** @deprecated */ - createElement(tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; - createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; + createElement( + tagName: K, + options?: ElementCreationOptions + ): HTMLElementTagNameMap[K]; + + /** + * @deprecated + */ + createElement( + tagName: K, + options?: ElementCreationOptions + ): HTMLElementDeprecatedTagNameMap[K]; + + createElement( + tagName: string, + options?: ElementCreationOptions + ): HTMLElement; + /** - * Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after ":" (U+003E) in qualifiedName or qualifiedName. + * Returns an element with namespace namespace. Its namespace prefix will be everything before + * ":" (U+003E) in qualifiedName or null. Its local name will be everything after ":" (U+003E) + * in qualifiedName or qualifiedName. * - * If localName does not match the Name production an "InvalidCharacterError" DOMException will be thrown. + * If localName does not match the Name production an "InvalidCharacterError" DOMException will + * be thrown. * * If one of the following conditions is true a "NamespaceError" DOMException will be thrown: * @@ -589,37 +665,83 @@ declare module '@xmldom/xmldom' { * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElementNS) */ - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: K): SVGElementTagNameMap[K]; - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; - createElementNS(namespaceURI: "http://www.w3.org/1998/Math/MathML", qualifiedName: K): MathMLElementTagNameMap[K]; - createElementNS(namespaceURI: "http://www.w3.org/1998/Math/MathML", qualifiedName: string): MathMLElement; - createElementNS(namespaceURI: string | null, qualifiedName: string, options?: ElementCreationOptions): Element; - createElementNS(namespace: string | null, qualifiedName: string, options?: string | ElementCreationOptions): Element; + createElementNS( + namespaceURI: 'http://www.w3.org/1999/xhtml', + qualifiedName: string + ): HTMLElement; + + createElementNS( + namespaceURI: 'http://www.w3.org/2000/svg', + qualifiedName: K + ): SVGElementTagNameMap[K]; + + createElementNS( + namespaceURI: 'http://www.w3.org/2000/svg', + qualifiedName: string + ): SVGElement; + + createElementNS( + namespaceURI: 'http://www.w3.org/1998/Math/MathML', + qualifiedName: K + ): MathMLElementTagNameMap[K]; + + createElementNS( + namespaceURI: 'http://www.w3.org/1998/Math/MathML', + qualifiedName: string + ): MathMLElement; + + createElementNS( + namespaceURI: string | null, + qualifiedName: string, + options?: ElementCreationOptions + ): Element; + + createElementNS( + namespace: string | null, + qualifiedName: string, + options?: string | ElementCreationOptions + ): Element; + /** - * Returns a ProcessingInstruction node whose target is target and data is data. If target does not match the Name production an "InvalidCharacterError" DOMException will be thrown. If data contains "?>" an "InvalidCharacterError" DOMException will be thrown. + * Returns a ProcessingInstruction node whose target is target and data is data. If target does + * not match the Name production an "InvalidCharacterError" DOMException will be thrown. If + * data contains "?>" an "InvalidCharacterError" DOMException will be thrown. * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction) + * [MDN + * Reference](https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction) */ - createProcessingInstruction(target: string, data: string): ProcessingInstruction; + createProcessingInstruction( + target: string, + data: string + ): ProcessingInstruction; + /** * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. + * + * @param data + * String that specifies the nodeValue property of the text node. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createTextNode) */ createTextNode(data: string): Text; + /** * Returns a reference to the first object with the specified value of the ID attribute. - * @param elementId String that specifies the ID value. + * + * @param elementId + * String that specifies the ID value. */ getElementById(elementId: string): HTMLElement | null; + /** - * Returns a HTMLCollection of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. + * Returns a HTMLCollection of the elements in the object on which the method was invoked (a + * document or an element) that have all the classes given by classNames. The classNames + * argument is interpreted as a space-separated list of classes. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getElementsByClassName) */ getElementsByClassName(classNames: string): HTMLCollectionOf; + /** * Returns a copy of node. If deep is true, the copy also includes the node's descendants. * @@ -629,12 +751,14 @@ declare module '@xmldom/xmldom' { */ importNode(node: T, deep?: boolean): T; } + var Document: { // instanceof pre ts 5.3 (val: unknown): val is Document; // instanceof post ts 5.3 [Symbol.hasInstance](val: unknown): val is Document; - } + }; + /** * A Node containing a doctype. * @@ -656,6 +780,7 @@ declare module '@xmldom/xmldom' { // instanceof post ts 5.3 [Symbol.hasInstance](val: unknown): val is DocumentType; }; + class DOMImplementation { /** * The DOMImplementation interface represents an object providing methods which are not @@ -682,15 +807,17 @@ declare module '@xmldom/xmldom' { * `type` set to `'xml'`). * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. * - * @returns {Document} The XML document. + * @returns {Document} + * The XML document. * @see {@link DOMImplementation.createHTMLDocument} - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN - * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM - * Level 2 Core (initial) + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument + * MDN + * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument + * DOM Level 2 Core (initial) * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core */ createDocument( - namespaceURI: string | null, + namespaceURI: NAMESPACE | string | null, qualifiedName: string, doctype?: DocumentType | null ): Document; @@ -701,9 +828,10 @@ declare module '@xmldom/xmldom' { * __This behavior is slightly different from the in the specs__: * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. * - * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` - * upon document creation or can be put into the document via methods - * like `Node.insertBefore()` or `Node.replaceChild()` + * @returns {DocumentType} + * which can either be used with `DOMImplementation.createDocument` + * upon document creation or can be put into the document via methods like + * `Node.insertBefore()` or `Node.replaceChild()` * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType * MDN * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM @@ -721,10 +849,9 @@ declare module '@xmldom/xmldom' { * Returns an HTML document, that might already have a basic DOM structure. * * __It behaves slightly different from the description in the living standard__: - * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs are - * omitted) - * - several properties and methods are missing - * - Nothing related to events is implemented + * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs + * are omitted) + * - several properties and methods are missing - Nothing related to events is implemented. * * @see {@link DOMImplementation.createDocument} * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument @@ -751,12 +878,13 @@ declare module '@xmldom/xmldom' { class XMLSerializer { serializeToString(node: Node, nodeFilter?: (node: Node) => boolean): string; } + // END ./lib/dom.js // START ./lib/dom-parser.js /** - * The DOMParser interface provides the ability to parse XML or HTML source code from a string - * into a DOM `Document`. + * The DOMParser interface provides the ability to parse XML or HTML source code from a + * string into a DOM `Document`. * * _xmldom is different from the spec in that it allows an `options` parameter, * to control the behavior._. @@ -778,11 +906,12 @@ declare module '@xmldom/xmldom' { * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization */ constructor(options?: DOMParserOptions); + /** * Parses `source` using the options in the way configured by the `DOMParserOptions` of * `this` - * `DOMParser`. If `mimeType` is `text/html` an HTML `Document` is created, otherwise an XML - * `Document` is created. + * `DOMParser`. If `mimeType` is `text/html` an HTML `Document` is created, otherwise an + * XML `Document` is created. * * __It behaves different from the description in the living standard__: * - Uses the `options` passed to the `DOMParser` constructor to modify the behavior. @@ -790,19 +919,19 @@ declare module '@xmldom/xmldom' { * `fatalError` level. * - Any `fatalError` throws a `ParseError` which prevents further processing. * - Any error thrown by `onError` is converted to a `ParseError` which prevents further - * processing - If no `Document` was created during parsing it is reported as a `fatalError`. + * processing - If no `Document` was created during parsing it is reported as a + * `fatalError`. * - * @returns The `Document` node. + * @returns + * The `Document` node. * @throws {ParseError} * for any `fatalError` or anything that is thrown by `onError` - * @throws {TypeError} for any invalid `mimeType` + * @throws {TypeError} + * for any invalid `mimeType` * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString * @see https://html.spec.whatwg.org/#dom-domparser-parsefromstring-dev */ - parseFromString( - source: string, - mimeType: MIME_TYPE - ): Document; + parseFromString(source: string, mimeType: MIME_TYPE | string): Document; } interface DOMParserOptions { @@ -815,8 +944,8 @@ declare module '@xmldom/xmldom' { */ readonly assign?: typeof Object.assign; /** - * For internal testing: The class for creating an instance for handling events from the SAX - * parser. + * For internal testing: The class for creating an instance for handling events from the + * SAX parser. * *****Warning: By configuring a faulty implementation, * the specified behavior can completely be broken*****. * @@ -832,7 +961,8 @@ declare module '@xmldom/xmldom' { * but it receives different argument types than before 0.9.0. * * @deprecated - * @throws {TypeError} If it is an object. + * @throws {TypeError} + * If it is an object. */ readonly errorHandler?: ErrorHandlerFunction; @@ -858,8 +988,8 @@ declare module '@xmldom/xmldom' { * If the provided method throws, a `ParserError` is thrown, * which prevents any further processing. * - * Be aware that many `warning`s are considered an error that prevents further processing in - * most implementations. + * Be aware that many `warning`s are considered an error that prevents further processing + * in most implementations. * * @param level * The error level as reported by the SAXParser. @@ -894,6 +1024,7 @@ declare module '@xmldom/xmldom' { * @see {@link onWarningStopParsing} */ function onErrorStopParsing(): void | never; + /** * A method that prevents any further parsing when an `error` * with any level is reported during parsing. @@ -902,5 +1033,6 @@ declare module '@xmldom/xmldom' { * @see {@link onErrorStopParsing} */ function onWarningStopParsing(): never; + // END ./lib/dom-parser.js } From c554b1dd9d98159067604a4f25071ea6f781494f Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Mon, 2 Sep 2024 21:54:58 +0200 Subject: [PATCH 08/13] fix: add NodeList and LiveNodeList - drop copied references to NoteListOf and generics - include index.d.ts into `format` script --- examples/typescript-node-es6/src/index.ts | 11 +- index.d.ts | 135 ++++++++++++++++------ lib/index.js | 1 + package.json | 2 +- 4 files changed, 112 insertions(+), 37 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index 316a8502b..ce9e646a8 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -15,6 +15,8 @@ import { XMLSerializer, Node, DocumentType, + NodeList, + LiveNodeList, } from '@xmldom/xmldom'; const failedAssertions: Error[] = []; @@ -66,6 +68,8 @@ new ParseError('message', {}, domException); assert(Node.ATTRIBUTE_NODE, 2); assert(Node.DOCUMENT_POSITION_CONTAINS, 8); +assert(new NodeList().length, 0); + const impl = new DOMImplementation(); const document = impl.createDocument(null, 'qualifiedName'); assert(document.contentType, MIME_TYPE.XML_APPLICATION); @@ -74,6 +78,8 @@ assert(document.ATTRIBUTE_NODE, 2); assert(document.DOCUMENT_POSITION_CONTAINS, 8); assert(document instanceof Node, true); assert(document instanceof Document, true); +assert(document.childNodes instanceof NodeList, true); +assert(document.getElementsByClassName('hide') instanceof LiveNodeList, true); impl.createDocument( NAMESPACE.XML, @@ -92,7 +98,10 @@ assert(impl.createHTMLDocument().type, 'html'); assert(impl.createHTMLDocument(false).childNodes.length, 0); assert(impl.createHTMLDocument('title').childNodes.length, 2); -assert(new DOMParser().parseFromString(`
`, mimeHtml).childNodes.length, 1) +assert( + new DOMParser().parseFromString(`
`, mimeHtml).childNodes.length, + 1 +); const source = ` test diff --git a/index.d.ts b/index.d.ts index 4a649c34d..0361bf1fe 100644 --- a/index.d.ts +++ b/index.d.ts @@ -100,8 +100,7 @@ declare module '@xmldom/xmldom' { /** * `image/svg+xml`, * - * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType - * registration + * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1 * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia */ @@ -357,19 +356,19 @@ declare module '@xmldom/xmldom' { * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/childNodes) */ - readonly childNodes: NodeListOf; + readonly childNodes: NodeList; /** * Returns the first child. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/firstChild) */ - readonly firstChild: ChildNode | null; + readonly firstChild: Node | null; /** * Returns the last child. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/lastChild) */ - readonly lastChild: ChildNode | null; + readonly lastChild: Node | null; /** * The local part of the qualified name of this node. */ @@ -383,7 +382,7 @@ declare module '@xmldom/xmldom' { * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/nextSibling) */ - readonly nextSibling: ChildNode | null; + readonly nextSibling: Node | null; /** * Returns a string appropriate for the type of node. * @@ -413,18 +412,18 @@ declare module '@xmldom/xmldom' { * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/previousSibling) */ - readonly previousSibling: ChildNode | null; + readonly previousSibling: Node | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/appendChild) */ - appendChild(node: T): T; + appendChild(node: Node): Node; /** * Returns a copy of node. If deep is true, the copy also includes the node's descendants. * * @throws {DOMException} * May throw a DOMException if operations within {@link Element#setAttributeNode} or - * {@link Node#appendChild} (which are potentially invoked in this method) do not meet - * their specific constraints. + * {@link Node#appendChild} (which are potentially invoked in this method) do not meet their + * specific constraints. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/cloneNode) */ @@ -445,7 +444,7 @@ declare module '@xmldom/xmldom' { hasChildNodes(): boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/insertBefore) */ - insertBefore(node: T, child: Node | null): T; + insertBefore(node: Node, child: Node | null): Node; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/isDefaultNamespace) */ isDefaultNamespace(namespace: string | null): boolean; @@ -480,10 +479,10 @@ declare module '@xmldom/xmldom' { normalize(): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/removeChild) */ - removeChild(child: T): T; + removeChild(child: Node): Node; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/replaceChild) */ - replaceChild(node: Node, child: T): T; + replaceChild(node: Node, child: Node): Node; /** node is an element. */ readonly ELEMENT_NODE: 1; @@ -556,6 +555,63 @@ declare module '@xmldom/xmldom' { readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 0x20; }; + /** + * NodeList objects are collections of nodes, usually returned by properties such as + * Node.childNodes and methods such as document.querySelectorAll(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/NodeList) + */ + class NodeList implements Iterable { + /** + * Returns the number of nodes in the collection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/NodeList/length) + */ + readonly length: number; + /** + * Returns the node with index index from the collection. The nodes are sorted in tree order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/NodeList/item) + */ + item(index: number): Node | null; + /** + * Returns a string representation of the NodeList. + */ + toString(nodeFilter: (node: Node) => Node | undefined): string; + /** + * Filters the NodeList based on a predicate. + * + * @private + */ + filter(predicate: (node: Node) => boolean): Node[]; + /** + * Returns the first index at which a given node can be found in the NodeList, or -1 if it is + * not present. + * + * @private + */ + indexOf(node: Node): number; + [index: number]: Node | undefined; + + [Symbol.iterator](): Iterator; + } + + /** + * Represents a live collection of nodes that is automatically updated when its associated + * document changes. + */ + interface LiveNodeList extends NodeList {} + /** + * Represents a live collection of nodes that is automatically updated when its associated + * document changes. + */ + var LiveNodeList: { + // instanceof pre ts 5.3 + (val: unknown): val is LiveNodeList; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is LiveNodeList; + }; + interface Document extends Node { /** * The mime type of the document is determined at creation time and can not be modified. @@ -734,13 +790,24 @@ declare module '@xmldom/xmldom' { getElementById(elementId: string): HTMLElement | null; /** - * Returns a HTMLCollection of the elements in the object on which the method was invoked (a - * document or an element) that have all the classes given by classNames. The classNames - * argument is interpreted as a space-separated list of classes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getElementsByClassName) + * The `getElementsByClassName` method of `Document` interface returns an array-like object + * of all child elements which have **all** of the given class name(s). + * + * Returns an empty list if `classeNames` is an empty string or only contains HTML white + * space characters. + * + * Warning: This is a live LiveNodeList. + * Changes in the DOM will reflect in the array as the changes occur. + * If an element selected by this array no longer qualifies for the selector, + * it will automatically be removed. Be aware of this for iteration purposes. + * + * @param {string} classNames + * Is a string representing the class name(s) to match; multiple class names are separated by + * (ASCII-)whitespace. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName + * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname */ - getElementsByClassName(classNames: string): HTMLCollectionOf; + getElementsByClassName(classNames: string): LiveNodeList; /** * Returns a copy of node. If deep is true, the copy also includes the node's descendants. @@ -810,10 +877,9 @@ declare module '@xmldom/xmldom' { * @returns {Document} * The XML document. * @see {@link DOMImplementation.createHTMLDocument} - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument - * MDN - * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument - * DOM Level 2 Core (initial) + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN + * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM + * Level 2 Core (initial) * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core */ createDocument( @@ -849,8 +915,8 @@ declare module '@xmldom/xmldom' { * Returns an HTML document, that might already have a basic DOM structure. * * __It behaves slightly different from the description in the living standard__: - * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs - * are omitted) + * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs are + * omitted) * - several properties and methods are missing - Nothing related to events is implemented. * * @see {@link DOMImplementation.createDocument} @@ -883,8 +949,8 @@ declare module '@xmldom/xmldom' { // START ./lib/dom-parser.js /** - * The DOMParser interface provides the ability to parse XML or HTML source code from a - * string into a DOM `Document`. + * The DOMParser interface provides the ability to parse XML or HTML source code from a string + * into a DOM `Document`. * * _xmldom is different from the spec in that it allows an `options` parameter, * to control the behavior._. @@ -910,8 +976,8 @@ declare module '@xmldom/xmldom' { /** * Parses `source` using the options in the way configured by the `DOMParserOptions` of * `this` - * `DOMParser`. If `mimeType` is `text/html` an HTML `Document` is created, otherwise an - * XML `Document` is created. + * `DOMParser`. If `mimeType` is `text/html` an HTML `Document` is created, otherwise an XML + * `Document` is created. * * __It behaves different from the description in the living standard__: * - Uses the `options` passed to the `DOMParser` constructor to modify the behavior. @@ -919,8 +985,7 @@ declare module '@xmldom/xmldom' { * `fatalError` level. * - Any `fatalError` throws a `ParseError` which prevents further processing. * - Any error thrown by `onError` is converted to a `ParseError` which prevents further - * processing - If no `Document` was created during parsing it is reported as a - * `fatalError`. + * processing - If no `Document` was created during parsing it is reported as a `fatalError`. * * @returns * The `Document` node. @@ -944,8 +1009,8 @@ declare module '@xmldom/xmldom' { */ readonly assign?: typeof Object.assign; /** - * For internal testing: The class for creating an instance for handling events from the - * SAX parser. + * For internal testing: The class for creating an instance for handling events from the SAX + * parser. * *****Warning: By configuring a faulty implementation, * the specified behavior can completely be broken*****. * @@ -988,8 +1053,8 @@ declare module '@xmldom/xmldom' { * If the provided method throws, a `ParserError` is thrown, * which prevents any further processing. * - * Be aware that many `warning`s are considered an error that prevents further processing - * in most implementations. + * Be aware that many `warning`s are considered an error that prevents further processing in + * most implementations. * * @param level * The error level as reported by the SAXParser. diff --git a/lib/index.js b/lib/index.js index 3c4b29fa1..663de9623 100644 --- a/lib/index.js +++ b/lib/index.js @@ -25,6 +25,7 @@ exports.DocumentType = dom.DocumentType; exports.Element = dom.Element; exports.EntityReference = dom.EntityReference; exports.Entity = dom.Entity; +exports.LiveNodeList = dom.LiveNodeList; exports.NamedNodeMap = dom.NamedNodeMap; exports.Node = dom.Node; exports.NodeList = dom.NodeList; diff --git a/package.json b/package.json index 6e0422b14..463398d6f 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ ], "scripts": { "lint": "eslint examples lib test", - "format": "prettier --write examples lib test", + "format": "prettier --write examples lib test index.d.ts", "changelog": "auto-changelog --unreleased-only", "start": "nodemon --watch package.json --watch lib --watch test --exec 'npm --silent run test && npm --silent run lint'", "test": "jest", From 244cc715034ebf05c6abf7c8d44a7201d1336b74 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Tue, 3 Sep 2024 07:26:32 +0200 Subject: [PATCH 09/13] fix: add Attr and use Element instead of HtmlElement --- examples/typescript-node-es6/src/index.ts | 20 +++++++---- index.d.ts | 43 +++++++++++++++++++++-- 2 files changed, 53 insertions(+), 10 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index ce9e646a8..40440b0cc 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -1,23 +1,24 @@ import { + Attr, Document, - DOMImplementation, + DocumentType, DOMException, DOMExceptionName, + DOMImplementation, DOMParser, ExceptionCode, hasDefaultHTMLNamespace, isHTMLMimeType, isValidMimeType, + LiveNodeList, MIME_TYPE, NAMESPACE, - onWarningStopParsing, - ParseError, - XMLSerializer, Node, - DocumentType, NodeList, - LiveNodeList, -} from '@xmldom/xmldom'; + onWarningStopParsing, + ParseError, + XMLSerializer +} from "@xmldom/xmldom"; const failedAssertions: Error[] = []; let assertions = 0; @@ -81,6 +82,11 @@ assert(document instanceof Document, true); assert(document.childNodes instanceof NodeList, true); assert(document.getElementsByClassName('hide') instanceof LiveNodeList, true); +const attr = document.createAttribute('attr') +assert(attr.ownerDocument, document); +assert(attr.value, undefined); +assert(attr instanceof Attr, true); + impl.createDocument( NAMESPACE.XML, 'qualifiedName', diff --git a/index.d.ts b/index.d.ts index 0361bf1fe..cd7fb55a9 100644 --- a/index.d.ts +++ b/index.d.ts @@ -555,6 +555,43 @@ declare module '@xmldom/xmldom' { readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 0x20; }; + + /** + * A DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr) + */ + interface Attr extends Node { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/namespaceURI) */ + readonly namespaceURI: string | null; + readonly ownerDocument: Document; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/ownerElement) */ + readonly ownerElement: Element | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/prefix) */ + readonly prefix: string | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/specified) + */ + readonly specified: true; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/value) */ + value: string; + } + /** + * A DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr) + */ + var Attr: { + // instanceof pre ts 5.3 + (val: unknown): val is Attr; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is Attr; + }; + /** * NodeList objects are collections of nodes, usually returned by properties such as * Node.childNodes and methods such as document.querySelectorAll(). @@ -699,7 +736,7 @@ declare module '@xmldom/xmldom' { createElement( tagName: string, options?: ElementCreationOptions - ): HTMLElement; + ): Element; /** * Returns an element with namespace namespace. Its namespace prefix will be everything before @@ -724,7 +761,7 @@ declare module '@xmldom/xmldom' { createElementNS( namespaceURI: 'http://www.w3.org/1999/xhtml', qualifiedName: string - ): HTMLElement; + ): Element; createElementNS( namespaceURI: 'http://www.w3.org/2000/svg', @@ -787,7 +824,7 @@ declare module '@xmldom/xmldom' { * @param elementId * String that specifies the ID value. */ - getElementById(elementId: string): HTMLElement | null; + getElementById(elementId: string): Element | null; /** * The `getElementsByClassName` method of `Document` interface returns an array-like object From fe36bd45ce3eb8c9b08d63ad61bc95a701bd65c6 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Wed, 4 Sep 2024 06:35:01 +0200 Subject: [PATCH 10/13] fix: add NamedNodeMap and Element and missing `Document.getElementsByTagName/-NS` --- examples/typescript-node-es6/src/index.ts | 13 +- index.d.ts | 298 +++++++++++++++++++++- 2 files changed, 302 insertions(+), 9 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index 40440b0cc..3bc8b7a1d 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -12,13 +12,14 @@ import { isValidMimeType, LiveNodeList, MIME_TYPE, + NamedNodeMap, NAMESPACE, Node, NodeList, onWarningStopParsing, ParseError, - XMLSerializer -} from "@xmldom/xmldom"; + XMLSerializer, +} from '@xmldom/xmldom'; const failedAssertions: Error[] = []; let assertions = 0; @@ -82,11 +83,17 @@ assert(document instanceof Document, true); assert(document.childNodes instanceof NodeList, true); assert(document.getElementsByClassName('hide') instanceof LiveNodeList, true); -const attr = document.createAttribute('attr') +const attr = document.createAttribute('attr'); +assert(attr.nodeType, Node.ATTRIBUTE_NODE); assert(attr.ownerDocument, document); assert(attr.value, undefined); assert(attr instanceof Attr, true); +const element = document.createElement('a'); +assert(element.nodeType, Node.ELEMENT_NODE); +assert(element.ownerDocument, document); +assert(element.attributes instanceof NamedNodeMap, true); + impl.createDocument( NAMESPACE.XML, 'qualifiedName', diff --git a/index.d.ts b/index.d.ts index cd7fb55a9..1d656b9ea 100644 --- a/index.d.ts +++ b/index.d.ts @@ -555,13 +555,13 @@ declare module '@xmldom/xmldom' { readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 0x20; }; - /** * A DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr) */ interface Attr extends Node { + readonly nodeType: typeof Node.ATTRIBUTE_NODE; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/name) */ readonly name: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/namespaceURI) */ @@ -573,7 +573,6 @@ declare module '@xmldom/xmldom' { readonly prefix: string | null; /** * @deprecated - * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/specified) */ readonly specified: true; @@ -592,6 +591,119 @@ declare module '@xmldom/xmldom' { [Symbol.hasInstance](val: unknown): val is Attr; }; + /** + * Objects implementing the NamedNodeMap interface are used to represent collections of nodes + * that can be accessed by name. + * Note that NamedNodeMap does not inherit from NodeList; + * NamedNodeMaps are not maintained in any particular order. + * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal + * index, + * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, + * and does not imply that the DOM specifies an order to these Nodes. + * NamedNodeMap objects in the DOM are live. + * used for attributes or DocumentType entities + * + * This implementation only supports property indices, but does not support named properties, + * as specified in the living standard. + * + * @see https://dom.spec.whatwg.org/#interface-namednodemap + * @see https://webidl.spec.whatwg.org/#dfn-supported-property-names + */ + class NamedNodeMap implements Iterable { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/NamedNodeMap/length) */ + readonly length: number; + /** + * Get an attribute by name. Note: Name is in lower case in case of HTML namespace and + * document. + * + * @param {string} localName + * The local name of the attribute. + * @returns {Attr | null} + * The attribute with the given local name, or null if no such attribute exists. + * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name + */ + getNamedItem(qualifiedName: string): Attr | null; + /** + * Get an attribute by namespace and local name. + * + * @param {string | null} namespaceURI + * The namespace URI of the attribute. + * @param {string} localName + * The local name of the attribute. + * @returns {Attr | null} + * The attribute with the given namespace URI and local name, or null if no such attribute + * exists. + * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace + */ + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/NamedNodeMap/item) */ + item(index: number): Attr | null; + + /** + * Removes an attribute specified by the local name. + * + * @param {string} localName + * The local name of the attribute to be removed. + * @returns {Attr} + * The attribute node that was removed. + * @throws {DOMException} + * With code: + * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given name is found. + * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem + * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name + */ + removeNamedItem(qualifiedName: string): Attr; + /** + * Removes an attribute specified by the namespace and local name. + * + * @param {string | null} namespaceURI + * The namespace URI of the attribute to be removed. + * @param {string} localName + * The local name of the attribute to be removed. + * @returns {Attr} + * The attribute node that was removed. + * @throws {DOMException} + * With code: + * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given namespace URI and + * local name is found. + * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns + * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-namespace + */ + removeNamedItemNS(namespace: string | null, localName: string): Attr; + /** + * Set an attribute. + * + * @param {Attr} attr + * The attribute to set. + * @returns {Attr | null} + * The old attribute with the same local name and namespace URI as the new one, or null if no + * such attribute exists. + * @throws {DOMException} + * With code: + * - {@link INUSE_ATTRIBUTE_ERR} - If the attribute is already an attribute of another + * element. + * @see https://dom.spec.whatwg.org/#concept-element-attributes-set + */ + setNamedItem(attr: Attr): Attr | null; + /** + * Set an attribute, replacing an existing attribute with the same local name and namespace + * URI if one exists. + * + * @param {Attr} attr + * The attribute to set. + * @returns {Attr | null} + * The old attribute with the same local name and namespace URI as the new one, or null if no + * such attribute exists. + * @throws {DOMException} + * Throws a DOMException with the name "InUseAttributeError" if the attribute is already an + * attribute of another element. + * @see https://dom.spec.whatwg.org/#concept-element-attributes-set + */ + setNamedItemNS(attr: Attr): Attr | null; + [index: number]: Attr; + [Symbol.iterator](): Iterator; + } + /** * NodeList objects are collections of nodes, usually returned by properties such as * Node.childNodes and methods such as document.querySelectorAll(). @@ -649,6 +761,145 @@ declare module '@xmldom/xmldom' { [Symbol.hasInstance](val: unknown): val is LiveNodeList; }; + /** + * Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element) + */ + interface Element extends Node { + readonly nodeType: typeof Node.ELEMENT_NODE; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/attributes) */ + readonly attributes: NamedNodeMap; + /** + * Returns element's first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttribute) + */ + getAttribute(qualifiedName: string): string | null; + /** + * Returns element's attribute whose namespace is namespace and local name is localName, and null if there is no such attribute otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNS) + */ + getAttributeNS(namespace: string | null, localName: string): string | null; + /** + * Returns the qualified names of all element's attributes. Can contain duplicates. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNames) + */ + getAttributeNames(): string[]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNode) */ + getAttributeNode(qualifiedName: string): Attr | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNodeNS) */ + getAttributeNodeNS( + namespace: string | null, + localName: string + ): Attr | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getBoundingClientRect) */ + + /** + * Returns a LiveNodeList of elements with the given qualifiedName. + * Searching for all descendants can be done by passing `*` as `qualifiedName`. + * + * All descendants of the specified element are searched, but not the element itself. + * The returned list is live, which means it updates itself with the DOM tree automatically. + * Therefore, there is no need to call `Element.getElementsByTagName()` + * with the same element and arguments repeatedly if the DOM changes in between calls. + * + * When called on an HTML element in an HTML document, + * `getElementsByTagName` lower-cases the argument before searching for it. + * This is undesirable when trying to match camel-cased SVG elements (such as + * ``) in an HTML document. + * Instead, use `Element.getElementsByTagNameNS()`, + * which preserves the capitalization of the tag name. + * + * `Element.getElementsByTagName` is similar to `Document.getElementsByTagName()`, + * except that it only searches for elements that are descendants of the specified element. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName + * @see https://dom.spec.whatwg.org/#concept-getelementsbytagname + */ + getElementsByTagName(qualifiedName: string): LiveNodeList; + + /** + * Returns a `LiveNodeList` of elements with the given tag name belonging to the given namespace. + * It is similar to `Document.getElementsByTagNameNS`, + * except that its search is restricted to descendants of the specified element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getElementsByTagNameNS) + * */ + getElementsByTagNameNS( + namespaceURI: string | null, + localName: string + ): LiveNodeList; + + getQualifiedName(): string; + /** + * Returns true if element has an attribute whose qualified name is qualifiedName, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasAttribute) + */ + hasAttribute(qualifiedName: string): boolean; + /** + * Returns true if element has an attribute whose namespace is namespace and local name is localName. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasAttributeNS) + */ + hasAttributeNS(namespace: string | null, localName: string): boolean; + /** + * Returns true if element has attributes, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasAttributes) + */ + hasAttributes(): boolean; + /** + * Removes element's first attribute whose qualified name is qualifiedName. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/removeAttribute) + */ + removeAttribute(qualifiedName: string): void; + /** + * Removes element's attribute whose namespace is namespace and local name is localName. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/removeAttributeNS) + */ + removeAttributeNS(namespace: string | null, localName: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/removeAttributeNode) */ + removeAttributeNode(attr: Attr): Attr; + /** + * Sets the value of element's first attribute whose qualified name is qualifiedName to value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttribute) + */ + setAttribute(qualifiedName: string, value: string): void; + /** + * Sets the value of element's attribute whose namespace is namespace and local name is localName to value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttributeNS) + */ + setAttributeNS( + namespace: string | null, + qualifiedName: string, + value: string + ): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttributeNode) */ + setAttributeNode(attr: Attr): Attr | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttributeNodeNS) */ + setAttributeNodeNS(attr: Attr): Attr | null; + } + /** + * Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element) + */ + var Element: { + // instanceof pre ts 5.3 + (val: unknown): val is Element; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is Element; + }; + interface Document extends Node { /** * The mime type of the document is determined at creation time and can not be modified. @@ -733,10 +984,7 @@ declare module '@xmldom/xmldom' { options?: ElementCreationOptions ): HTMLElementDeprecatedTagNameMap[K]; - createElement( - tagName: string, - options?: ElementCreationOptions - ): Element; + createElement(tagName: string, options?: ElementCreationOptions): Element; /** * Returns an element with namespace namespace. Its namespace prefix will be everything before @@ -846,6 +1094,44 @@ declare module '@xmldom/xmldom' { */ getElementsByClassName(classNames: string): LiveNodeList; + /** + * Returns a LiveNodeList of elements with the given qualifiedName. + * Searching for all descendants can be done by passing `*` as `qualifiedName`. + * + * The complete document is searched, including the root node. + * The returned list is live, which means it updates itself with the DOM tree automatically. + * Therefore, there is no need to call `Element.getElementsByTagName()` + * with the same element and arguments repeatedly if the DOM changes in between calls. + * + * When called on an HTML element in an HTML document, + * `getElementsByTagName` lower-cases the argument before searching for it. + * This is undesirable when trying to match camel-cased SVG elements (such as + * ``) in an HTML document. + * Instead, use `Element.getElementsByTagNameNS()`, + * which preserves the capitalization of the tag name. + * + * `Element.getElementsByTagName` is similar to `Document.getElementsByTagName()`, + * except that it only searches for elements that are descendants of the specified element. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName + * @see https://dom.spec.whatwg.org/#concept-getelementsbytagname + */ + getElementsByTagName(qualifiedName: string): LiveNodeList; + + /** + * Returns a `LiveNodeList` of elements with the given tag name belonging to the given namespace. + * The complete document is searched, including the root node. + * + * The returned list is live, which means it updates itself with the DOM tree automatically. + * Therefore, there is no need to call `Element.getElementsByTagName()` + * with the same element and arguments repeatedly if the DOM changes in between calls. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getElementsByTagNameNS) + * */ + getElementsByTagNameNS( + namespaceURI: string | null, + localName: string + ): LiveNodeList; /** * Returns a copy of node. If deep is true, the copy also includes the node's descendants. * From 03794563ce5c19bd1abb7b11fe1b8dece8a1e849 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Wed, 4 Sep 2024 07:06:01 +0200 Subject: [PATCH 11/13] fix: add CharacterData, Comment, CDataSection and Text --- examples/typescript-node-es6/src/index.ts | 18 +++- index.d.ts | 106 ++++++++++++++++++++++ lib/dom.js | 2 +- 3 files changed, 123 insertions(+), 3 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index 3bc8b7a1d..c552f0be0 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -1,5 +1,8 @@ import { Attr, + CDATASection, + CharacterData, + Comment, Document, DocumentType, DOMException, @@ -18,8 +21,9 @@ import { NodeList, onWarningStopParsing, ParseError, - XMLSerializer, -} from '@xmldom/xmldom'; + Text, + XMLSerializer +} from "@xmldom/xmldom"; const failedAssertions: Error[] = []; let assertions = 0; @@ -94,6 +98,16 @@ assert(element.nodeType, Node.ELEMENT_NODE); assert(element.ownerDocument, document); assert(element.attributes instanceof NamedNodeMap, true); +const cdata = document.createCDATASection('< &'); +assert(cdata instanceof CharacterData, true); +assert(cdata instanceof CDATASection, true); +const comment = document.createComment('< &'); +assert(comment instanceof CharacterData, true); +assert(comment instanceof Comment, true); +const text = document.createTextNode('text'); +assert(text instanceof CharacterData, true); +assert(text instanceof Text, true); + impl.createDocument( NAMESPACE.XML, 'qualifiedName', diff --git a/index.d.ts b/index.d.ts index 1d656b9ea..c505fd13b 100644 --- a/index.d.ts +++ b/index.d.ts @@ -900,6 +900,112 @@ declare module '@xmldom/xmldom' { [Symbol.hasInstance](val: unknown): val is Element; }; + /** + * The CharacterData abstract interface represents a Node object that contains characters. This is an abstract interface, meaning there aren't any object of type CharacterData: it is implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren't abstract. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData) + */ + interface CharacterData extends Node { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/data) */ + data: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/length) */ + readonly length: number; + readonly ownerDocument: Document; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/appendData) */ + appendData(data: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/deleteData) */ + deleteData(offset: number, count: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/insertData) */ + insertData(offset: number, data: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/replaceData) */ + replaceData(offset: number, count: number, data: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/substringData) */ + substringData(offset: number, count: number): string; + } + /** + * The CharacterData abstract interface represents a Node object that contains characters. This is an abstract interface, meaning there aren't any object of type CharacterData: it is implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren't abstract. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData) + */ + var CharacterData: { + // instanceof pre ts 5.3 + (val: unknown): val is CharacterData; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is CharacterData; + }; + + /** + * The textual content of Element or Attr. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Text) + */ + interface Text extends CharacterData { + nodeName: '#text'; + nodeType: typeof Node.TEXT_NODE; + /** + * Splits data at the given offset and returns the remainder as Text node. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Text/splitText) + */ + splitText(offset: number): Text; + } + + /** + * The textual content of Element or Attr. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Text) + */ + var Text: { + // instanceof pre ts 5.3 + (val: unknown): val is Text; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is Text; + }; + + /** + * The Comment interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. + * Comments are represented in HTML and XML as content between ''. In XML, like inside SVG or MathML markup, the character sequence '--' cannot be used within a comment. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Comment) + */ + interface Comment extends CharacterData { + nodeName: '#comment'; + nodeType: typeof Node.COMMENT_NODE; + } + /** + * The Comment interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. + * Comments are represented in HTML and XML as content between ''. In XML, like inside SVG or MathML markup, the character sequence '--' cannot be used within a comment. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Comment) + */ + var Comment: { + // instanceof pre ts 5.3 + (val: unknown): val is Comment; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is Comment; + }; + + /** + * A CDATA section that can be used within XML to include extended portions of unescaped text. The symbols < and & don’t need escaping as they normally do when inside a CDATA section. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CDATASection) + */ + interface CDATASection extends Text { + nodeName: '#cdata-section'; + nodeType: typeof Node.CDATA_SECTION_NODE; + } + /** + * A CDATA section that can be used within XML to include extended portions of unescaped text. The symbols < and & don’t need escaping as they normally do when inside a CDATA section. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CDATASection) + */ + var CDATASection: { + // instanceof pre ts 5.3 + (val: unknown): val is CDATASection; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is CDATASection; + }; + interface Document extends Node { /** * The mime type of the document is determined at creation time and can not be modified. diff --git a/lib/dom.js b/lib/dom.js index c8a6c9504..fc4ba1e58 100644 --- a/lib/dom.js +++ b/lib/dom.js @@ -2443,7 +2443,7 @@ CDATASection.prototype = { nodeName: '#cdata-section', nodeType: CDATA_SECTION_NODE, }; -_extends(CDATASection, CharacterData); +_extends(CDATASection, Text); function DocumentType(symbol) { checkSymbol(symbol); From 31436f9a89129868655896aeb4c67a5c32f7726f Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Wed, 4 Sep 2024 22:11:03 +0200 Subject: [PATCH 12/13] fix: add remaining node types --- examples/typescript-node-es6/src/index.ts | 4 +- index.d.ts | 184 ++++++++++++---------- lib/dom.js | 2 +- lib/index.js | 4 +- 4 files changed, 110 insertions(+), 84 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index c552f0be0..20248db28 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -22,8 +22,8 @@ import { onWarningStopParsing, ParseError, Text, - XMLSerializer -} from "@xmldom/xmldom"; + XMLSerializer, +} from '@xmldom/xmldom'; const failedAssertions: Error[] = []; let assertions = 0; diff --git a/index.d.ts b/index.d.ts index c505fd13b..f4ca1419c 100644 --- a/index.d.ts +++ b/index.d.ts @@ -326,6 +326,13 @@ declare module '@xmldom/xmldom' { // END ./lib/errors.js // START ./lib/dom.js + + type InstanceOf = { + // instanceof pre ts 5.3 + (val: unknown): val is T; + // instanceof post ts 5.3 + [Symbol.hasInstance](val: unknown): val is T; + }; /** * The DOM Node interface is an abstract base class upon which many other DOM API objects are * based, thus letting those object types to be used similarly and often interchangeably. As an @@ -517,11 +524,7 @@ declare module '@xmldom/xmldom' { readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 0x20; } - var Node: { - // instanceof pre ts 5.3 - (val: unknown): val is Node; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is Node; + var Node: InstanceOf & { /** node is an element. */ readonly ELEMENT_NODE: 1; readonly ATTRIBUTE_NODE: 2; @@ -556,7 +559,9 @@ declare module '@xmldom/xmldom' { }; /** - * A DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. + * A DOM element's attribute as an object. In most DOM methods, you will probably directly + * retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., + * Element.getAttributeNode()) or means of iterating give Attr types. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr) */ @@ -580,16 +585,13 @@ declare module '@xmldom/xmldom' { value: string; } /** - * A DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. + * A DOM element's attribute as an object. In most DOM methods, you will probably directly + * retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., + * Element.getAttributeNode()) or means of iterating give Attr types. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr) */ - var Attr: { - // instanceof pre ts 5.3 - (val: unknown): val is Attr; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is Attr; - }; + var Attr: InstanceOf; /** * Objects implementing the NamedNodeMap interface are used to represent collections of nodes @@ -754,15 +756,12 @@ declare module '@xmldom/xmldom' { * Represents a live collection of nodes that is automatically updated when its associated * document changes. */ - var LiveNodeList: { - // instanceof pre ts 5.3 - (val: unknown): val is LiveNodeList; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is LiveNodeList; - }; + var LiveNodeList: InstanceOf; /** - * Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. + * Element is the most general base class from which all objects in a Document inherit. It only + * has methods and properties common to all kinds of elements. More specific classes inherit from + * Element. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element) */ @@ -772,13 +771,15 @@ declare module '@xmldom/xmldom' { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/attributes) */ readonly attributes: NamedNodeMap; /** - * Returns element's first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise. + * Returns element's first attribute whose qualified name is qualifiedName, and null if there + * is no such attribute otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttribute) */ getAttribute(qualifiedName: string): string | null; /** - * Returns element's attribute whose namespace is namespace and local name is localName, and null if there is no such attribute otherwise. + * Returns element's attribute whose namespace is namespace and local name is localName, and + * null if there is no such attribute otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNS) */ @@ -823,9 +824,9 @@ declare module '@xmldom/xmldom' { getElementsByTagName(qualifiedName: string): LiveNodeList; /** - * Returns a `LiveNodeList` of elements with the given tag name belonging to the given namespace. - * It is similar to `Document.getElementsByTagNameNS`, - * except that its search is restricted to descendants of the specified element. + * Returns a `LiveNodeList` of elements with the given tag name belonging to the given + * namespace. It is similar to `Document.getElementsByTagNameNS`, except that its search is + * restricted to descendants of the specified element. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getElementsByTagNameNS) * */ @@ -836,13 +837,15 @@ declare module '@xmldom/xmldom' { getQualifiedName(): string; /** - * Returns true if element has an attribute whose qualified name is qualifiedName, and false otherwise. + * Returns true if element has an attribute whose qualified name is qualifiedName, and false + * otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasAttribute) */ hasAttribute(qualifiedName: string): boolean; /** - * Returns true if element has an attribute whose namespace is namespace and local name is localName. + * Returns true if element has an attribute whose namespace is namespace and local name is + * localName. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasAttributeNS) */ @@ -874,7 +877,8 @@ declare module '@xmldom/xmldom' { */ setAttribute(qualifiedName: string, value: string): void; /** - * Sets the value of element's attribute whose namespace is namespace and local name is localName to value. + * Sets the value of element's attribute whose namespace is namespace and local name is + * localName to value. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttributeNS) */ @@ -889,19 +893,19 @@ declare module '@xmldom/xmldom' { setAttributeNodeNS(attr: Attr): Attr | null; } /** - * Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. + * Element is the most general base class from which all objects in a Document inherit. It only + * has methods and properties common to all kinds of elements. More specific classes inherit from + * Element. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element) */ - var Element: { - // instanceof pre ts 5.3 - (val: unknown): val is Element; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is Element; - }; + var Element: InstanceOf; /** - * The CharacterData abstract interface represents a Node object that contains characters. This is an abstract interface, meaning there aren't any object of type CharacterData: it is implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren't abstract. + * The CharacterData abstract interface represents a Node object that contains characters. This + * is an abstract interface, meaning there aren't any object of type CharacterData: it is + * implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren't + * abstract. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData) */ @@ -923,7 +927,10 @@ declare module '@xmldom/xmldom' { substringData(offset: number, count: number): string; } /** - * The CharacterData abstract interface represents a Node object that contains characters. This is an abstract interface, meaning there aren't any object of type CharacterData: it is implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren't abstract. + * The CharacterData abstract interface represents a Node object that contains characters. This + * is an abstract interface, meaning there aren't any object of type CharacterData: it is + * implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren't + * abstract. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData) */ @@ -935,13 +942,15 @@ declare module '@xmldom/xmldom' { }; /** - * The textual content of Element or Attr. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. + * The textual content of Element or Attr. If an element has no markup within its content, it has + * a single child implementing Text that contains the element's text. However, if the element + * contains markup, it is parsed into information items and Text nodes that form its children. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Text) */ interface Text extends CharacterData { - nodeName: '#text'; - nodeType: typeof Node.TEXT_NODE; + nodeName: '#text' | '#cdata-section'; + nodeType: typeof Node.TEXT_NODE | typeof Node.CDATA_SECTION_NODE; /** * Splits data at the given offset and returns the remainder as Text node. * @@ -951,20 +960,19 @@ declare module '@xmldom/xmldom' { } /** - * The textual content of Element or Attr. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. + * The textual content of Element or Attr. If an element has no markup within its content, it has + * a single child implementing Text that contains the element's text. However, if the element + * contains markup, it is parsed into information items and Text nodes that form its children. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Text) */ - var Text: { - // instanceof pre ts 5.3 - (val: unknown): val is Text; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is Text; - }; + var Text: InstanceOf; /** - * The Comment interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. - * Comments are represented in HTML and XML as content between ''. In XML, like inside SVG or MathML markup, the character sequence '--' cannot be used within a comment. + * The Comment interface represents textual notations within markup; although it is generally not + * visually shown, such comments are available to be read in the source view. Comments are + * represented in HTML and XML as content between ''. In XML, like inside SVG or + * MathML markup, the character sequence '--' cannot be used within a comment. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Comment) */ @@ -973,20 +981,18 @@ declare module '@xmldom/xmldom' { nodeType: typeof Node.COMMENT_NODE; } /** - * The Comment interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. - * Comments are represented in HTML and XML as content between ''. In XML, like inside SVG or MathML markup, the character sequence '--' cannot be used within a comment. + * The Comment interface represents textual notations within markup; although it is generally not + * visually shown, such comments are available to be read in the source view. Comments are + * represented in HTML and XML as content between ''. In XML, like inside SVG or + * MathML markup, the character sequence '--' cannot be used within a comment. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Comment) */ - var Comment: { - // instanceof pre ts 5.3 - (val: unknown): val is Comment; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is Comment; - }; + var Comment: InstanceOf; /** - * A CDATA section that can be used within XML to include extended portions of unescaped text. The symbols < and & don’t need escaping as they normally do when inside a CDATA section. + * A CDATA section that can be used within XML to include extended portions of unescaped text. + * The symbols < and & don’t need escaping as they normally do when inside a CDATA section. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CDATASection) */ @@ -995,16 +1001,46 @@ declare module '@xmldom/xmldom' { nodeType: typeof Node.CDATA_SECTION_NODE; } /** - * A CDATA section that can be used within XML to include extended portions of unescaped text. The symbols < and & don’t need escaping as they normally do when inside a CDATA section. + * A CDATA section that can be used within XML to include extended portions of unescaped text. + * The symbols < and & don’t need escaping as they normally do when inside a CDATA section. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CDATASection) */ - var CDATASection: { - // instanceof pre ts 5.3 - (val: unknown): val is CDATASection; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is CDATASection; - }; + var CDATASection: InstanceOf; + + /** + * The DocumentFragment interface represents a minimal document object that has no parent. + * It is used as a lightweight version of Document that stores a segment of a document structure + * comprised of nodes just like a standard document. + * The key difference is due to the fact that the document fragment isn't part + * of the active document tree structure. + * Changes made to the fragment don't affect the document. + */ + interface DocumentFragment extends Node { + readonly ownerDocument: Document; + getElementById(elementId: string): Element | null; + } + var DocumentFragment: InstanceOf; + + interface Entity extends Node { + nodeType: typeof Node.ENTITY_NODE; + } + var Entity: InstanceOf; + + interface EntityReference extends Node { + nodeType: typeof Node.ENTITY_REFERENCE_NODE; + } + var EntityReference: InstanceOf; + + interface Notation extends Node { + nodeType: typeof Node.NOTATION_NODE; + } + var Notation: InstanceOf; + + interface ProcessingInstruction extends Node { + nodeType: typeof Node.PROCESSING_INSTRUCTION_NODE; + } + var ProcessingInstruction: InstanceOf; interface Document extends Node { /** @@ -1225,8 +1261,8 @@ declare module '@xmldom/xmldom' { getElementsByTagName(qualifiedName: string): LiveNodeList; /** - * Returns a `LiveNodeList` of elements with the given tag name belonging to the given namespace. - * The complete document is searched, including the root node. + * Returns a `LiveNodeList` of elements with the given tag name belonging to the given + * namespace. The complete document is searched, including the root node. * * The returned list is live, which means it updates itself with the DOM tree automatically. * Therefore, there is no need to call `Element.getElementsByTagName()` @@ -1248,12 +1284,7 @@ declare module '@xmldom/xmldom' { importNode(node: T, deep?: boolean): T; } - var Document: { - // instanceof pre ts 5.3 - (val: unknown): val is Document; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is Document; - }; + var Document: InstanceOf; /** * A Node containing a doctype. @@ -1270,12 +1301,7 @@ declare module '@xmldom/xmldom' { readonly systemId: string; } - var DocumentType: { - // instanceof pre ts 5.3 - (val: unknown): val is DocumentType; - // instanceof post ts 5.3 - [Symbol.hasInstance](val: unknown): val is DocumentType; - }; + var DocumentType: InstanceOf; class DOMImplementation { /** diff --git a/lib/dom.js b/lib/dom.js index fc4ba1e58..d9a42f79c 100644 --- a/lib/dom.js +++ b/lib/dom.js @@ -2920,5 +2920,5 @@ exports.Node = Node; exports.NodeList = NodeList; exports.Notation = Notation; exports.Text = Text; -exports.XMLSerializer = XMLSerializer; exports.ProcessingInstruction = ProcessingInstruction; +exports.XMLSerializer = XMLSerializer; diff --git a/lib/index.js b/lib/index.js index 663de9623..d480e73e5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -14,7 +14,6 @@ exports.ExceptionCode = errors.ExceptionCode; exports.ParseError = errors.ParseError; var dom = require('./dom'); -exports.DOMImplementation = dom.DOMImplementation; exports.Attr = dom.Attr; exports.CDATASection = dom.CDATASection; exports.CharacterData = dom.CharacterData; @@ -22,9 +21,10 @@ exports.Comment = dom.Comment; exports.Document = dom.Document; exports.DocumentFragment = dom.DocumentFragment; exports.DocumentType = dom.DocumentType; +exports.DOMImplementation = dom.DOMImplementation; exports.Element = dom.Element; -exports.EntityReference = dom.EntityReference; exports.Entity = dom.Entity; +exports.EntityReference = dom.EntityReference; exports.LiveNodeList = dom.LiveNodeList; exports.NamedNodeMap = dom.NamedNodeMap; exports.Node = dom.Node; From 3b5af22e8509b71992d435bcc13f4cccd9b9a152 Mon Sep 17 00:00:00 2001 From: Christian Bewernitz Date: Wed, 4 Sep 2024 22:58:43 +0200 Subject: [PATCH 13/13] fix: only use existing parameters and types tested locally using https://github.com/amacneil/xmldom-types-repro/tree/main/2-new-import --- examples/typescript-node-es6/src/index.ts | 32 ++++++------- index.d.ts | 56 +---------------------- 2 files changed, 18 insertions(+), 70 deletions(-) diff --git a/examples/typescript-node-es6/src/index.ts b/examples/typescript-node-es6/src/index.ts index 20248db28..b497e4e6b 100644 --- a/examples/typescript-node-es6/src/index.ts +++ b/examples/typescript-node-es6/src/index.ts @@ -77,34 +77,34 @@ assert(Node.DOCUMENT_POSITION_CONTAINS, 8); assert(new NodeList().length, 0); const impl = new DOMImplementation(); -const document = impl.createDocument(null, 'qualifiedName'); -assert(document.contentType, MIME_TYPE.XML_APPLICATION); -assert(document.type, 'xml'); -assert(document.ATTRIBUTE_NODE, 2); -assert(document.DOCUMENT_POSITION_CONTAINS, 8); -assert(document instanceof Node, true); -assert(document instanceof Document, true); -assert(document.childNodes instanceof NodeList, true); -assert(document.getElementsByClassName('hide') instanceof LiveNodeList, true); +const doc1 = impl.createDocument(null, 'qualifiedName'); +assert(doc1.contentType, MIME_TYPE.XML_APPLICATION); +assert(doc1.type, 'xml'); +assert(doc1.ATTRIBUTE_NODE, 2); +assert(doc1.DOCUMENT_POSITION_CONTAINS, 8); +assert(doc1 instanceof Node, true); +assert(doc1 instanceof Document, true); +assert(doc1.childNodes instanceof NodeList, true); +assert(doc1.getElementsByClassName('hide') instanceof LiveNodeList, true); -const attr = document.createAttribute('attr'); +const attr = doc1.createAttribute('attr'); assert(attr.nodeType, Node.ATTRIBUTE_NODE); -assert(attr.ownerDocument, document); +assert(attr.ownerDocument, doc1); assert(attr.value, undefined); assert(attr instanceof Attr, true); -const element = document.createElement('a'); +const element = doc1.createElement('a'); assert(element.nodeType, Node.ELEMENT_NODE); -assert(element.ownerDocument, document); +assert(element.ownerDocument, doc1); assert(element.attributes instanceof NamedNodeMap, true); -const cdata = document.createCDATASection('< &'); +const cdata = doc1.createCDATASection('< &'); assert(cdata instanceof CharacterData, true); assert(cdata instanceof CDATASection, true); -const comment = document.createComment('< &'); +const comment = doc1.createComment('< &'); assert(comment instanceof CharacterData, true); assert(comment instanceof Comment, true); -const text = document.createTextNode('text'); +const text = doc1.createTextNode('text'); assert(text instanceof CharacterData, true); assert(text instanceof Text, true); diff --git a/index.d.ts b/index.d.ts index f4ca1419c..2b931a0fc 100644 --- a/index.d.ts +++ b/index.d.ts @@ -409,7 +409,7 @@ declare module '@xmldom/xmldom' { * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/parentNode) */ - readonly parentNode: ParentNode | null; + readonly parentNode: Node | null; /** * The prefix of the namespace for this node. */ @@ -1105,28 +1105,8 @@ declare module '@xmldom/xmldom' { */ createDocumentFragment(): DocumentFragment; - /** - * Creates an instance of the element for the specified tag. - * - * @param tagName - * The name of an element. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElement) - */ - createElement( - tagName: K, - options?: ElementCreationOptions - ): HTMLElementTagNameMap[K]; - /** - * @deprecated - */ - createElement( - tagName: K, - options?: ElementCreationOptions - ): HTMLElementDeprecatedTagNameMap[K]; - - createElement(tagName: string, options?: ElementCreationOptions): Element; + createElement(tagName: string): Element; /** * Returns an element with namespace namespace. Its namespace prefix will be everything before @@ -1148,41 +1128,9 @@ declare module '@xmldom/xmldom' { * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElementNS) */ - createElementNS( - namespaceURI: 'http://www.w3.org/1999/xhtml', - qualifiedName: string - ): Element; - - createElementNS( - namespaceURI: 'http://www.w3.org/2000/svg', - qualifiedName: K - ): SVGElementTagNameMap[K]; - - createElementNS( - namespaceURI: 'http://www.w3.org/2000/svg', - qualifiedName: string - ): SVGElement; - - createElementNS( - namespaceURI: 'http://www.w3.org/1998/Math/MathML', - qualifiedName: K - ): MathMLElementTagNameMap[K]; - - createElementNS( - namespaceURI: 'http://www.w3.org/1998/Math/MathML', - qualifiedName: string - ): MathMLElement; - - createElementNS( - namespaceURI: string | null, - qualifiedName: string, - options?: ElementCreationOptions - ): Element; - createElementNS( namespace: string | null, qualifiedName: string, - options?: string | ElementCreationOptions ): Element; /**