All files / semantic-dom-diff index.js

67.54% Statements 77/114
51.16% Branches 44/86
74.07% Functions 20/27
66.98% Lines 71/106

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                            11x 11x 6x   1x   4x     4x                                           8x 8x 4x                     8x 4x   8x 8x 8x 8x       1x 1x   2x     2x 2x                         1x       1x                             1x             1x 1x           2x 2x 6x 2x 2x 2x           4x 2x 2x           2x                   2x     2x       1x     1x 1x 1x     1x 1x 1x 3x 1x 1x 1x           2x 1x 1x                 1x   2x 1x 1x 1x       1x                         1x 1x 1x             2x 2x 2x                         1x 1x 1x 1x   9x 1x 1x     1x        
import { parseFragment, serialize } from '@bundled-es-modules/parse5';
import { deepDiff } from '@bundled-es-modules/deep-diff';
 
function sanitizeHtmlString(htmlString) {
  return htmlString
    // Remove whitespace between elements (no whitespace only nodes)
    .replace(/>\s+</g, '><')
    // remove lit-html expression markers
    .replace(/<!---->/g, '')
    // Remove leading and trailing whitespace
    .trim();
}
 
// Typings for parse5 contains errors, and the inheritence tree is funky.
const isElement = (arg) => arg && 'tagName' in arg;
const isParentNode = (arg) => arg && 'childNodes' in arg;
const isTextNode = (arg) => arg && arg.nodeName === '#text';
 
const defaultIgnoresTags = ['style', 'script', '#comment'];
function filterNode(node, ignoredTags) {
  return !defaultIgnoresTags.includes(node.nodeName) && !ignoredTags.includes(node.nodeName);
}
function sortAttributes(attrs) {
  return attrs
    // Sort attributes
    .map((attr) => {
      if (attr.name === 'class') {
        attr.value = attr.value.trim().split(/\s+/).sort().join(' ');
      }
      return attr;
    })
    // Sort classes
    .sort((attrA, attrB) => {
      const a = attrA.name.toLowerCase();
      const b = attrB.name.toLowerCase();
      if (a < b) {
        return -1;
      }
      if (a > b) {
        return 1;
      }
      return 0;
    });
}
function normalizeWhitespace(nodes) {
  const lastIndex = nodes.length - 1;
  nodes.forEach((node, i) => {
    Iif (isTextNode(node)) {
      if (i === 0) {
        node.value = node.value.replace(/^\s+/, '');
      }
      if (i === lastIndex) {
        node.value = node.value.replace(/\s+$/, '');
      }
    }
  });
}
function normalizeAST(node, ignoredTags = []) {
  if (isElement(node)) {
    node.attrs = sortAttributes(node.attrs);
  }
  Eif (isParentNode(node)) {
    normalizeWhitespace(node.childNodes);
    node.childNodes = node.childNodes.filter(child => filterNode(child, ignoredTags));
    node.childNodes.forEach(child => normalizeAST(child, ignoredTags));
  }
}
 
const isAttribute = (arg) => arg && 'name' in arg && 'value' in arg;
const isArray = Array.isArray;
function identifier(arg) {
  Iif (isTextNode(arg)) {
    return `text "${arg.value}"`;
  }
  Eif (isElement(arg)) {
    return `tag <${arg.tagName}>`;
  }
  if (isAttribute(arg)) {
    return arg.value
      ? `attribute [${arg.name}="${arg.value}"]`
      : `attribute [${arg.name}]`;
  }
  throw new Error(`Unknown arg: ${arg}`);
}
/** Asserts that the diff is an array diff, returns type assertions to remove optional props.  */
function isArrayDiff(d) {
  return d.kind === 'A' && !!d.item && typeof d.index === 'number';
}
const messageTemplates = {
  // New diff
  N: (diff, lhs, rhs) => `${identifier(rhs)} has been added`,
  // Edit diff
  E: (diff, lhs, rhs) => `${identifier(lhs)} was changed to ${identifier(rhs)}`,
  // Delete diff
  D: (diff, lhs, rhs) => `${identifier(lhs)} has been removed`,
};
/**
 * Generates a human understandable message for a HTML diff.
 *
 * @param diff The diff
 * @param lhs The left hand side diffed object. Can be a HTML ASTNode or an Attribute.
 * @param rhs The left hand side diffed object. Can be a HTML ASTNode or an Attribute.
 *
 * @returns the message
 */
function getDiffMessage(diff, lhs, rhs) {
  // Array diff
  Iif (isArray(lhs) || isArray(rhs)) {
    if (!isArrayDiff(diff) || !isArray(lhs) || !isArray(rhs)) {
      throw new Error('Not all arguments are array diffs');
    }
    return getDiffMessage(diff.item, lhs[diff.index], rhs[diff.index]);
  }
  // Non-array diff
  Eif (diff.kind in messageTemplates) {
    return messageTemplates[diff.kind](diff, lhs, rhs);
  }
  throw new Error(`Unknown diff kind: ${diff.kind}`);
}
 
function findDiffedObject(root, path) {
  let node = root;
  for (const step of path) {
    if (Array.isArray(node)) {
      const i = parseFloat(step);
      Eif (Number.isInteger(i)) {
        node = node[i];
      }
      else {
        throw new Error(`Non-integer step: ${step} for array node.`);
      }
    }
    else if (step === 'childNodes') {
      Eif (isParentNode(node)) {
        node = node.childNodes;
      }
      else {
        throw new Error(`Cannot read childNodes from non-parent node.`);
      }
    }
    else Iif (step === 'attrs') {
      if (isElement(node)) {
        node = node.attrs;
      }
      else {
        throw new Error(`Cannot read attributes from non-element node.`);
      }
    }
    else {
      // For all other steps we don't walk further
      break;
    }
  }
  return node;
}
 
function getNodeName(node) {
  Iif (!isElement(node)) {
    return;
  }
  const idAttr = node.attrs && node.attrs.find((attr) => attr.name === 'id');
  const id = idAttr ? `#${idAttr.value}` : '';
  return `${node.nodeName}${id}`;
}
function getDiffPath(root, path) {
  const names = [];
  let node = root;
  for (const step of path) {
    if (Array.isArray(node)) {
      const i = parseFloat(step);
      Eif (Number.isInteger(i)) {
        node = node[i];
      }
      else {
        throw new Error(`Non-integer step: ${step} for array node.`);
      }
    }
    else if (step === 'childNodes') {
      Eif (isParentNode(node)) {
        node = node.childNodes;
      }
      else {
        throw new Error(`Cannot read childNodes from non-parent node.`);
      }
    }
    else {
      // Break loop if we end up at a type of path section we don't want
      // walk further into
      break;
    }
    if (!Array.isArray(node)) {
      const name = getNodeName(node);
      Eif (name) {
        names.push(name);
      }
    }
  }
  return names.join(' > ');
}
 
/**
 * Creates the DiffResult for two AST trees.
 *
 * @param leftTree the left tree
 * @param rightTree the right tree
 * @param diff the semantic difference between the two trees
 *
 * @returns the diff result containing the human readable semantic difference
 */
function createDiffResult(leftTree, rightTree, diff) {
  const leftDiffObject = findDiffedObject(leftTree, diff.path);
  const rightDiffObject = findDiffedObject(rightTree, diff.path);
  return {
    message: getDiffMessage(diff, leftDiffObject, rightDiffObject),
    path: getDiffPath(leftTree, diff.path),
  };
}
 
function getAST(value, config = {}) {
  const ast = parseFragment(value);
  normalizeAST(ast, config.ignoredTags);
  return ast;
}
/**
 * Parses two HTML trees, and generates the semantic difference between the two trees.
 * The HTML is diffed semantically, not literally. This means that changes in attribute
 * and class order and whitespace/newlines are ignored. Also, script and style
 * tags ignored.
 *
 * @param leftHTML the left HTML tree
 * @param rightHTML the right HTML tree
 * @returns the diff result, or undefined if no diffs were found
 */
function getDOMDiff(leftHTML, rightHTML, config = {}) {
  const leftTree = getAST(leftHTML);
  const rightTree = getAST(rightHTML);
  normalizeAST(leftTree, config.ignoredTags);
  normalizeAST(rightTree, config.ignoredTags);
  // parentNode causes a circular reference, so ignore them.
  const ignore = (path, key) => key === 'parentNode';
  const diffs = deepDiff(leftTree, rightTree, ignore);
  Iif (!diffs || !diffs.length) {
    return undefined;
  }
  return createDiffResult(leftTree, rightTree, diffs[0]);
}
 
export { getAST, getDOMDiff };