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 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 564x 2x 2x 562x 562x 564x 498x 498x 64x 64x 64x 64x 564x 172x 172x 172x 172x 172x 172x 172x 172x 54x 54x 1x 1x 54x 54x 54x 53x 53x 53x 54x 9x 9x 54x 54x 54x 54x 11x 10x 10x 172x 64x 64x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1240x 1240x 1240x 1240x 1240x 18x 18x 18x 18x 18x 18x 18x 1240x 1240x 1240x 1240x 1240x 1240x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 38x 38x 38x 38x 38x 120x 120x 120x 120x 120x 120x 120x 120x 120x 42x 42x 42x 42x 42x 42x 42x 6x 6x 42x 42x 7x 4x 4x 7x 7x 2x 2x 7x 7x 29x 28x 28x 28x 42x 9x 9x 7x 7x 9x 9x 9x 9x 120x 38x 260x 260x 260x 3x 3x 3x 1x 1x 3x 3x 3x 3x 257x 257x 257x 257x 257x 257x 257x 257x 298x 1220x 1240x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 800x 219x 219x 219x 800x 800x 682x 682x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 800x 799x 799x 799x 1x 1x 1x 1x 1x 1x 799x 799x 1x 1x 1x 1x 1x 1x 799x 800x 800x 800x 800x 32x 32x 32x 800x 800x 800x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 1483x 347x 347x 347x 347x 347x 347x 1483x 2230x 2230x 2230x 2230x 73x 73x 73x 71x 71x 73x 2230x 2230x 2230x 2230x 2230x 8x 8x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 2230x 1222x 1222x 13x 1x 1x 1x 13x 1222x 1222x 1222x 1222x 1222x 1222x 1222x 1222x 1222x 1222x 1222x 77x 77x 77x 77x 77x 77x 10x 10x 10x 10x 10x 2x 2x 2x 2x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 77x 67x 77x 50x 1x 1x 49x 49x 49x 49x 49x 50x 50x 50x 50x 77x 1222x 2230x 2230x 1198x 1197x 1197x 1198x 1198x 1198x 1201x 1201x 11x 11x 11x 11x 11x 1201x 1201x 4x 2x 2x 2x 2x 2x 4x 1188x 1201x 1180x 1180x 1180x 1180x 1180x 1201x 1201x 1201x 1201x 1201x 4x 3x 3x 3x 3x 3x 4x 5x 5x 5x 5x 1201x 1198x 2230x 800x 800x 800x 800x 800x 753x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 753x 800x 800x 800x 800x 64x 64x 752x 752x 752x 800x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 25x 25x 11x 11x 11x 11x 11x 25x 25x 4x 3x 3x 4x 11x 11x 11x 11x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 7x 7x 7x 7x 7x 7x 11x 11x 11x 7x 7x 7x 7x 7x 7x 7x 7x 7x 11x 11x 11x 11x 11x 800x 800x 800x | // Adapted implementation from: // https://github.com/ashi009/node-fast-html-parser import createTree from '../tree/create'; import getConfig from './config'; import process from './process'; import { VTree, Supplemental, TransactionConfig, ParserConfig, EMPTY, NODE_TYPE } from './types'; // Magic token used for interpolation. export const TOKEN = '__DIFFHTML__'; const doctypeEx = /<!DOCTYPE.*>/i; const spaceEx = /[^ ]/; const tokenEx = new RegExp(`${TOKEN}([^_]*)__`); /** @type {Supplemental} */ const defaultSupplemental = { tags: [], attributes: {}, children: {}, } const { assign } = Object; const { isArray } = Array; const rawElementsDefaults = [ 'script', 'noscript', 'style', 'template', ]; const selfClosingElementsDefaults = [ 'source', 'embed', 'param', 'track', 'input', 'meta', 'link', 'area', 'base', 'col', 'wbr', 'img', 'br', 'hr', ]; /** @type {any} */ const kElementsClosedByOpening = { li: { li: true }, p: { p: true, div: true }, td: { td: true, th: true }, th: { td: true, th: true }, }; /** @type {any} */ const kElementsClosedByClosing = { li: { ul: true, ol: true }, a: { div: true }, b: { div: true }, i: { div: true }, p: { div: true }, td: { tr: true, table: true }, th: { tr: true, table: true }, }; /** * Interpolates children from dynamic supplemental values into the parent node. * * @param {VTree} currentParent - Active element VTree * @param {string} markup - Incoming partial HTML markup * @param {Supplemental} supplemental - Dynamic interpolated data values */ const interpolateChildNodes = (currentParent, markup, supplemental) => { if ('childNodes' in currentParent.attributes) { return; } // If this is text and not a doctype, add as a text node. if (markup && !doctypeEx.test(markup) && !tokenEx.test(markup)) { return currentParent.childNodes.push(/** @type {VTree} */ (createTree('#text', markup))); } const childNodes = []; const parts = markup.split(tokenEx); for (let i = 0; i < parts.length; i++) { const value = parts[i]; if (!value) { continue; } // When we split on the token expression, the capture group will replace // the token's position. So all we do is ensure that we're on an odd // index and then we can source the correct value. if (i % 2 === 1) { const supValue = supplemental.children[value]; const innerTree = value in supplemental.children ? supValue : createTree( '#text', `${TOKEN}${value}__`, ); if (!innerTree) continue; const isFragment = innerTree.nodeType === NODE_TYPE.FRAGMENT; if (typeof innerTree.rawNodeName === 'string' && isFragment) { childNodes.push(...innerTree.childNodes); } else { childNodes.push(innerTree); } } else if (!doctypeEx.test(value)) { childNodes.push(createTree('#text', value)); } } currentParent.childNodes.push(...childNodes); }; /** * HTMLElement, which contains a set of children. * * Note: this is a minimalist implementation, no complete tree structure * provided (no parentNode, nextSibling, previousSibling etc). * * @param {String} nodeName - DOM Node name * @param {String} rawAttrs - DOM Node Attributes * @param {Supplemental} supplemental - Interpolated data from a tagged template * @param {TransactionConfig} options * @return {VTree} vTree */ const HTMLElement = (nodeName, rawAttrs, supplemental, options) => { let match = null; const attrEx = /([_@$#a-z][^\s\x00-\x1F"'>\/=\uFDD0-\uFDEF\uFFFE\uFFFF]*)\s*(=\s*("([^"]+)"|'([^']+)'|(\S+)))?/ig; // Support dynamic tag names like: `<${MyComponent} />`. if (match = tokenEx.exec(nodeName)) { return HTMLElement( supplemental.tags[match[1]], rawAttrs, supplemental, options ); } /** @type {{ [key: string]: any }} */ const attributes = {}; // Migrate raw attributes into the attributes object used by the VTree. for (let match; match = attrEx.exec(rawAttrs || EMPTY.STR);) { const isHTML = typeof nodeName === 'string'; const name = match[1]; let tokenValue; if (name === '') { const match = rawAttrs.match(tokenEx); tokenValue = match ? match[0] : ''; } const testValue = match[6] || match[5] || match[4]; /** @type {unknown} */ const rawValue = tokenValue || testValue || (isHTML ? match[1] : testValue || true); const value = rawValue === `''` || rawValue === `""` ? EMPTY.STR : rawValue; let valueMatchesToken = String(value).match(tokenEx); // If we have multiple interpolated values in an attribute, we must // flatten to a string. There are no other valid options. if (valueMatchesToken && valueMatchesToken.length) { const parts = String(value).split(tokenEx); const hasToken = tokenEx.exec(name); const newName = hasToken ? supplemental.attributes[hasToken[1]] : name; for (let i = 0; i < parts.length; i++) { /** @type {string} */ const value = parts[i]; if (!value) { continue; } // When we split on the token expression, the capture group will // replace the token's position. So all we do is ensure that we're on // an odd index and then we can source the correct value. if (i % 2 === 1) { const isObject = typeof newName === 'object'; const hasSupValue = value in supplemental.attributes; const supValue = supplemental.attributes[value]; const fallback = `${TOKEN}${value}__`; // Allow interpolating multiple values into a single attribute. if (attributes[newName]) { attributes[newName] += hasSupValue ? supValue : fallback; } // Merge object attributes directly into the existing attributes. else if (isObject) { if (newName && !isArray(newName)) { assign(attributes, newName); } else { if (process.env.NODE_ENV !== 'production') { throw new Error('Arrays cannot be spread as attributes'); } } } else if (newName) { const defaultValue = hasSupValue ? supValue : fallback; attributes[newName] = testValue ? defaultValue : true; } } // Otherwise this is a static iteration, simply concat the raw value into the attribute. else if (attributes[newName]) { attributes[newName] += value; } // Set the initial attribute value. else { attributes[newName] = value; } } } // If the name was injected, pull from attributes and assign as either // empty or truthy. else if (valueMatchesToken = tokenEx.exec(name)) { const nameAndValue = supplemental.attributes[valueMatchesToken[1]]; if (typeof nameAndValue === 'object' && !isArray(nameAndValue)) { assign(attributes, nameAndValue); } else { attributes[nameAndValue] = value; } } // If the remaining value is a string, directly assign to the attribute // name. If the value is anything else, treat it as unknown and default to // a boolean. else { // If no test value was found, this means no real value was provided, use // the default value of true. attributes[name] = testValue !== undefined ? value : true; } } return createTree(nodeName, attributes, attributes.childNodes || []); }; /** * Parses HTML and returns a root element * * @param {String} html - String of HTML markup to parse into a Virtual Tree * @param {Supplemental=} supplemental - Dynamic interpolated data values * @param {TransactionConfig=} options - Contains options like silencing warnings * @return {VTree} - Parsed Virtual Tree Element */ export default function parse(html, supplemental, options = {}) { if (!options.parser) { /** @type {ParserConfig} */ options.parser = {}; } if (!supplemental) { supplemental = defaultSupplemental; } const blockText = new Set( /** @type {string[]} */( getConfig( 'rawElements', rawElementsDefaults, 'array', options.parser, ) ), ); const selfClosing = new Set( /** @type {string[]} */( getConfig( 'selfClosingElements', selfClosingElementsDefaults, 'array', options.parser, ) ), ); const tagEx = /<!--[^]*?(?=-->)-->|<(\/?)([a-z\-\_][a-z0-9\-\_]*)\s*([^>]*?)(".*?"|'.*?')?(\/?)>/ig; const root = createTree('#document-fragment', null, []); const stack = [root]; let currentParent = root; let lastTextPos = -1; if (process.env.NODE_ENV !== 'production') { const markup = [html]; if (!html.includes('<') && options.parser.strict) { markup.splice(1, 0, ` Possibly invalid markup. Opening tag was not properly opened. `); throw new Error(`\n\n${markup.join('\n')}`); } if (!html.includes('>') && options.parser.strict) { markup.splice(1, 0, ` Possibly invalid markup. Opening tag was not properly closed. `); throw new Error(`\n\n${markup.join('\n')}`); } } // If there are no HTML elements, treat the passed in html as a single // text node. if (!html.includes('<') && html) { interpolateChildNodes(currentParent, html, supplemental); return root; } // Look through the HTML markup for valid tags. for (let match, text, i=0; match = tagEx.exec(html); i++) { const [ fullMatch, isClosingMatch, tagMatch, attributeMatch, extraMatch, selfClosingMatch, ] = match; if (lastTextPos > -1) { if (lastTextPos + fullMatch.length < tagEx.lastIndex) { text = html.slice(lastTextPos, tagEx.lastIndex - fullMatch.length); if (text) { interpolateChildNodes(currentParent, text, supplemental); } } } const matchOffset = tagEx.lastIndex - fullMatch.length; if (lastTextPos === -1 && matchOffset > 0) { const string = html.slice(0, matchOffset); if (string && !doctypeEx.exec(string)) { interpolateChildNodes(currentParent, string, supplemental); } } lastTextPos = tagEx.lastIndex; // This is a comment (TODO someday support these). if (match[0][1] === '!') { continue; } // Get the tag index. const tokenMatch = tokenEx.exec(tagMatch); // Normalized name, use either the tag extracted from the supplemental // tags, or use tagMatch. const supTag = tokenMatch && supplemental.tags[tokenMatch[1]]; const name = supTag ? supTag.name || supTag : tagMatch; let bypassMatch; if (!isClosingMatch) { // not </ tags if (!match[4] && kElementsClosedByOpening[currentParent.rawNodeName]) { if (kElementsClosedByOpening[currentParent.rawNodeName][name]) { stack.pop(); currentParent = stack[stack.length - 1]; } } const attrs = attributeMatch + (extraMatch || ''); currentParent = currentParent.childNodes[ currentParent.childNodes.push( HTMLElement(tagMatch, attrs, supplemental, options) ) - 1 ]; stack.push(currentParent); if (options.parser.strict || blockText.has(name)) { // A little test to find next </script> or </style> ... const closeMarkup = `</${name}>`; const index = html.indexOf(closeMarkup, tagEx.lastIndex); if (process.env.NODE_ENV !== 'production') { if (index === -1 && options.parser.strict && !selfClosing.has(name)) { // Find a subset of the markup passed in to validate. const markup = html .slice(tagEx.lastIndex - fullMatch.length) .split('\n') .map(line => line.replace(tokenEx, (value, index) => { if (!supplemental) { return value; } const { tags, children, attributes } = supplemental; return tags[index] || children[index] || attributes[index]; })) .slice(0, 3); // Position the caret next to the first non-whitespace character. const lookup = spaceEx.exec(markup[0]); const caret = Array( (lookup ? lookup.index - 1 : 0) + closeMarkup.length - 1 ).join(' ') + '^'; // Craft the warning message and inject it into the markup. markup.splice(1, 0, `${caret} Possibly invalid markup. <${name}> must be closed in strict mode. `); // Throw an error message if the markup isn't what we expected. throw new Error(`\n\n${markup.join('\n')}`); } } if (blockText.has(name)) { if (index === -1) { lastTextPos = tagEx.lastIndex = html.length + 1; } else { lastTextPos = index + closeMarkup.length; tagEx.lastIndex = lastTextPos; bypassMatch = true; } const newText = html.slice(match.index + fullMatch.length, index); interpolateChildNodes(currentParent, newText, supplemental); } } } if (bypassMatch || isClosingMatch || selfClosingMatch || selfClosing.has(name)) { if (process.env.NODE_ENV !== 'production') { if (currentParent && name !== currentParent.rawNodeName && options.parser.strict) { const nodeName = currentParent.rawNodeName; // Find a subset of the markup passed in to validate. const markup = html .slice(tagEx.lastIndex - fullMatch.length) .split('\n') .map(line => line.replace(tokenEx, (value, index) => { if (!supplemental) { return value; } const { tags, children, attributes } = supplemental; return tags[index] || children[index] || attributes[index]; })) .slice(0, 3); // Position the caret next to the first non-whitespace character. const lookup = spaceEx.exec(markup[0]); const caret = Array(lookup ? lookup.index : 0).join(' ') + '^'; // Craft the warning message and inject it into the markup. markup.splice(1, 0, `${caret} Possibly invalid markup. Saw ${name}, expected ${nodeName}... `); // Throw an error message if the markup isn't what we expected. throw new Error(`\n\n${markup.join('\n')}`); } } // </ or /> or <br> etc. while (currentParent) { // Self closing dynamic nodeName. if (selfClosingMatch === '/' && tokenMatch) { stack.pop(); currentParent = stack[stack.length - 1]; break; } // Not self-closing, so seek out the next match. else if (supTag) { if (currentParent.rawNodeName === name) { stack.pop(); currentParent = stack[stack.length - 1]; break; } } if (currentParent.rawNodeName === name) { stack.pop(); currentParent = stack[stack.length - 1]; break; } else { const tag = kElementsClosedByClosing[currentParent.rawNodeName]; // Trying to close current tag, and move on if (tag) { if (tag[name]) { stack.pop(); currentParent = stack[stack.length - 1]; continue; } } // Use aggressive strategy to handle unmatching markups. break; } } } } // Find any last remaining text after the parsing completes over tags. const remainingText = html.slice(lastTextPos === -1 ? 0 : lastTextPos); if (process.env.NODE_ENV !== 'production') { if ((remainingText.includes('>') || remainingText.includes('<')) && options.parser.strict) { // Find a subset of the markup passed in to validate. const markup = [remainingText]; // Position the caret next to the first non-whitespace character. const lookup = spaceEx.exec(markup[0]); const caret = Array(lookup ? lookup.index : 0).join(' ') + '^'; // Craft the warning message and inject it into the markup. if (remainingText.includes('>')) { markup.splice(1, 0, `${caret} Possibly invalid markup. Opening tag was not properly opened. `); } else { markup.splice(1, 0, `${caret} Possibly invalid markup. Opening tag was not properly closed. `); } // Throw an error message if the markup isn't what we expected. throw new Error(`\n\n${markup.join('\n')}`); } } // Ensure that all values are properly interpolated through the remaining // markup after parsing. if (remainingText) { interpolateChildNodes(currentParent, remainingText, supplemental); } // This is an entire document, so only allow the HTML children to be // body or head. if (root.childNodes.length && root.childNodes[0].nodeName === 'html') { // Store elements from before body end and after body end. /** @type {{ [name: string]: VTree[] }} */ const head = { before: [], after: [] }; /** @type {{ [name: string]: VTree[] }} */ const body = { after: [] }; const HTML = root.childNodes[0]; let beforeHead = true; let beforeBody = true; // Iterate the children and store elements in the proper array for // later concat, replace the current childNodes with this new array. HTML.childNodes = HTML.childNodes.filter(el => { // If either body or head, allow as a valid element. if (el.nodeName === 'body' || el.nodeName === 'head') { if (el.nodeName === 'head') beforeHead = false; if (el.nodeName === 'body') beforeBody = false; return true; } // Not a valid nested HTML tag element, move to respective container. else if (el.nodeType === NODE_TYPE.ELEMENT) { if (beforeHead && beforeBody) head.before.push(el); else if (!beforeHead && beforeBody) head.after.push(el); else if (!beforeBody) body.after.push(el); } }); // Ensure the first element is the HEAD tag. if (!HTML.childNodes[0] || HTML.childNodes[0].nodeName !== 'head') { const headInstance = createTree('head', null, []); if (headInstance) { const existing = headInstance.childNodes; existing.unshift.apply(existing, head.before); existing.push.apply(existing, head.after); HTML.childNodes.unshift(headInstance); } } else { const existing = HTML.childNodes[0].childNodes; existing.unshift.apply(existing, head.before); existing.push.apply(existing, head.after); } // Ensure the second element is the body tag. if (!HTML.childNodes[1] || HTML.childNodes[1].nodeName !== 'body') { const bodyInstance = createTree('body', null, []); if (bodyInstance) { const existing = bodyInstance.childNodes; existing.push.apply(existing, body.after); HTML.childNodes.push(bodyInstance); } } else { const existing = HTML.childNodes[1].childNodes; existing.push.apply(existing, body.after); } } return root; } |