Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: New rule to disallow certain attribute values #145

Merged
merged 5 commits into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module.exports = {
extends: ["eslint:recommended"],
plugins: ["jest", "node"],
parserOptions: {
ecmaVersion: 9,
ecmaVersion: 2020,
},
env: {
node: true,
Expand Down
71 changes: 71 additions & 0 deletions docs/rules/no-restricted-attr-values.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
id: no-restricted-attr-values
title: "no-restricted-attr-values"
---

# no-restricted-attrs

Disallow specified attribute values

## How to use

.eslintrc.js

```js
module.exports = {
rules: {
'@html-eslint/no-restricted-attr-values': ["error", {
attrPatterns: ["class"],
attrValuePatterns: ["data-.*"]
message: "\'data-x\' is restricted."
}]
}
};
```

## Rule Details

This rule allows you to specify attribute values that you don't want to use in your application.

### Options

This rule takes an array of option objects, where the `attrPatterns` and `attrValuePatterns` are specified.

- `attrPatterns`: an array of strings representing regular expression pattern, disallows attribute names that match any of the patterns.
- `attrValuePatterns`: an array of strings representing regular expression pattern, disallows attribute values that match any of the patterns.
- `message` (optional): a string for custom message.

```js
module.exports = {
"rules": {
"@html-eslint/no-restricted-attrs": [
"error",
{
attrPatterns: ["class", "alt"],
attrValuePatterns: ["data-.*"]
message: "\'data-x\' is restricted."
},
{
attrPatterns: [".*"],
attrValuePatterns: ["^foo$"]
message: "\'foo\' is restricted."
}
],
}
};
```

Examples of **incorrect** code for this rule with the option below:

```json
{
"attrPatterns": ["data-.*"],
"attrValuePatterns": ["foo"],
"message": "Do not use foo attr value"
}
```

```html
<div data-name="foo"></div>
<img data-name="foo"></div>
```
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"license": "MIT",
"devDependencies": {
"cspell": "^6.19.2",
"eslint": "^7.14.0",
"eslint": "^7.32.0",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had to update esLint to handle the optional chaining

"eslint-plugin-jest": "^24.1.3",
"eslint-plugin-node": "^11.1.0",
"gh-pages": "^3.1.0",
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/lib/rules/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const noAccesskeyAttrs = require("./no-accesskey-attrs");
const noRestrictedAttrs = require("./no-restricted-attrs");
const noTrailingSpaces = require("./no-trailing-spaces");
const requireAttrs = require("./require-attrs");
const noRestrictedAttrValues = require("./no-restricted-attr-values");

module.exports = {
"require-lang": requireLang,
Expand Down Expand Up @@ -64,4 +65,5 @@ module.exports = {
"no-accesskey-attrs": noAccesskeyAttrs,
"no-restricted-attrs": noRestrictedAttrs,
"no-trailing-spaces": noTrailingSpaces,
"no-restricted-attr-values": noRestrictedAttrValues,
};
139 changes: 139 additions & 0 deletions packages/eslint-plugin/lib/rules/no-restricted-attr-values.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/**
* @typedef {import("../types").Rule} Rule
* @typedef {{attrPatterns: string[], attrValuePatterns: string[], message?: string}[]} Options
*/

const { RULE_CATEGORY } = require("../constants");

const MESSAGE_IDS = {
RESTRICTED: "restricted",
};

/**
* @type {Rule}
*/
module.exports = {
meta: {
type: "code",

docs: {
description: "Disallow specified attributes",
category: RULE_CATEGORY.BEST_PRACTICE,
recommended: false,
},

fixable: null,
schema: {
type: "array",

items: {
type: "object",
required: ["attrPatterns", "attrValuePatterns"],
properties: {
attrPatterns: {
type: "array",
items: {
type: "string",
},
},
attrValuePatterns: {
type: "array",
items: {
type: "string",
},
},
message: {
type: "string",
},
},
},
},
messages: {
[MESSAGE_IDS.RESTRICTED]:
"'{{attrValuePatterns}}' is restricted from being used.",
},
},

create(context) {
/**
* @type {Options}
*/
const options = context.options;
const checkers = options.map((option) => new PatternChecker(option));

return {
[["Tag", "StyleTag", "ScriptTag"].join(",")](node) {
node.attributes.forEach((attr) => {
if (
!attr.key ||
typeof attr.value?.value !== "string" ||
!attr.key?.value
) {
return;

Check warning on line 72 in packages/eslint-plugin/lib/rules/no-restricted-attr-values.js

View check run for this annotation

Codecov / codecov/patch

packages/eslint-plugin/lib/rules/no-restricted-attr-values.js#L72

Added line #L72 was not covered by tests
}
const matched = checkers.find((checker) =>
checker.test(attr.key.value, attr.value.value)
);

if (!matched) {
return;
}

const result = {
node: attr,
message: "",
};

const customMessage = matched.getMessage();

if (customMessage) {
result.message = customMessage;
} else {
result.messageId = MESSAGE_IDS.RESTRICTED;
}

context.report({
...result,
data: { attrValuePatterns: attr.value.value },
});
});
},
};
},
};

class PatternChecker {
/**
* @param {Options[number]} option
*/
constructor(option) {
this.option = option;
this.attrRegExps = option.attrPatterns.map(
(pattern) => new RegExp(pattern, "u")
);

this.valueRegExps = option.attrValuePatterns.map(
(pattern) => new RegExp(pattern, "u")
);
this.message = option.message;
}

/**
* @param {string} attrName
* @param {string} attrValue
* @returns {boolean}
*/
test(attrName, attrValue) {
const result =
this.attrRegExps.some((exp) => exp.test(attrName)) &&
this.valueRegExps.some((exp) => exp.test(attrValue));
return result;
}

/**
* @returns {string}
*/
getMessage() {
return this.message || "";
}
}
114 changes: 114 additions & 0 deletions packages/eslint-plugin/tests/rules/no-restricted-attr-values.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
const createRuleTester = require("../rule-tester");
const rule = require("../../lib/rules/no-restricted-attr-values");

const ruleTester = createRuleTester();

ruleTester.run("no-restricted-attr-values", rule, {
valid: [
{
code: `<div> </div>`,
options: [
{
attrPatterns: [".*"],
attrValuePatterns: ["data-.*"],
},
],
},
{
code: `<div class="foo"> </div>`,
options: [
{
attrPatterns: ["class"],
attrValuePatterns: ["data-.*"],
},
],
},
],
invalid: [
{
code: `<div foo="data-x"> </div>`,
options: [
{
attrPatterns: [".*"],
attrValuePatterns: ["data-.*"],
},
],
errors: [
{
messageId: "restricted",
data: {
attrValuePatterns: "data-x",
},
},
],
},
{
code: `<div foo=""> </div>`,
options: [
{
attrPatterns: [".*"],
attrValuePatterns: [""],
},
],
errors: [
{
messageId: "restricted",
data: {
attrValuePatterns: "",
},
},
],
},
{
code: `<div class="foo"> </div> <a alt="foo"></a>`,
options: [
{
attrPatterns: ["alt"],
attrValuePatterns: ["foo"],
},
],
errors: [
{
messageId: "restricted",
data: {
attrValuePatterns: "foo",
},
},
],
},
{
code: `<div alt="foo"> </div> <custom-element class="foo"></custom-element>`,
options: [
{
attrPatterns: ["alt", "class"],
attrValuePatterns: ["^foo$"],
message: "no foo for alt or class",
},
],
errors: [
{
message: "no foo for alt or class",
},
{
message: "no foo for alt or class",
},
],
},
// custom message
{
code: `<div foo="data-x"> </div>`,
options: [
{
attrPatterns: [".*"],
attrValuePatterns: ["data.*"],
message: "please do not use 'data-x'",
},
],
errors: [
{
message: "please do not use 'data-x'",
},
],
},
],
});
Loading