eslint-plugin-sonarjs
Version:
255 lines (254 loc) • 10.5 kB
JavaScript
;
/*
* SonarQube JavaScript Plugin
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
// https://sonarsource.github.io/rspec/#/rspec/S1101/javascript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rule = void 0;
const jsx_ast_utils_x_1 = __importDefault(require("jsx-ast-utils-x"));
const { getProp } = jsx_ast_utils_x_1.default;
const generate_meta_js_1 = require("../helpers/generate-meta.js");
const accessibility_js_1 = require("../helpers/accessibility.js");
const ancestor_js_1 = require("../helpers/ancestor.js");
const ast_js_1 = require("../helpers/ast.js");
const jsx_js_1 = require("../helpers/jsx.js");
const location_js_1 = require("../helpers/location.js");
const accessible_name_js_1 = require("./accessible-name.js");
const destination_js_1 = require("./destination.js");
const meta = __importStar(require("./generated-meta.js"));
const messages = {
identicalTextDifferentTarget: 'Use a distinct text or label, or point to the same target for this link and the one on line {{line}}.',
};
// Props whose presence in a spread makes the anchor unresolvable.
const RELEVANT_PROPS = ['href', 'aria-labelledby', 'aria-label', 'title', ...accessibility_js_1.HIDING_ATTRIBUTES];
exports.rule = {
meta: (0, generate_meta_js_1.generateMeta)(meta, { messages }),
create(context) {
const elementType = (0, accessibility_js_1.getElementType)(context);
const links = [];
return {
JSXElement(node) {
const element = node;
const opening = element.openingElement;
if (elementType(opening).toLowerCase() !== 'a') {
return;
}
const attributes = opening.attributes;
if (!isSpreadSafe(attributes, context)) {
return;
}
if ((0, accessibility_js_1.getHiddenState)(opening, context) === 'hidden' ||
hasUnsafeSpreadAncestor(element, context)) {
return;
}
const hrefAttribute = getProp(attributes, 'href');
const href = hrefAttribute && (0, accessible_name_js_1.getStaticHref)(hrefAttribute.value);
if (!href) {
return;
}
const name = (0, accessible_name_js_1.computeAccessibleName)(element, attributes, context, elementType);
if (!name) {
return;
}
const { scope, conditionals } = resolveScope(element);
links.push({
name,
href: (0, destination_js_1.normalizeDestination)(href),
node: opening,
scope,
conditionals,
});
},
'Program:exit'() {
checkLinks(context, links);
},
};
},
};
function checkLinks(context, links) {
// Keyed by scope then accessible name; holds every link seen so far, not just the last one.
const candidatesByScope = new Map();
for (const link of links) {
let siblingCandidates = candidatesByScope.get(link.scope);
if (!siblingCandidates) {
siblingCandidates = new Map();
candidatesByScope.set(link.scope, siblingCandidates);
}
const candidates = siblingCandidates.get(link.name);
const conflict = candidates && findConflict(candidates, link);
if (conflict) {
(0, location_js_1.report)(context, {
node: link.node,
message: messages.identicalTextDifferentTarget,
messageId: 'identicalTextDifferentTarget',
data: { line: String(conflict.node.loc.start.line) },
}, [(0, location_js_1.toSecondaryLocation)(conflict.node, 'Link with the same text or label.')]);
}
if (candidates) {
candidates.push(link);
}
else {
siblingCandidates.set(link.name, [link]);
}
}
}
// The nearest preceding sibling that can render alongside `link` with a different target.
function findConflict(candidates, link) {
for (let i = candidates.length - 1; i >= 0; i--) {
const candidate = candidates[i];
if (candidate.href !== link.href && !areExclusive(link, candidate)) {
return candidate;
}
}
return undefined;
}
// Exclusive if any shared conditional ancestor puts them in different branches.
function areExclusive(a, b) {
return a.conditionals.some(x => b.conditionals.some(y => x.root === y.root && x.branch !== y.branch));
}
function resolveScope(anchor) {
let node = anchor;
const conditionals = [];
for (;;) {
const parent = node.parent;
if (!parent) {
return { scope: node, conditionals };
}
if (parent.type === 'JSXElement' || parent.type === 'JSXFragment') {
return { scope: parent, conditionals };
}
conditionals.push(...matchConditional(parent, node));
if (isScopeBoundary(parent)) {
return { scope: parent, conditionals };
}
node = parent;
}
}
// `child` is conditional if it's a direct branch of `parent`, or follows one or more guards inside it.
function matchConditional(parent, child) {
const branchRoot = (0, jsx_js_1.getConditionalBranchRoot)(parent, child);
if (branchRoot) {
// A switch case's branch identity is the case itself, not the individual statement.
const branch = parent.type === 'SwitchCase' ? parent : child;
return [{ root: branchRoot, branch }];
}
if (parent.type === 'BlockStatement') {
return findEarlyReturnGuards(parent, child).map(guard => ({
root: guard,
branch: 'after-guard',
}));
}
return [];
}
function isScopeBoundary(node) {
if (node.type === 'Program') {
return true;
}
if (!ast_js_1.functionLike.has(node.type)) {
return false;
}
if (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
return !(0, jsx_js_1.isArgumentOfRenderingCall)(node);
}
return true;
}
// Finds every earlier else-less `if` that always exits, not just the closest one.
function findEarlyReturnGuards(block, statement) {
const index = block.body.indexOf(statement);
if (index <= 0) {
return [];
}
const guards = [];
for (let i = index - 1; i >= 0; i--) {
const candidate = block.body[i];
if (isEarlyReturnGuard(candidate)) {
guards.push(candidate);
}
}
return guards;
}
function isEarlyReturnGuard(statement) {
return (statement.type === 'IfStatement' && !statement.alternate && alwaysExits(statement.consequent));
}
// Conservative: only recognizes the common return/throw and nested-if-with-both-branches shapes.
function alwaysExits(statement) {
switch (statement.type) {
case 'ReturnStatement':
case 'ThrowStatement':
return true;
case 'BlockStatement':
return statement.body.length > 0 && alwaysExits(statement.body.at(-1));
case 'IfStatement':
return (!!statement.alternate &&
alwaysExits(statement.consequent) &&
alwaysExits(statement.alternate));
default:
return false;
}
}
// True when a wrapping JSX element has a spread that could hide the anchor, e.g. `<div {...props}>`.
function hasUnsafeSpreadAncestor(anchor, context) {
return !!(0, ancestor_js_1.findFirstMatchingAncestor)(anchor, node => node.type === 'JSXElement' &&
!isSpreadSafe(node.openingElement.attributes, context));
}
// False when a spread attribute could dynamically set href, aria-labelledby, aria-label, title, or a visibility prop (hidden/aria-hidden/style), making the anchor unresolvable.
function isSpreadSafe(attributes, context) {
return attributes
.filter((attribute) => attribute.type === 'JSXSpreadAttribute')
.every(attribute => {
const resolved = (0, ast_js_1.getValueOfExpression)(context, attribute.argument, 'ObjectExpression');
if (!resolved) {
return false;
}
return !RELEVANT_PROPS.some(prop => (0, ast_js_1.getProperty)(resolved, prop, context) !== null);
});
}