All files / lib/dom domParser.ts

90% Statements 126/140
82% Branches 82/100
100% Functions 30/30
95.45% Lines 126/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 41726x 26x                                                                         26x 26x         26x                                 115x     115x     115x                   120x     120x 120x     120x                     115x           115x 22x     115x           26x                                 118x 118x               122x       121x 121x       1x         426x     426x 426x 314x 314x 314x       426x   426x       424x         577x     577x         17x     17x         11x     11x     11x       11x         20x     20x                 437x     437x             435x       435x                   426x   36x   11x   8x   15x   16x   8x   22x   5x   4x   9x   1x   25x   15x   1x   6x   244x         36x 36x 36x       19x 19x     26x 11x 11x     26x 8x 8x       8x 8x     8x 8x   5x 5x     5x     5x     8x       22x 22x 22x       5x 5x 5x       9x 9x   9x 9x 9x   9x 5x 4x 4x             1x 1x 1x 1x         25x     25x 18x       7x 7x       7x   7x 7x 3x   4x           15x 2x       13x 13x 8x   5x           1x       1x 1x 1x   1x         6x 6x       6x    
import { Handler, Parser, ParserOptions } from 'htmlparser2/lib/Parser';
import {
    DocumentNode,
    NodeWithChildren,
    TagNode,
    TextNode,
    CommentNode,
    CDATANode,
    ProcessingInstructionNode,
    MVarNode,
    MFragmentNode,
    MSlotNode,
    MContentNode,
    MImportNode,
    MIfNode,
    MScopeNode,
    MForNode,
    MForOfNode,
    MForInNode,
    MElseNode,
    MElseIfNode,
    MDataNode,
    ExternalStyleNode,
    InternalStyleNode,
    StyleNodeBind,
    StyleNode,
    ScriptNode,
    ExternalScriptNode,
    InternalScriptNode,
    UncompiledScriptNode,
    UncompiledStyleNode,
    AnchorNode,
    UncompiledAnchorNode,
    CompiledAnchorNode,
    parseAnchorNodeResolve,
    MWhitespaceNode,
    MWhitespaceNodeMode
} from './node';
import {MimeType} from '..';
import {convertCamelCaseToSnakeCase} from '../util/caseUtils';
 
/**
 * Parses HTML into a dom using htmlparser2
 */
export class DomParser {
    /**
     * DomHandler instance that receives callbacks from {@link parser}
     */
    private readonly handler: DomHandler;
 
    /**
     * HTML parser instance
     */
    private readonly parser: Parser;
 
    /**
     * Creates a new DomParser instance
     * @param userOptions Optional options to pass to htmlparser2
     */
    constructor(userOptions?: ParserOptions) {
        // get parser options
        const options = createParserOptions(userOptions);
 
        // set up handler
        this.handler = new DomHandler();
 
        // create parser
        this.parser = new Parser(this.handler, options);
    }
 
    /**
     * Parse a string of HTML into a DOM
     * @param html HTML to parse
     * @returns a DocumentNode containing parsed HTML
     */
    parseDom(html: string): DocumentNode {
        // reset parser
        this.parser.reset();
 
        // process html
        this.parser.write(html);
        this.parser.end();
 
        // get generated dom
        return this.handler.getDom();
    }
}
 
/**
 * Creates an instance of ParserOptions.
 * Loads defaults and optionally overrides with a provided instance
 * @param userOptions optional options to include
 */
function createParserOptions(userOptions?: ParserOptions): ParserOptions {
    // base (default) options
    const options: ParserOptions = {
        recognizeSelfClosing: true,
        lowerCaseTags: true
    };
 
    // load user-supplied options
    if (userOptions !== undefined) {
        Object.assign(options, userOptions);
    }
 
    return options;
}
 
/**
 * Implementation of htmlparser2's Handler interface that generates a DOM from the parsed HTML.
 */
export class DomHandler implements Partial<Handler> {
    /**
     * DOM containing parsed nodes
     */
    private dom: DocumentNode;
 
    /**
     * Current parent node.
     * The next incoming node will be attached as a child to this node
     */
    private currentParent: NodeWithChildren;
 
    /**
     * Creates a new DomHandler.
     * The instance will be fully initialized and ready to begin receiving callbacks from htmlparser2
     */
    constructor() {
        this.dom = new DocumentNode();
        this.currentParent = this.dom;
    }
 
    /**
     * Gets the generated DOM in its current state
     * @returns a DocumentNode containing all parsed HTML
     */
    getDom(): DocumentNode {
        return this.dom;
    }
 
    onreset(): void {
        this.dom = new DocumentNode();
        this.currentParent = this.dom;
    }
 
    onerror(error: Error): void {
        throw error;
    }
 
    onopentag(name: string, attribs: { [s: string]: string }): void {
        // normalize tag name
        const tagName = name.toLowerCase();
 
        // copy attribs
        const attributes = new Map<string, string | null>();
        for (const key of Object.keys(attribs)) {
            const attrVal = attribs[key];
            const value: string | null = attrVal.length > 0 ? attrVal : null;
            attributes.set(key, value);
        }
 
        // create tag
        const tag: TagNode = DomHandler.createTagNode(tagName, attributes);
 
        this.pushParent(tag);
    }
 
    onclosetag(): void {
        this.popParent();
    }
 
    ontext(data: string): void {
        // create text node
        const textNode = new TextNode(data);
 
        // append to parent
        this.currentParent.appendChild(textNode);
    }
 
    oncomment(data: string): void {
        // create comment node
        const commentNode = new CommentNode(data);
 
        // append to parent
        this.currentParent.appendChild(commentNode);
    }
 
    oncdatastart(): void {
        // create cdata node
        const cdataNode = new CDATANode();
 
        // append to parent
        this.currentParent.appendChild(cdataNode);
 
        // set as parent
        this.pushParent(cdataNode);
    }
 
    oncdataend(): void {
        this.popParent();
    }
    
    onprocessinginstruction(name: string, data: string): void {
        // create node
        const piNode = new ProcessingInstructionNode(name, data);
 
        // append to parent
        this.currentParent.appendChild(piNode);
    }
 
    /**
     * Attaches a node to the current parent, and then sets the new node as the current parent.
     * @param node Node to attach
     */
    private pushParent(node: NodeWithChildren): void {
        // attach to parent
        this.currentParent.appendChild(node);
 
        // push node
        this.currentParent = node;
    }
 
    /**
     * "closes" the current parent and sets its parent as the current
     */
    private popParent(): void {
        Iif (this.currentParent === this.dom) {
            throw new Error('Tried to close too many tags: DOM is currentParent');
        }
        
        this.currentParent = this.currentParent.parentNode ?? this.dom;
    }
 
    /**
     * Creates an instance of TagNode or one of its subclasses based on the provided tag data.
     * @param tagName Name of the tag to create
     * @param attributes Tag attributes
     * @returns Instance of TagNode or a subclass
     */
    private static createTagNode(tagName: string, attributes: Map<string, string | null>): TagNode {
        switch (tagName) {
            case 'm-fragment':
                return DomHandler.createMFragmentNode(attributes);
            case 'm-slot':
                return DomHandler.createMSlotNode(attributes);
            case 'm-content':
                return DomHandler.createMContentNode(attributes);
            case 'm-var':
                return new MVarNode(attributes);
            case 'm-scope':
                return new MScopeNode(attributes);
            case 'm-import':
                return DomHandler.createMImportNode(attributes);
            case 'm-if':
                return DomHandler.createMIfNode(attributes);
            case 'm-else-if':
                return DomHandler.createMElseIfNode(attributes);
            case 'm-else':
                return new MElseNode(attributes);
            case 'm-for':
                return DomHandler.createMForNode(attributes);
            case 'm-data':
                return DomHandler.createMDataNode(attributes);
            case 'style':
                return DomHandler.createStyleNode(attributes);
            case 'script':
                return DomHandler.createScriptNode(attributes);
            case 'a':
                return DomHandler.createAnchorNode(attributes);
            case 'm-whitespace':
                return DomHandler.createMWhitespaceNode(attributes);
            default:
                return new TagNode(tagName, attributes);
        }
    }
 
    private static createMFragmentNode(attributes: Map<string, string | null>): MFragmentNode {
        const src = attributes.get('src');
        Iif (src === undefined || src === null) throw new Error('Parse error: <m-fragment> is missing required attribute: src');
        return new MFragmentNode(src, attributes);
    }
 
    private static getSlotAttribute(attributes: Map<string, string | null>): string | undefined {
        const slot = attributes.get('slot');
        return slot !== undefined ? String(slot) : undefined;
    }
 
    private static createMSlotNode = (attributes: Map<string, string | null>): MSlotNode => {
        const slot = DomHandler.getSlotAttribute(attributes);
        return new MSlotNode(slot, attributes);
    };
 
    private static createMContentNode = (attributes: Map<string, string | null>): MContentNode => {
        const slot = DomHandler.getSlotAttribute(attributes);
        return new MContentNode(slot, attributes);
    };
 
    private static createMImportNode(attributes: Map<string, string | null>): MImportNode {
        const src = attributes.get('src');
        Iif (src === undefined || src === null) throw new Error('Parse error: <m-import> is missing required attribute: src');
        
        // default "as" if not specified
        let as = attributes.get('as');
        if (as === undefined || as === null) {
            // extract file name (find the section of text between the last slash or start-of-input and the next period or end of input).
            const srcFileNameMatch = src.match(/([\\/]|^)([^\\/\r\n.]+)[^\\/\r\n]*$/);
            Iif (srcFileNameMatch === null) {
                throw new Error(`Parse error: attribute 'as' not specified for <m-import>, and it could not be inferred from the value of "src"`);
            }
            const srcFileName = srcFileNameMatch[2].trim();
            
            // convert to attribute case and use as "as"
            as = convertCamelCaseToSnakeCase(srcFileName);
        }
        
        return new MImportNode(src, as, attributes);
    }
 
    private static createMIfNode(attributes: Map<string, string | null>): MIfNode {
        const expression = attributes.get('?');
        Iif (expression === undefined) throw new Error('Parse error: <m-if> is missing required attribute: ?');
        return new MIfNode(expression, attributes);
    }
 
    private static createMElseIfNode(attributes: Map<string, string | null>): MElseIfNode {
        const expression = attributes.get('?');
        Iif (expression === undefined) throw new Error('Parse error: <m-else-if> is missing required attribute: ?');
        return new MElseIfNode(expression, attributes);
    }
 
    private static createMForNode(attributes: Map<string, string | null>): MForNode {
        const varName = attributes.get('var');
        Iif (varName === undefined || varName === null) throw new Error('Parse error: <m-for> is missing required attribute: varName');
 
        const indexName = attributes.get('index') ?? undefined;
        const ofExpression = attributes.get('of') ?? undefined;
        const inExpression = attributes.get('in') ?? undefined;
 
        if (ofExpression !== undefined && inExpression === undefined) {
            return new MForOfNode(ofExpression, varName, indexName, attributes);
        } else Eif (inExpression !== undefined && ofExpression === undefined) {
            return new MForInNode(inExpression, varName, indexName, attributes);
        } else {
            throw new Error('Parse error: <m-for> must have exactly one of these attributes: [of,in]');
        }
    }
 
    private static createMDataNode(attributes: Map<string, string | null>): MDataNode {
        const type = attributes.get('type');
        Iif (type === undefined) throw new Error('Parse error: <m-data> is missing required attribute: type');
        Iif (type !== MimeType.JSON && type !== MimeType.TEXT) throw new Error(`Parse error: <m-data> has invalid value for attribute 'type': '${ type }'`);
        return new MDataNode(type, attributes);
    }
 
    private static createStyleNode(attributes: Map<string, string | null>): StyleNode {
        // Get lang
        const lang = attributes.get('lang') ?? undefined;
 
        // "uncompiled" style nodes should be passed on as-is
        if (!attributes.has('compiled')) {
            return new UncompiledStyleNode(lang, attributes);
        }
 
        // "compiled" style nodes need further processing
        const bind = attributes.get('bind') ?? undefined;
        Iif (bind !== undefined && bind !== StyleNodeBind.HEAD && bind !== StyleNodeBind.LINK) {
            throw new Error(`Parse error: 'style' tag has invalid value for attribute 'bind': '${ bind }'`);
        }
 
        const skipFormat = attributes.has('skip-format');
 
        const src = attributes.get('src');
        if (src) {
            return new ExternalStyleNode(src, bind, skipFormat, lang, attributes);
        } else {
            return new InternalStyleNode(bind, skipFormat, lang, attributes);
        }
    }
 
    private static createScriptNode(attributes: Map<string, string | null>): ScriptNode {
        // "uncompiled" script nodes should be passed on as-is
        if (!attributes.has('compiled')) {
            return new UncompiledScriptNode(attributes);
        }
 
        // "compiled" script nodes need further processing
        const src = attributes.get('src');
        if (src) {
            return new ExternalScriptNode(src, attributes);
        } else {
            return new InternalScriptNode(attributes);
        }
    }
 
    private static createAnchorNode(attributes: Map<string, string | null>): AnchorNode {
        // "uncompiled" anchor nodes should be passed on as-is
        Iif (!attributes.has('compiled')) {
            return new UncompiledAnchorNode(attributes);
        }
 
        const href = attributes.get('href');
        Iif (href === undefined || href === null) throw new Error('Parse error: <a> is missing required attribute: href');
        const resolve = parseAnchorNodeResolve(attributes.get('resolve') ?? undefined);
 
        return new CompiledAnchorNode(href, resolve, attributes);
    }
 
    private static createMWhitespaceNode(attributes: Map<string, string | null>): MWhitespaceNode {
        // parse mode
        const mode = attributes.get('mode') ?? undefined;
        Iif (mode !== undefined && mode !== MWhitespaceNodeMode.SENSITIVE && mode !== MWhitespaceNodeMode.INSENSITIVE) {
            throw new Error(`Parse error: 'm-whitespace' tag has invalid value for attribute 'bind': '${ mode }'`);
        }
 
        return new MWhitespaceNode(mode, attributes);
    }
}