@pob/eslint-plugin 66.6.0 → 67.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,8 +1,6 @@
1
- import baseConfig from "./configs/base.js";
2
- import nodeConfig from "./configs/node.js";
3
- import reactConfig from "./configs/react.js";
4
1
  import { loadRules } from "./loadRules.js";
5
2
 
3
+ // rules run by oxlint as a JS plugin, see @pob/eslint-config/oxlint/*.json
6
4
  export default {
7
5
  meta: {
8
6
  name: "@pob/eslint-plugin",
@@ -11,9 +9,4 @@ export default {
11
9
  rules: {
12
10
  ...loadRules(),
13
11
  },
14
- configs: {
15
- base: baseConfig,
16
- react: reactConfig,
17
- node: nodeConfig,
18
- },
19
12
  };
package/lib/loadRules.js CHANGED
@@ -2,6 +2,9 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import forbidNonNativeFetchImportRule from "./rules/forbid-non-native-fetch-import.js";
4
4
  import forbidNonNativeNodeImportsRule from "./rules/forbid-non-native-node-imports.js";
5
+ import jsxNoLeakedRenderRule from "./rules/jsx-no-leaked-render.js";
6
+ import jsxSortPropsRule from "./rules/jsx-sort-props.js";
7
+ import noUselessTemplateLiteralRule from "./rules/no-useless-template-literal.js";
5
8
  import reactFunctionComponentReturnReactNodeRule from "./rules/react-function-component-return-react-node.js";
6
9
  import reactNamedImportRule from "./rules/react-named-import.js";
7
10
 
@@ -42,6 +45,15 @@ export function loadRules() {
42
45
  "forbid-non-native-node-imports",
43
46
  forbidNonNativeNodeImportsRule,
44
47
  ),
48
+ "jsx-no-leaked-render": loadRule(
49
+ "jsx-no-leaked-render",
50
+ jsxNoLeakedRenderRule,
51
+ ),
52
+ "jsx-sort-props": loadRule("jsx-sort-props", jsxSortPropsRule),
53
+ "no-useless-template-literal": loadRule(
54
+ "no-useless-template-literal",
55
+ noUselessTemplateLiteralRule,
56
+ ),
45
57
  "react-function-component-return-react-node": loadRule(
46
58
  "react-function-component-return-react-node",
47
59
  reactFunctionComponentReturnReactNodeRule,
@@ -0,0 +1,75 @@
1
+ // Same as react/jsx-no-leaked-render of eslint-plugin-react with its default
2
+ // options (ternary and coerce strategies), for React >= 18.
3
+
4
+ // left sides already coerced to a boolean: !x, a === b, Boolean(x), ...
5
+ const COERCED_TYPES = new Set([
6
+ "UnaryExpression",
7
+ "BinaryExpression",
8
+ "CallExpression",
9
+ ]);
10
+
11
+ const isCoerced = (node) =>
12
+ node.type === "LogicalExpression"
13
+ ? isCoerced(node.left) && isCoerced(node.right)
14
+ : COERCED_TYPES.has(node.type);
15
+
16
+ const findVariable = (scope, name) => {
17
+ for (let current = scope; current; current = current.upper) {
18
+ const variable = current.set.get(name);
19
+ if (variable) return variable;
20
+ }
21
+ return undefined;
22
+ };
23
+
24
+ // a variable initialized with a boolean literal
25
+ const isBooleanVariable = (context, node) => {
26
+ if (node.type !== "Identifier") return false;
27
+ const variable = findVariable(context.sourceCode.getScope(node), node.name);
28
+ const init = variable?.defs[0]?.node.init;
29
+ return init?.type === "Literal" && typeof init.value === "boolean";
30
+ };
31
+
32
+ export default {
33
+ meta: {
34
+ type: "problem",
35
+
36
+ docs: {
37
+ description:
38
+ "Disallow problematic leaked values from being rendered, like 0 in `{count && <Item />}`",
39
+ category: "Possible Errors",
40
+ recommended: true,
41
+ },
42
+
43
+ fixable: "code",
44
+
45
+ messages: {
46
+ noPotentialLeakedRender:
47
+ "Potential leaked value that might cause unintentionally rendered values or rendering crashes",
48
+ },
49
+ },
50
+
51
+ create: (context) => ({
52
+ 'JSXExpressionContainer > LogicalExpression[operator="&&"]'(node) {
53
+ const { left } = node;
54
+ if (isCoerced(left) || isBooleanVariable(context, left)) return;
55
+ // React >= 18 renders nothing for an empty string
56
+ if (left.type === "Literal" && left.value === "") return;
57
+
58
+ context.report({
59
+ node,
60
+ messageId: "noPotentialLeakedRender",
61
+ fix: (fixer) => {
62
+ const text = context.sourceCode.getText(node);
63
+ // after the left side and its parentheses
64
+ const operatorIndex = text.indexOf(
65
+ "&&",
66
+ left.range[1] - node.range[0],
67
+ );
68
+ const leftText = text.slice(0, operatorIndex).trim();
69
+ const rightText = text.slice(operatorIndex + 2).trim();
70
+ return fixer.replaceText(node, `${leftText} ? ${rightText} : null`);
71
+ },
72
+ });
73
+ },
74
+ }),
75
+ };
@@ -0,0 +1,61 @@
1
+ import { RuleTester } from "eslint";
2
+ import rule from "./jsx-no-leaked-render.js";
3
+
4
+ const ruleTester = new RuleTester({
5
+ languageOptions: {
6
+ ecmaVersion: 2022,
7
+ sourceType: "module",
8
+ parserOptions: { ecmaFeatures: { jsx: true } },
9
+ },
10
+ });
11
+
12
+ // @ts-ignore
13
+ ruleTester.run("jsx-no-leaked-render", rule, {
14
+ valid: [
15
+ { code: "const a = <div>{count > 0 && <span />}</div>;" },
16
+ { code: "const a = <div>{!!count && <span />}</div>;" },
17
+ { code: "const a = <div>{Boolean(count) && <span />}</div>;" },
18
+ { code: "const a = <div>{!count && <span />}</div>;" },
19
+ { code: "const a = <div>{count ? <span /> : null}</div>;" },
20
+ { code: "const a = <div>{a > 0 && b === 1 && <span />}</div>;" },
21
+ {
22
+ code: "const isOpen = false; const a = <div>{isOpen && <span />}</div>;",
23
+ },
24
+ { code: 'const a = <div>{"" && <span />}</div>;' },
25
+ // not rendered: only JSX expression containers are checked
26
+ { code: "const a = count && <span />;" },
27
+ ],
28
+ invalid: [
29
+ {
30
+ code: "const a = <div>{count && <span />}</div>;",
31
+ output: "const a = <div>{count ? <span /> : null}</div>;",
32
+ errors: [{ messageId: "noPotentialLeakedRender" }],
33
+ },
34
+ {
35
+ code: "const a = <div>{items.length && <span />}</div>;",
36
+ output: "const a = <div>{items.length ? <span /> : null}</div>;",
37
+ errors: [{ messageId: "noPotentialLeakedRender" }],
38
+ },
39
+ {
40
+ code: "const a = <div>{(a || b) && <span />}</div>;",
41
+ output: "const a = <div>{(a || b) ? <span /> : null}</div>;",
42
+ errors: [{ messageId: "noPotentialLeakedRender" }],
43
+ },
44
+ {
45
+ code: "const a = <div>{a > 0 && b && <span />}</div>;",
46
+ output: "const a = <div>{a > 0 && b ? <span /> : null}</div>;",
47
+ errors: [{ messageId: "noPotentialLeakedRender" }],
48
+ },
49
+ {
50
+ code: "const a = <div>{count && (\n <span />\n)}</div>;",
51
+ output: "const a = <div>{count ? (\n <span />\n) : null}</div>;",
52
+ errors: [{ messageId: "noPotentialLeakedRender" }],
53
+ },
54
+ {
55
+ code: "const isOpen = 0; const a = <div>{isOpen && <span />}</div>;",
56
+ output:
57
+ "const isOpen = 0; const a = <div>{isOpen ? <span /> : null}</div>;",
58
+ errors: [{ messageId: "noPotentialLeakedRender" }],
59
+ },
60
+ ],
61
+ });
@@ -0,0 +1,124 @@
1
+ // Same as react/jsx-sort-props of eslint-plugin-react with the options
2
+ // { noSortAlphabetically: true, reservedFirst: true, shorthandFirst: true,
3
+ // callbacksLast: true }: only the groups are ordered, not the names.
4
+
5
+ const RESERVED_PROPS = new Set([
6
+ "children",
7
+ "dangerouslySetInnerHTML",
8
+ "key",
9
+ "ref",
10
+ ]);
11
+
12
+ const getPropName = (attribute) =>
13
+ attribute.name.type === "JSXNamespacedName"
14
+ ? `${attribute.name.namespace.name}:${attribute.name.name.name}`
15
+ : attribute.name.name;
16
+
17
+ // dangerouslySetInnerHTML is only reserved on DOM elements
18
+ const isReservedProp = (name, isDomElement) =>
19
+ RESERVED_PROPS.has(name) &&
20
+ (name !== "dangerouslySetInnerHTML" || isDomElement);
21
+
22
+ const isCallbackProp = (name) => /^on[A-Z]/.test(name);
23
+
24
+ const isShorthandProp = (attribute) => attribute.value === null;
25
+
26
+ /**
27
+ * Sort key: reserved props first, callbacks last, shorthand props first among
28
+ * the others.
29
+ */
30
+ const getRank = (attribute, isDomElement) => {
31
+ const name = getPropName(attribute);
32
+ if (isReservedProp(name, isDomElement)) {
33
+ return isShorthandProp(attribute) ? 0 : 1;
34
+ }
35
+ if (isCallbackProp(name)) return isShorthandProp(attribute) ? 4 : 5;
36
+ return isShorthandProp(attribute) ? 2 : 3;
37
+ };
38
+
39
+ /** Attributes split by spread attributes, which are not moved. */
40
+ const getAttributeGroups = (attributes) => {
41
+ /** @type {any[][]} */
42
+ const groups = [];
43
+ let group = [];
44
+ for (const attribute of attributes) {
45
+ if (attribute.type === "JSXSpreadAttribute") {
46
+ groups.push(group);
47
+ group = [];
48
+ } else {
49
+ group.push(attribute);
50
+ }
51
+ }
52
+ groups.push(group);
53
+ return groups.filter((attributeGroup) => attributeGroup.length > 1);
54
+ };
55
+
56
+ export default {
57
+ meta: {
58
+ type: "layout",
59
+
60
+ docs: {
61
+ description:
62
+ "Enforce the order of JSX props: reserved props first, then shorthand props, callbacks last",
63
+ category: "Stylistic Issues",
64
+ recommended: true,
65
+ },
66
+
67
+ fixable: "code",
68
+
69
+ messages: {
70
+ listReservedPropsFirst:
71
+ "Reserved props must be listed before all other props",
72
+ listShorthandFirst:
73
+ "Shorthand props must be listed before all other props",
74
+ listCallbacksLast: "Callbacks must be listed after all other props",
75
+ },
76
+ },
77
+
78
+ create: (context) => ({
79
+ JSXOpeningElement(node) {
80
+ const isDomElement =
81
+ node.name.type === "JSXIdentifier" && /^[a-z]/.test(node.name.name);
82
+
83
+ for (const group of getAttributeGroups(node.attributes)) {
84
+ const ranks = group.map((attribute) =>
85
+ getRank(attribute, isDomElement),
86
+ );
87
+ const sorted = group
88
+ .map((attribute, index) => ({ attribute, rank: ranks[index] }))
89
+ .toSorted((a, b) => a.rank - b.rank)
90
+ .map(({ attribute }) => attribute);
91
+
92
+ const fix = (fixer) =>
93
+ group.map((attribute, index) =>
94
+ fixer.replaceText(
95
+ attribute,
96
+ context.sourceCode.getText(sorted[index]),
97
+ ),
98
+ );
99
+
100
+ // report the first prop out of its group
101
+ for (let index = 1; index < group.length; index++) {
102
+ const previousRank = ranks[index - 1];
103
+ const rank = ranks[index];
104
+ if (rank >= previousRank) continue;
105
+
106
+ const attribute = group[index];
107
+ const name = getPropName(attribute);
108
+ const previousName = getPropName(group[index - 1]);
109
+ let messageId = "listShorthandFirst";
110
+ let reportedAttribute = attribute;
111
+ if (isReservedProp(name, isDomElement)) {
112
+ messageId = "listReservedPropsFirst";
113
+ } else if (isCallbackProp(previousName) && !isCallbackProp(name)) {
114
+ // like eslint-plugin-react, report the callback
115
+ messageId = "listCallbacksLast";
116
+ reportedAttribute = group[index - 1];
117
+ }
118
+ context.report({ node: reportedAttribute, messageId, fix });
119
+ break;
120
+ }
121
+ }
122
+ },
123
+ }),
124
+ };
@@ -0,0 +1,55 @@
1
+ import { RuleTester } from "eslint";
2
+ import rule from "./jsx-sort-props.js";
3
+
4
+ const ruleTester = new RuleTester({
5
+ languageOptions: {
6
+ ecmaVersion: 2022,
7
+ sourceType: "module",
8
+ parserOptions: { ecmaFeatures: { jsx: true } },
9
+ },
10
+ });
11
+
12
+ // @ts-ignore
13
+ ruleTester.run("jsx-sort-props", rule, {
14
+ valid: [
15
+ { code: "const a = <A key={1} ref={r} b c={1} onClick={f} />;" },
16
+ // names are not sorted
17
+ { code: "const a = <A z={1} a={1} />;" },
18
+ // spread attributes split the groups
19
+ { code: "const a = <A onClick={f} {...props} b={1} />;" },
20
+ // dangerouslySetInnerHTML is only reserved on DOM elements
21
+ { code: "const a = <A b={1} dangerouslySetInnerHTML={html} />;" },
22
+ { code: "const a = <A b onClick onChange={f} />;" },
23
+ ],
24
+ invalid: [
25
+ {
26
+ code: "const a = <A b={1} key={1} />;",
27
+ output: "const a = <A key={1} b={1} />;",
28
+ errors: [{ messageId: "listReservedPropsFirst" }],
29
+ },
30
+ {
31
+ code: "const a = <div b={1} dangerouslySetInnerHTML={html} />;",
32
+ output: "const a = <div dangerouslySetInnerHTML={html} b={1} />;",
33
+ errors: [{ messageId: "listReservedPropsFirst" }],
34
+ },
35
+ {
36
+ code: "const a = <A b={1} c />;",
37
+ output: "const a = <A c b={1} />;",
38
+ errors: [{ messageId: "listShorthandFirst" }],
39
+ },
40
+ {
41
+ code: "const a = <A onClick={f} b={1} />;",
42
+ output: "const a = <A b={1} onClick={f} />;",
43
+ errors: [{ messageId: "listCallbacksLast", column: 14 }],
44
+ },
45
+ {
46
+ code: "const a = <A onClick={f} c={1} b ref={r} {...props} onChange={g} d={1} />;",
47
+ output:
48
+ "const a = <A ref={r} b c={1} onClick={f} {...props} d={1} onChange={g} />;",
49
+ errors: [
50
+ { messageId: "listCallbacksLast" },
51
+ { messageId: "listCallbacksLast" },
52
+ ],
53
+ },
54
+ ],
55
+ });
@@ -0,0 +1,57 @@
1
+ // An unescaped line break is preceded by an even number of backslashes.
2
+ const UNESCAPED_LINEBREAK_PATTERN = /(?:^|[^\\])(?:\\\\)*[\n\r\u2028\u2029]/u;
3
+
4
+ const toDoubleQuotedString = (raw) =>
5
+ `"${raw.slice(1, -1).replaceAll(/\\(\$\{|.)|"/gu, (match, escaped) => {
6
+ if (escaped === "`" || escaped === "${") return escaped;
7
+ if (match === '"') return '\\"';
8
+ return match;
9
+ })}"`;
10
+
11
+ export default {
12
+ meta: {
13
+ type: "suggestion",
14
+
15
+ docs: {
16
+ description:
17
+ "Disallow template literals without interpolation, line break or tag",
18
+ category: "Best Practices",
19
+ recommended: true,
20
+ },
21
+
22
+ fixable: "code",
23
+
24
+ messages: {
25
+ useless:
26
+ "Template literal without interpolation, line break or tag: use a string literal.",
27
+ },
28
+ },
29
+
30
+ create: (context) => {
31
+ return {
32
+ TemplateLiteral(node) {
33
+ if (
34
+ node.expressions.length > 0 ||
35
+ (node.parent.type === "TaggedTemplateExpression" &&
36
+ node.parent.quasi === node) ||
37
+ UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw)
38
+ ) {
39
+ return;
40
+ }
41
+
42
+ context.report({
43
+ node,
44
+ messageId: "useless",
45
+ fix: (fixer) =>
46
+ // a string literal statement can become a directive ("use strict")
47
+ node.parent.type === "ExpressionStatement"
48
+ ? null
49
+ : fixer.replaceText(
50
+ node,
51
+ toDoubleQuotedString(context.sourceCode.getText(node)),
52
+ ),
53
+ });
54
+ },
55
+ };
56
+ },
57
+ };
@@ -0,0 +1,54 @@
1
+ /* oxlint-disable no-template-curly-in-string -- code samples */
2
+ import { RuleTester } from "eslint";
3
+ import rule from "./no-useless-template-literal.js";
4
+
5
+ const ruleTester = new RuleTester({
6
+ languageOptions: {
7
+ ecmaVersion: 2022,
8
+ sourceType: "module",
9
+ },
10
+ });
11
+
12
+ // @ts-ignore
13
+ ruleTester.run("no-useless-template-literal", rule, {
14
+ valid: [
15
+ { code: "const a = 'single';" },
16
+ { code: 'const a = "double";' },
17
+ { code: "const a = `with ${b}`;" },
18
+ { code: "const a = String.raw`tagged`;" },
19
+ { code: "const a = `multi\nline`;" },
20
+ { code: "const a = `multi\\\\\nline`;" },
21
+ ],
22
+ invalid: [
23
+ {
24
+ code: "const a = `plain`;",
25
+ output: 'const a = "plain";',
26
+ errors: [{ messageId: "useless" }],
27
+ },
28
+ {
29
+ code: 'const a = `say "hi"`;',
30
+ output: 'const a = "say \\"hi\\"";',
31
+ errors: [{ messageId: "useless" }],
32
+ },
33
+ {
34
+ code: "const a = `it's`;",
35
+ output: 'const a = "it\'s";',
36
+ errors: [{ messageId: "useless" }],
37
+ },
38
+ {
39
+ code: "const a = `\\`a\\` \\${b} \\n`;",
40
+ output: 'const a = "`a` ${b} \\n";',
41
+ errors: [{ messageId: "useless" }],
42
+ },
43
+ {
44
+ code: "const a = `escaped \\\nline break`;",
45
+ output: 'const a = "escaped \\\nline break";',
46
+ errors: [{ messageId: "useless" }],
47
+ },
48
+ {
49
+ code: "`use strict`;",
50
+ output: null,
51
+ errors: [{ messageId: "useless" }],
52
+ },
53
+ ],
54
+ });
@@ -1,4 +1,5 @@
1
- import Components from "eslint-plugin-react/lib/util/Components.js";
1
+ // function components are named in PascalCase
2
+ const isComponentName = (name) => /^[A-Z]/.test(name);
2
3
 
3
4
  function getSuggestionFixer(node, range, context) {
4
5
  return (fixer) => {
@@ -16,8 +17,13 @@ function checkFunctionReturnType(node, onError) {
16
17
  const { typeName } = typeAnnotation;
17
18
  if (typeName == null) return;
18
19
 
19
- if (typeName.name !== "ReactNode") {
20
- onError(typeName, typeName.name, typeName.range);
20
+ // React.ReactElement: check and replace the right side. React.ReactNode is
21
+ // reported by @pob/react-named-import
22
+ const nameNode =
23
+ typeName.type === "TSQualifiedName" ? typeName.right : typeName;
24
+
25
+ if (nameNode.name !== "ReactNode") {
26
+ onError(nameNode, nameNode.name, nameNode.range);
21
27
  }
22
28
  }
23
29
 
@@ -41,10 +47,10 @@ export default {
41
47
  hasSuggestions: true,
42
48
  },
43
49
 
44
- create: Components.detect((context, components) => {
50
+ create: (context) => {
45
51
  return {
46
52
  FunctionDeclaration(node) {
47
- if (!components.get(node)) return;
53
+ if (!node.id || !isComponentName(node.id.name)) return;
48
54
 
49
55
  checkFunctionReturnType(node, (typeName, currentName, range) =>
50
56
  context.report({
@@ -62,5 +68,5 @@ export default {
62
68
  );
63
69
  },
64
70
  };
65
- }),
71
+ },
66
72
  };
@@ -24,6 +24,22 @@ ruleTester.run("react-function-component-return-react-node", rule, {
24
24
  import type { ReactNode } from 'react';
25
25
  export function SomeComponent(): ReactNode {
26
26
  return <div />;
27
+ }
28
+ `,
29
+ },
30
+ // reported by @pob/react-named-import
31
+ {
32
+ code: `
33
+ import type * as React from 'react';
34
+ export function SomeComponent(): React.ReactNode {
35
+ return <div />;
36
+ }
37
+ `,
38
+ },
39
+ {
40
+ code: `
41
+ export function notAComponent(): string {
42
+ return "";
27
43
  }
28
44
  `,
29
45
  },
@@ -31,6 +47,30 @@ export function SomeComponent(): ReactNode {
31
47
  invalid: [
32
48
  {
33
49
  code: `
50
+ import type * as React from 'react';
51
+ export function SomeComponent(): React.ReactElement {
52
+ return <div />;
53
+ }`,
54
+ errors: [
55
+ {
56
+ messageId: "invalidReturnType",
57
+ data: { value: "ReactElement" },
58
+ suggestions: [
59
+ {
60
+ messageId: "replaceReturnType",
61
+ data: { value: "ReactElement" },
62
+ output: `
63
+ import type * as React from 'react';
64
+ export function SomeComponent(): React.ReactNode {
65
+ return <div />;
66
+ }`,
67
+ },
68
+ ],
69
+ },
70
+ ],
71
+ },
72
+ {
73
+ code: `
34
74
  import type { ReactElement } from 'react';
35
75
  export function SomeComponent(): ReactElement {
36
76
  return <div />;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pob/eslint-plugin",
3
- "version": "66.6.0",
3
+ "version": "67.0.0",
4
4
  "description": "eslint plugin for react",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/christophehurpeau/pob",
@@ -27,10 +27,6 @@
27
27
  "publishConfig": {
28
28
  "access": "public"
29
29
  },
30
- "dependencies": {
31
- "@typescript-eslint/utils": "8.63.0",
32
- "eslint-plugin-react": "^7.37.5"
33
- },
34
30
  "devDependencies": {
35
31
  "@types/node": "24.19.1",
36
32
  "@typescript-eslint/rule-tester": "8.63.0",
@@ -1,6 +0,0 @@
1
- export default {
2
- name: "@pob/eslint-plugin/configs/base",
3
- rules: {
4
- "@pob/forbid-non-native-fetch-import": "error",
5
- },
6
- };
@@ -1,6 +0,0 @@
1
- export default {
2
- name: "@pob/eslint-plugin/configs/node",
3
- rules: {
4
- "@pob/forbid-non-native-node-imports": "error",
5
- },
6
- };
@@ -1,7 +0,0 @@
1
- export default {
2
- name: "@pob/eslint-plugin/configs/react",
3
- rules: {
4
- "@pob/react-named-import": "error",
5
- "@pob/react-function-component-return-react-node": "error",
6
- },
7
- };