no-invalid-html-attribute.js 14.3 KB
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
/**
 * @fileoverview Check if tag attributes to have non-valid value
 * @author Sebastian Malton
 */

'use strict';

const matchAll = require('string.prototype.matchall');
const docsUrl = require('../util/docsUrl');
const report = require('../util/report');

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

const rel = new Map([
  ['alternate', new Set(['link', 'area', 'a'])],
  ['apple-touch-icon', new Set(['link'])],
  ['author', new Set(['link', 'area', 'a'])],
  ['bookmark', new Set(['area', 'a'])],
  ['canonical', new Set(['link'])],
  ['dns-prefetch', new Set(['link'])],
  ['external', new Set(['area', 'a', 'form'])],
  ['help', new Set(['link', 'area', 'a', 'form'])],
  ['icon', new Set(['link'])],
  ['license', new Set(['link', 'area', 'a', 'form'])],
  ['manifest', new Set(['link'])],
  ['mask-icon', new Set(['link'])],
  ['modulepreload', new Set(['link'])],
  ['next', new Set(['link', 'area', 'a', 'form'])],
  ['nofollow', new Set(['area', 'a', 'form'])],
  ['noopener', new Set(['area', 'a', 'form'])],
  ['noreferrer', new Set(['area', 'a', 'form'])],
  ['opener', new Set(['area', 'a', 'form'])],
  ['pingback', new Set(['link'])],
  ['preconnect', new Set(['link'])],
  ['prefetch', new Set(['link'])],
  ['preload', new Set(['link'])],
  ['prerender', new Set(['link'])],
  ['prev', new Set(['link', 'area', 'a', 'form'])],
  ['search', new Set(['link', 'area', 'a', 'form'])],
  ['shortcut', new Set(['link'])], // generally allowed but needs pair with "icon"
  ['shortcut\u0020icon', new Set(['link'])],
  ['stylesheet', new Set(['link'])],
  ['tag', new Set(['area', 'a'])],
]);

const pairs = new Map([
  ['shortcut', new Set(['icon'])],
]);

/**
 * Map between attributes and a mapping between valid values and a set of tags they are valid on
 * @type {Map<string, Map<string, Set<string>>>}
 */
const VALID_VALUES = new Map([
  ['rel', rel],
]);

/**
 * Map between attributes and a mapping between pair-values and a set of values they are valid with
 * @type {Map<string, Map<string, Set<string>>>}
 */
const VALID_PAIR_VALUES = new Map([
  ['rel', pairs],
]);

/**
 * The set of all possible HTML elements. Used for skipping custom types
 * @type {Set<string>}
 */
const HTML_ELEMENTS = new Set([
  'a',
  'abbr',
  'acronym',
  'address',
  'applet',
  'area',
  'article',
  'aside',
  'audio',
  'b',
  'base',
  'basefont',
  'bdi',
  'bdo',
  'bgsound',
  'big',
  'blink',
  'blockquote',
  'body',
  'br',
  'button',
  'canvas',
  'caption',
  'center',
  'cite',
  'code',
  'col',
  'colgroup',
  'content',
  'data',
  'datalist',
  'dd',
  'del',
  'details',
  'dfn',
  'dialog',
  'dir',
  'div',
  'dl',
  'dt',
  'em',
  'embed',
  'fieldset',
  'figcaption',
  'figure',
  'font',
  'footer',
  'form',
  'frame',
  'frameset',
  'h1',
  'h2',
  'h3',
  'h4',
  'h5',
  'h6',
  'head',
  'header',
  'hgroup',
  'hr',
  'html',
  'i',
  'iframe',
  'image',
  'img',
  'input',
  'ins',
  'kbd',
  'keygen',
  'label',
  'legend',
  'li',
  'link',
  'main',
  'map',
  'mark',
  'marquee',
  'math',
  'menu',
  'menuitem',
  'meta',
  'meter',
  'nav',
  'nobr',
  'noembed',
  'noframes',
  'noscript',
  'object',
  'ol',
  'optgroup',
  'option',
  'output',
  'p',
  'param',
  'picture',
  'plaintext',
  'portal',
  'pre',
  'progress',
  'q',
  'rb',
  'rp',
  'rt',
  'rtc',
  'ruby',
  's',
  'samp',
  'script',
  'section',
  'select',
  'shadow',
  'slot',
  'small',
  'source',
  'spacer',
  'span',
  'strike',
  'strong',
  'style',
  'sub',
  'summary',
  'sup',
  'svg',
  'table',
  'tbody',
  'td',
  'template',
  'textarea',
  'tfoot',
  'th',
  'thead',
  'time',
  'title',
  'tr',
  'track',
  'tt',
  'u',
  'ul',
  'var',
  'video',
  'wbr',
  'xmp',
]);

/**
* Map between attributes and set of tags that the attribute is valid on
* @type {Map<string, Set<string>>}
*/
const COMPONENT_ATTRIBUTE_MAP = new Map();
COMPONENT_ATTRIBUTE_MAP.set('rel', new Set(['link', 'a', 'area', 'form']));

const messages = {
  emptyIsMeaningless: 'An empty “{{attributeName}}” attribute is meaningless.',
  neverValid: '“{{reportingValue}}” is never a valid “{{attributeName}}” attribute value.',
  noEmpty: 'An empty “{{attributeName}}” attribute is meaningless.',
  noMethod: 'The ”{{attributeName}}“ attribute cannot be a method.',
  notAlone: '“{{reportingValue}}” must be directly followed by “{{missingValue}}”.',
  notPaired: '“{{reportingValue}}” can not be directly followed by “{{secondValue}}” without “{{missingValue}}”.',
  notValidFor: '“{{reportingValue}}” is not a valid “{{attributeName}}” attribute value for <{{elementName}}>.',
  onlyMeaningfulFor: 'The ”{{attributeName}}“ attribute only has meaning on the tags: {{tagNames}}',
  onlyStrings: '“{{attributeName}}” attribute only supports strings.',
  spaceDelimited: '”{{attributeName}}“ attribute values should be space delimited.',
};

function splitIntoRangedParts(node, regex) {
  const valueRangeStart = node.range[0] + 1; // the plus one is for the initial quote

  return Array.from(matchAll(node.value, regex), (match) => {
    const start = match.index + valueRangeStart;
    const end = start + match[0].length;

    return {
      reportingValue: `${match[1]}`,
      value: match[1],
      range: [start, end],
    };
  });
}

function checkLiteralValueNode(context, attributeName, node, parentNode, parentNodeName) {
  if (typeof node.value !== 'string') {
    report(context, messages.onlyStrings, 'onlyStrings', {
      node,
      data: { attributeName },
      fix(fixer) {
        return fixer.remove(parentNode);
      },
    });
    return;
  }

  if (!node.value.trim()) {
    report(context, messages.noEmpty, 'noEmpty', {
      node,
      data: { attributeName },
      fix(fixer) {
        return fixer.remove(parentNode);
      },
    });
    return;
  }

  const singleAttributeParts = splitIntoRangedParts(node, /(\S+)/g);
  for (const singlePart of singleAttributeParts) {
    const allowedTags = VALID_VALUES.get(attributeName).get(singlePart.value);
    const reportingValue = singlePart.reportingValue;
    if (!allowedTags) {
      report(context, messages.neverValid, 'neverValid', {
        node,
        data: {
          attributeName,
          reportingValue,
        },
        fix(fixer) {
          return fixer.removeRange(singlePart.range);
        },
      });
    } else if (!allowedTags.has(parentNodeName)) {
      report(context, messages.notValidFor, 'notValidFor', {
        node,
        data: {
          attributeName,
          reportingValue,
          elementName: parentNodeName,
        },
        fix(fixer) {
          return fixer.removeRange(singlePart.range);
        },
      });
    }
  }

  const allowedPairsForAttribute = VALID_PAIR_VALUES.get(attributeName);
  if (allowedPairsForAttribute) {
    const pairAttributeParts = splitIntoRangedParts(node, /(?=(\b\S+\s*\S+))/g);
    for (const pairPart of pairAttributeParts) {
      for (const allowedPair of allowedPairsForAttribute) {
        const pairing = allowedPair[0];
        const siblings = allowedPair[1];
        const attributes = pairPart.reportingValue.split('\u0020');
        const firstValue = attributes[0];
        const secondValue = attributes[1];
        if (firstValue === pairing) {
          const lastValue = attributes[attributes.length - 1]; // in case of multiple white spaces
          if (!siblings.has(lastValue)) {
            const message = secondValue ? messages.notPaired : messages.notAlone;
            const messageId = secondValue ? 'notPaired' : 'notAlone';
            report(context, message, messageId, {
              node,
              data: {
                reportingValue: firstValue,
                secondValue,
                missingValue: Array.from(siblings).join(', '),
              },
            });
          }
        }
      }
    }
  }

  const whitespaceParts = splitIntoRangedParts(node, /(\s+)/g);
  for (const whitespacePart of whitespaceParts) {
    if (whitespacePart.range[0] === (node.range[0] + 1) || whitespacePart.range[1] === (node.range[1] - 1)) {
      report(context, messages.spaceDelimited, 'spaceDelimited', {
        node,
        data: { attributeName },
        fix(fixer) {
          return fixer.removeRange(whitespacePart.range);
        },
      });
    } else if (whitespacePart.value !== '\u0020') {
      report(context, messages.spaceDelimited, 'spaceDelimited', {
        node,
        data: { attributeName },
        fix(fixer) {
          return fixer.replaceTextRange(whitespacePart.range, '\u0020');
        },
      });
    }
  }
}

const DEFAULT_ATTRIBUTES = ['rel'];

function checkAttribute(context, node) {
  const attribute = node.name.name;

  function fix(fixer) {
    return fixer.remove(node);
  }

  const parentNodeName = node.parent.name.name;
  if (!COMPONENT_ATTRIBUTE_MAP.has(attribute) || !COMPONENT_ATTRIBUTE_MAP.get(attribute).has(parentNodeName)) {
    const tagNames = Array.from(
      COMPONENT_ATTRIBUTE_MAP.get(attribute).values(),
      (tagName) => `"<${tagName}>"`
    ).join(', ');
    report(context, messages.onlyMeaningfulFor, 'onlyMeaningfulFor', {
      node,
      data: {
        attributeName: attribute,
        tagNames,
      },
      fix,
    });
    return;
  }

  if (!node.value) {
    report(context, messages.emptyIsMeaningless, 'emptyIsMeaningless', {
      node,
      data: { attributeName: attribute },
      fix,
    });
    return;
  }

  if (node.value.type === 'Literal') {
    return checkLiteralValueNode(context, attribute, node.value, node, parentNodeName);
  }

  if (node.value.expression.type === 'Literal') {
    return checkLiteralValueNode(context, attribute, node.value.expression, node, parentNodeName);
  }

  if (node.value.type !== 'JSXExpressionContainer') {
    return;
  }

  if (node.value.expression.type === 'ObjectExpression') {
    report(context, messages.onlyStrings, 'onlyStrings', {
      node,
      data: { attributeName: attribute },
      fix,
    });
    return;
  }

  if (node.value.expression.type === 'Identifier' && node.value.expression.name === 'undefined') {
    report(context, messages.onlyStrings, 'onlyStrings', {
      node,
      data: { attributeName: attribute },
      fix,
    });
  }
}

function isValidCreateElement(node) {
  return node.callee
    && node.callee.type === 'MemberExpression'
    && node.callee.object.name === 'React'
    && node.callee.property.name === 'createElement'
    && node.arguments.length > 0;
}

function checkPropValidValue(context, node, value, attribute) {
  const validTags = VALID_VALUES.get(attribute);

  if (value.type !== 'Literal') {
    return; // cannot check non-literals
  }

  const validTagSet = validTags.get(value.value);
  if (!validTagSet) {
    report(context, messages.neverValid, 'neverValid', {
      node: value,
      data: {
        attributeName: attribute,
        reportingValue: value.value,
      },
    });
    return;
  }

  if (!validTagSet.has(node.arguments[0].value)) {
    report(context, messages.notValidFor, 'notValidFor', {
      node: value,
      data: {
        attributeName: attribute,
        reportingValue: value.raw,
        elementName: node.arguments[0].value,
      },
    });
  }
}

/**
 *
 * @param {*} context
 * @param {*} node
 * @param {string} attribute
 */
function checkCreateProps(context, node, attribute) {
  const propsArg = node.arguments[1];

  if (!propsArg || propsArg.type !== 'ObjectExpression') {
    return; // can't check variables, computed, or shorthands
  }

  for (const prop of propsArg.properties) {
    if (!prop.key || prop.key.type !== 'Identifier') {
      // eslint-disable-next-line no-continue
      continue; // cannot check computed keys
    }

    if (prop.key.name !== attribute) {
      // eslint-disable-next-line no-continue
      continue; // ignore not this attribute
    }

    if (!COMPONENT_ATTRIBUTE_MAP.get(attribute).has(node.arguments[0].value)) {
      const tagNames = Array.from(
        COMPONENT_ATTRIBUTE_MAP.get(attribute).values(),
        (tagName) => `"<${tagName}>"`
      ).join(', ');

      report(context, messages.onlyMeaningfulFor, 'onlyMeaningfulFor', {
        node,
        data: {
          attributeName: attribute,
          tagNames,
        },
      });

      // eslint-disable-next-line no-continue
      continue;
    }

    if (prop.method) {
      report(context, messages.noMethod, 'noMethod', {
        node: prop,
        data: {
          attributeName: attribute,
        },
      });

      // eslint-disable-next-line no-continue
      continue;
    }

    if (prop.shorthand || prop.computed) {
      // eslint-disable-next-line no-continue
      continue; // cannot check these
    }

    if (prop.value.type === 'ArrayExpression') {
      for (const value of prop.value.elements) {
        checkPropValidValue(context, node, value, attribute);
      }

      // eslint-disable-next-line no-continue
      continue;
    }

    checkPropValidValue(context, node, prop.value, attribute);
  }
}

module.exports = {
  meta: {
    fixable: 'code',
    docs: {
      description: 'Disallow usage of invalid attributes',
      category: 'Possible Errors',
      url: docsUrl('no-invalid-html-attribute'),
    },
    messages,
    schema: [{
      type: 'array',
      uniqueItems: true,
      items: {
        enum: ['rel'],
      },
    }],
  },

  create(context) {
    return {
      JSXAttribute(node) {
        const attributes = new Set(context.options[0] || DEFAULT_ATTRIBUTES);

        // ignore attributes that aren't configured to be checked
        if (!attributes.has(node.name.name)) {
          return;
        }

        // ignore non-HTML elements
        if (!HTML_ELEMENTS.has(node.parent.name.name)) {
          return;
        }

        checkAttribute(context, node);
      },

      CallExpression(node) {
        if (!isValidCreateElement(node)) {
          return;
        }

        const elemNameArg = node.arguments[0];

        if (!elemNameArg || elemNameArg.type !== 'Literal') {
          return; // can only check literals
        }

        // ignore non-HTML elements
        if (!HTML_ELEMENTS.has(elemNameArg.value)) {
          return;
        }

        const attributes = new Set(context.options[0] || DEFAULT_ATTRIBUTES);

        for (const attribute of attributes) {
          checkCreateProps(context, node, attribute);
        }
      },
    };
  },
};