@tcy/eslint-rules 1.8.0 → 1.9.1

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.
Files changed (44) hide show
  1. package/README.md +4 -0
  2. package/coverage/clover.xml +109 -58
  3. package/coverage/coverage-final.json +2 -1
  4. package/coverage/lcov-report/index.html +19 -19
  5. package/coverage/lcov-report/src/array-elements-per-line.js.html +1 -1
  6. package/coverage/lcov-report/src/back/back.js.html +1 -1
  7. package/coverage/lcov-report/src/back/http.js.html +1 -1
  8. package/coverage/lcov-report/src/back/index.html +1 -1
  9. package/coverage/lcov-report/src/back/recommended.js.html +1 -1
  10. package/coverage/lcov-report/src/bin/eslint-cache-guard.js.html +1 -1
  11. package/coverage/lcov-report/src/bin/index.html +1 -1
  12. package/coverage/lcov-report/src/client/client.js.html +5 -2
  13. package/coverage/lcov-report/src/client/index.html +1 -1
  14. package/coverage/lcov-report/src/client/recommended.js.html +1 -1
  15. package/coverage/lcov-report/src/decorator-type-enforcement.js.html +1 -1
  16. package/coverage/lcov-report/src/enforce-tailwind-important.js.html +151 -16
  17. package/coverage/lcov-report/src/export-specifiers-per-line.js.html +1 -1
  18. package/coverage/lcov-report/src/import-specifiers-per-line.js.html +1 -1
  19. package/coverage/lcov-report/src/index.html +34 -19
  20. package/coverage/lcov-report/src/index.js.html +1 -1
  21. package/coverage/lcov-report/src/jsx-boolean-shorthand.js.html +1 -1
  22. package/coverage/lcov-report/src/jsx-expression-string-literals.js.html +1 -1
  23. package/coverage/lcov-report/src/jsx-ref-string-exists.js.html +1 -1
  24. package/coverage/lcov-report/src/no-static-key-in-map.js.html +631 -0
  25. package/coverage/lcov-report/src/plugin.js.html +8 -2
  26. package/coverage/lcov-report/src/recommended.js.html +1 -1
  27. package/coverage/lcov-report/src/require-fragment-key.js.html +1 -1
  28. package/coverage/lcov-report/src/route-dto-required.js.html +1 -1
  29. package/coverage/lcov-report/src/v-model-name-match.js.html +1 -1
  30. package/coverage/lcov-report/src/vuejs-define-component.js.html +1 -1
  31. package/coverage/lcov-report/src/vuejs-define-workspace.js.html +1 -1
  32. package/coverage/lcov.info +259 -128
  33. package/decl/back/back.d.ts +29 -1
  34. package/decl/client/client.d.ts +30 -1
  35. package/decl/enforce-tailwind-important.d.ts +30 -1
  36. package/decl/no-static-key-in-map.d.ts +66 -0
  37. package/decl/plugin.d.ts +29 -1
  38. package/package.json +1 -1
  39. package/src/client/client.js +1 -0
  40. package/src/enforce-tailwind-important.js +50 -5
  41. package/src/no-static-key-in-map.js +182 -0
  42. package/src/plugin.js +2 -0
  43. package/tests/enforce-tailwind-important.spec.js +42 -1
  44. package/tests/no-static-key-in-map.spec.js +186 -0
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @fileoverview no-static-key-in-map
3
+ *
4
+ * Reports a JSX list item whose `key` is a *static* value (a string / number /
5
+ * boolean literal, or a template literal with no interpolation) when that
6
+ * element is the root returned from an iterator callback:
7
+ *
8
+ * list.map(() => <Row key="row" />) // ✗ same key every item
9
+ * list.map(() => <Fragment key="rows">…</Fragment>) // ✗
10
+ * list.map((r) => r.ok && <Row key="row" />) // ✗ (conditional in .map)
11
+ * list.flatMap(() => [<A key="a" />, <B key="b" />]) // ✗ (array returned from .map)
12
+ *
13
+ * A constant key on every sibling is worse than no key: Vue / React build a
14
+ * key → index map where later duplicates overwrite earlier ones, so on
15
+ * insert / remove / reorder the diff patches the wrong node (misplaced DOM,
16
+ * lost child-component state) and dev builds warn about duplicate keys.
17
+ *
18
+ * It stays silent when:
19
+ *
20
+ * - the key is derived from the item or the index — `key={r.id}`, `key={i}`,
21
+ * `` key={`row-${i}`} ``
22
+ * - the element is NOT the list-item root — a static key on a nested element
23
+ * (`<ul>{rows.map(() => <li key="only" />)}</ul>` inside a keyed root) is
24
+ * scoped to its own parent's children, not the iterated list
25
+ * - there is no `key` at all — that is `react/jsx-key` / `require-fragment-key`
26
+ */
27
+ /** A value with no runtime input — a bare literal or a `${…}`-free template. */
28
+ export declare const isStaticExpression: (node: any) => any;
29
+ /**
30
+ * The `key` attribute of a JSXElement when it is present *and* static.
31
+ * `<>…</>` can never carry a key, so only JSXElement is inspected
32
+ * (`<Fragment key="…">` included).
33
+ *
34
+ * @returns the `key` JSXAttribute node, or `null`
35
+ */
36
+ export declare const getStaticKeyAttr: (node: any) => any;
37
+ /** Is `fnNode` the first argument of a `.map()` / `.flatMap()` call? */
38
+ export declare const isIteratorCallback: (fnNode: any) => boolean;
39
+ /**
40
+ * Walk outward from `node` through transparent wrappers and conditional
41
+ * operators. `node` is a list-item root when the first structural ancestor
42
+ * reached is an iterator callback; it is NOT when a JSX element / fragment is
43
+ * reached first (the element is nested, its key scoped to that parent).
44
+ */
45
+ export declare const isListItemRoot: (node: any) => boolean;
46
+ /**
47
+ * @returns {'staticKeyInIterator' | null}
48
+ */
49
+ export declare const analyzeElement: (node: any) => 'staticKeyInIterator' | null;
50
+ declare const _default: {
51
+ meta: {
52
+ type: string;
53
+ docs: {
54
+ description: string;
55
+ recommended: boolean;
56
+ };
57
+ schema: never[];
58
+ messages: {
59
+ staticKeyInIterator: string;
60
+ };
61
+ };
62
+ create(context: any): {
63
+ JSXElement: (node: any) => void;
64
+ };
65
+ };
66
+ export default _default;
package/decl/plugin.d.ts CHANGED
@@ -103,7 +103,19 @@ declare const _default: {
103
103
  recommended: boolean;
104
104
  };
105
105
  fixable: string;
106
- schema: never[];
106
+ schema: {
107
+ type: string;
108
+ properties: {
109
+ ignore: {
110
+ type: string;
111
+ items: {
112
+ type: string;
113
+ };
114
+ default: never[];
115
+ };
116
+ };
117
+ additionalProperties: boolean;
118
+ }[];
107
119
  messages: {
108
120
  missingImportant: string;
109
121
  };
@@ -215,5 +227,21 @@ declare const _default: {
215
227
  JSXElement: (node: any) => void;
216
228
  };
217
229
  };
230
+ 'no-static-key-in-map': {
231
+ meta: {
232
+ type: string;
233
+ docs: {
234
+ description: string;
235
+ recommended: boolean;
236
+ };
237
+ schema: never[];
238
+ messages: {
239
+ staticKeyInIterator: string;
240
+ };
241
+ };
242
+ create(context: any): {
243
+ JSXElement: (node: any) => void;
244
+ };
245
+ };
218
246
  };
219
247
  export default _default;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tcy/eslint-rules",
3
- "version": "1.8.0",
3
+ "version": "1.9.1",
4
4
  "description": "```typescript import { plugin as customRules } from 'tcy@eslint-rules/src/index.mjs';",
5
5
  "homepage": "https://github.com/tcastelly/eslint-rules#readme",
6
6
  "bugs": {
@@ -19,5 +19,6 @@ export default {
19
19
  'tcy/vuejs-define-component': 'error',
20
20
  'tcy/vuejs-define-workspace': 'error',
21
21
  'tcy/require-fragment-key': 'error',
22
+ 'tcy/no-static-key-in-map': 'error',
22
23
  }
23
24
  }
@@ -5,31 +5,76 @@ export const isMissingImportant = (cls) => !/^[a-zA-Z0-9-%&>*.:',/[\]()_@]+(:?!)
5
5
 
6
6
  export const addImportant = (cls) => `${cls}!`;
7
7
 
8
+ /**
9
+ * Plain (non-Tailwind) classes that must NOT receive the "!" modifier.
10
+ *
11
+ * These ship in the widgets' bundled Bootstrap-style grid CSS and are matched by
12
+ * a bare `.class` selector. Appending "!" turns the token into `class!`, which
13
+ * matches no rule at all (Tailwind does not emit anything for it, and `.class`
14
+ * does not match the `class!` token) - silently breaking the layout.
15
+ */
16
+ export const DEFAULT_IGNORED_CLASSES = [
17
+ 'row',
18
+ 'no-gutters',
19
+ 'container',
20
+ 'container-fluid',
21
+ ];
22
+
23
+ /**
24
+ * Whether a class token must be flagged for a missing "!" modifier.
25
+ * @param {string} cls the class token
26
+ * @param {Set<string>} ignored classes that are allowed without "!"
27
+ */
28
+ export const shouldFlag = (cls, ignored) => isMissingImportant(cls) && !ignored.has(cls);
29
+
30
+ /** Build the set of ignored classes from the rule options. */
31
+ export const resolveIgnored = (options) => new Set([
32
+ ...DEFAULT_IGNORED_CLASSES,
33
+ ...((options && options.ignore) || []),
34
+ ]);
35
+
8
36
  export default {
9
37
  meta: {
10
38
  type: 'layout',
11
39
  docs: { description: 'Enforce Tailwind classes end with "!"', recommended: false },
12
40
  fixable: 'code',
13
- schema: [],
41
+ schema: [
42
+ {
43
+ type: 'object',
44
+ properties: {
45
+ ignore: {
46
+ type: 'array',
47
+ items: { type: 'string' },
48
+ default: [],
49
+ },
50
+ },
51
+ additionalProperties: false,
52
+ },
53
+ ],
14
54
  messages: { missingImportant: 'Tailwind class "{{cls}}" should end with "!"' },
15
55
  },
16
56
 
17
57
  create(context) {
18
58
  const source = context.getSourceCode();
19
59
 
60
+ const ignored = resolveIgnored(context.options[0]);
61
+
62
+ // a class needs the "!" modifier unless it is explicitly ignored
63
+ const isFlagged = (cls) => shouldFlag(cls, ignored);
64
+
20
65
  //----------------------------------------------------------------------
21
66
  // Helpers
22
67
  //----------------------------------------------------------------------
23
68
  function reportIfMissing(node, value) {
24
69
  const classes = value.split(/\s+/).map((cls) => cls.trim()).filter(Boolean);
25
- const missing = classes.filter(isMissingImportant);
70
+ const missing = classes.filter(isFlagged);
26
71
 
27
72
  // nothing to fix
28
73
  if (!missing.length) {
29
74
  return;
30
75
  }
31
76
 
32
- const fixed = classes.map((c) => (isMissingImportant(c) ? addImportant(c) : c)).join(' ');
77
+ const fixed = classes.map((c) => (isFlagged(c) ? addImportant(c) : c)).join(' ');
33
78
  context.report({
34
79
  node,
35
80
  messageId: 'missingImportant',
@@ -51,7 +96,7 @@ export default {
51
96
  for (let i = 0; i < quasis.length; i += 1) {
52
97
  // fix literal part
53
98
  const parts = quasis[i].value.raw.split(/\s+/).filter(Boolean);
54
- const fixed = parts.map((p) => (isMissingImportant(p) ? addImportant(p) : p)).join(' ');
99
+ const fixed = parts.map((p) => (isFlagged(p) ? addImportant(p) : p)).join(' ');
55
100
  out += fixed;
56
101
 
57
102
  // add space before expression if needed
@@ -102,7 +147,7 @@ export default {
102
147
  .some((q) => q.value.raw
103
148
  .split(/\s+/)
104
149
  .filter(Boolean)
105
- .some(isMissingImportant));
150
+ .some(isFlagged));
106
151
 
107
152
  if (!hasMissing) {
108
153
  return;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * @fileoverview no-static-key-in-map
3
+ *
4
+ * Reports a JSX list item whose `key` is a *static* value (a string / number /
5
+ * boolean literal, or a template literal with no interpolation) when that
6
+ * element is the root returned from an iterator callback:
7
+ *
8
+ * list.map(() => <Row key="row" />) // ✗ same key every item
9
+ * list.map(() => <Fragment key="rows">…</Fragment>) // ✗
10
+ * list.map((r) => r.ok && <Row key="row" />) // ✗ (conditional in .map)
11
+ * list.flatMap(() => [<A key="a" />, <B key="b" />]) // ✗ (array returned from .map)
12
+ *
13
+ * A constant key on every sibling is worse than no key: Vue / React build a
14
+ * key → index map where later duplicates overwrite earlier ones, so on
15
+ * insert / remove / reorder the diff patches the wrong node (misplaced DOM,
16
+ * lost child-component state) and dev builds warn about duplicate keys.
17
+ *
18
+ * It stays silent when:
19
+ *
20
+ * - the key is derived from the item or the index — `key={r.id}`, `key={i}`,
21
+ * `` key={`row-${i}`} ``
22
+ * - the element is NOT the list-item root — a static key on a nested element
23
+ * (`<ul>{rows.map(() => <li key="only" />)}</ul>` inside a keyed root) is
24
+ * scoped to its own parent's children, not the iterated list
25
+ * - there is no `key` at all — that is `react/jsx-key` / `require-fragment-key`
26
+ */
27
+
28
+ const ITERATOR_METHODS = new Set(['map', 'flatMap']);
29
+
30
+ const LITERAL_TYPES = new Set([
31
+ 'Literal', // espree: string / number / boolean / null / regex
32
+ 'StringLiteral', // @babel/parser
33
+ 'NumericLiteral',
34
+ 'BooleanLiteral',
35
+ 'BigIntLiteral',
36
+ 'NullLiteral',
37
+ ]);
38
+
39
+ const UNWRAP_TYPES = new Set([
40
+ 'ParenthesizedExpression',
41
+ 'TSAsExpression',
42
+ 'TSNonNullExpression',
43
+ 'TSSatisfiesExpression',
44
+ ]);
45
+
46
+ /** Transparent wrappers we walk *through* on the way out to the callback. */
47
+ const TRANSPARENT_ANCESTORS = new Set([
48
+ 'JSXExpressionContainer',
49
+ 'ParenthesizedExpression',
50
+ 'TSAsExpression',
51
+ 'TSNonNullExpression',
52
+ 'TSSatisfiesExpression',
53
+ 'BlockStatement',
54
+ 'ReturnStatement',
55
+ 'ArrayExpression',
56
+ 'LogicalExpression',
57
+ 'ConditionalExpression',
58
+ ]);
59
+
60
+ /** A value with no runtime input — a bare literal or a `${…}`-free template. */
61
+ export const isStaticExpression = (node) => {
62
+ if (!node) return false;
63
+ if (LITERAL_TYPES.has(node.type)) return true;
64
+ if (node.type === 'TemplateLiteral') return node.expressions.length === 0;
65
+ if (UNWRAP_TYPES.has(node.type)) return isStaticExpression(node.expression);
66
+ return false;
67
+ };
68
+
69
+ /**
70
+ * The `key` attribute of a JSXElement when it is present *and* static.
71
+ * `<>…</>` can never carry a key, so only JSXElement is inspected
72
+ * (`<Fragment key="…">` included).
73
+ *
74
+ * @returns the `key` JSXAttribute node, or `null`
75
+ */
76
+ export const getStaticKeyAttr = (node) => {
77
+ if (!node || node.type !== 'JSXElement') return null;
78
+
79
+ const attr = node.openingElement.attributes.find(
80
+ (a) => a.type === 'JSXAttribute'
81
+ && a.name.type === 'JSXIdentifier'
82
+ && a.name.name === 'key',
83
+ );
84
+ if (!attr) return null;
85
+
86
+ const { value } = attr;
87
+ // `key` with no value (`<X key />`) — treat as static, it is never dynamic
88
+ if (!value) return attr;
89
+ if (value.type === 'JSXExpressionContainer') {
90
+ return isStaticExpression(value.expression) ? attr : null;
91
+ }
92
+ // a plain JSX string attribute: `key="row"`
93
+ return LITERAL_TYPES.has(value.type) ? attr : null;
94
+ };
95
+
96
+ /** Is `fnNode` the first argument of a `.map()` / `.flatMap()` call? */
97
+ export const isIteratorCallback = (fnNode) => {
98
+ const call = fnNode.parent;
99
+ return !!call
100
+ && call.type === 'CallExpression'
101
+ && call.arguments[0] === fnNode
102
+ && call.callee.type === 'MemberExpression'
103
+ && call.callee.property.type === 'Identifier'
104
+ && ITERATOR_METHODS.has(call.callee.property.name);
105
+ };
106
+
107
+ /**
108
+ * Walk outward from `node` through transparent wrappers and conditional
109
+ * operators. `node` is a list-item root when the first structural ancestor
110
+ * reached is an iterator callback; it is NOT when a JSX element / fragment is
111
+ * reached first (the element is nested, its key scoped to that parent).
112
+ */
113
+ export const isListItemRoot = (node) => {
114
+ let node_ = node.parent;
115
+
116
+ while (node_) {
117
+ if (TRANSPARENT_ANCESTORS.has(node_.type)) {
118
+ node_ = node_.parent;
119
+ continue;
120
+ }
121
+ if (
122
+ node_.type === 'ArrowFunctionExpression'
123
+ || node_.type === 'FunctionExpression'
124
+ ) {
125
+ return isIteratorCallback(node_);
126
+ }
127
+ // JSXElement / JSXFragment / anything else → not a direct list item
128
+ return false;
129
+ }
130
+ return false;
131
+ };
132
+
133
+ /**
134
+ * @returns {'staticKeyInIterator' | null}
135
+ */
136
+ export const analyzeElement = (node) => {
137
+ const keyAttr = getStaticKeyAttr(node);
138
+ if (!keyAttr) return null;
139
+ return isListItemRoot(node) ? 'staticKeyInIterator' : null;
140
+ };
141
+
142
+ export default {
143
+ meta: {
144
+ type: 'problem',
145
+ docs: {
146
+ description:
147
+ 'Disallow a static `key` (string / number / template-without-interpolation) '
148
+ + 'on the root element returned from `.map()` / `.flatMap()` — every item would '
149
+ + 'get the same key.',
150
+ recommended: false,
151
+ },
152
+ schema: [],
153
+ messages: {
154
+ staticKeyInIterator:
155
+ 'Static `key={{keyText}}` on a `.map()` list item — every iteration renders the '
156
+ + 'same key, so Vue diffs the list by position and can mismatch nodes on '
157
+ + 'insert / remove / reorder. Derive it from the item (`key={item.id}`) or, '
158
+ + 'failing that, the index (`key={i}`).',
159
+ },
160
+ },
161
+
162
+ create(context) {
163
+ const { sourceCode } = context;
164
+
165
+ const check = (node) => {
166
+ const keyAttr = getStaticKeyAttr(node);
167
+ if (!keyAttr || !isListItemRoot(node)) return;
168
+
169
+ context.report({
170
+ node: keyAttr,
171
+ messageId: 'staticKeyInIterator',
172
+ data: {
173
+ keyText: keyAttr.value ? sourceCode.getText(keyAttr.value) : '(none)',
174
+ },
175
+ });
176
+ };
177
+
178
+ return {
179
+ JSXElement: check,
180
+ };
181
+ },
182
+ };
package/src/plugin.js CHANGED
@@ -11,6 +11,7 @@ import vuejsDefineComponent from './vuejs-define-component.js'
11
11
  import vuejsDefineWorkspace from './vuejs-define-workspace.js'
12
12
  import routeDtoRequired from './route-dto-required.js'
13
13
  import requireFragmentKey from './require-fragment-key.js'
14
+ import noStaticKeyInMap from './no-static-key-in-map.js'
14
15
 
15
16
  export default {
16
17
  'import-specifiers-per-line': importSpecifiersPerLineRule,
@@ -26,4 +27,5 @@ export default {
26
27
  'vuejs-define-workspace': vuejsDefineWorkspace,
27
28
  'route-dto-required': routeDtoRequired,
28
29
  'require-fragment-key': requireFragmentKey,
30
+ 'no-static-key-in-map': noStaticKeyInMap,
29
31
  }
@@ -1,4 +1,9 @@
1
- import { isMissingImportant } from '../src/enforce-tailwind-important';
1
+ import {
2
+ DEFAULT_IGNORED_CLASSES,
3
+ isMissingImportant,
4
+ resolveIgnored,
5
+ shouldFlag,
6
+ } from '../src/enforce-tailwind-important';
2
7
 
3
8
  describe('GIVEN "enforce-tailwind-important"', () => {
4
9
  describe('WHEN "test" important class', () => {
@@ -12,4 +17,40 @@ describe('GIVEN "enforce-tailwind-important"', () => {
12
17
  expect(isImportantClass).toBe(true);
13
18
  });
14
19
  });
20
+
21
+ describe('WHEN a class is in the ignore list', () => {
22
+ it('THEN "no-gutters" and "container-fluid" are ignored by default', () => {
23
+ expect(DEFAULT_IGNORED_CLASSES).toEqual(
24
+ expect.arrayContaining(['no-gutters', 'container-fluid']),
25
+ );
26
+ });
27
+
28
+ it('THEN a default-ignored class is not flagged', () => {
29
+ const ignored = resolveIgnored();
30
+
31
+ expect(shouldFlag('no-gutters', ignored)).toBe(false);
32
+ expect(shouldFlag('container-fluid', ignored)).toBe(false);
33
+ });
34
+
35
+ it('THEN a real Tailwind class is still flagged', () => {
36
+ const ignored = resolveIgnored();
37
+
38
+ expect(shouldFlag('w-full', ignored)).toBe(true);
39
+ expect(shouldFlag('max-w-[800px]', ignored)).toBe(true);
40
+ });
41
+
42
+ it('THEN an already-important class is never flagged', () => {
43
+ const ignored = resolveIgnored();
44
+
45
+ expect(shouldFlag('w-full!', ignored)).toBe(false);
46
+ });
47
+
48
+ it('THEN classes from the "ignore" option are merged with the defaults', () => {
49
+ const ignored = resolveIgnored({ ignore: ['my-legacy-class'] });
50
+
51
+ expect(shouldFlag('my-legacy-class', ignored)).toBe(false);
52
+ expect(shouldFlag('no-gutters', ignored)).toBe(false);
53
+ expect(shouldFlag('text-red-500', ignored)).toBe(true);
54
+ });
55
+ });
15
56
  });
@@ -0,0 +1,186 @@
1
+ import { parse } from '@babel/parser';
2
+ import {
3
+ analyzeElement,
4
+ getStaticKeyAttr,
5
+ isListItemRoot,
6
+ isStaticExpression,
7
+ } from '../src/no-static-key-in-map';
8
+
9
+ // ─── helpers ────────────────────────────────────────────────────────────────
10
+
11
+ const linkParents = (node, parent = null) => {
12
+ if (!node || typeof node.type !== 'string') return;
13
+ node.parent = parent;
14
+ Object.keys(node).forEach((key) => {
15
+ if (key === 'parent') return;
16
+ const value = node[key];
17
+ if (Array.isArray(value)) {
18
+ value.forEach((child) => linkParents(child, node));
19
+ } else if (value && typeof value.type === 'string') {
20
+ linkParents(value, node);
21
+ }
22
+ });
23
+ };
24
+
25
+ const collectElements = (node, out = []) => {
26
+ if (!node || typeof node.type !== 'string') return out;
27
+ if (node.type === 'JSXElement') out.push(node);
28
+ Object.keys(node).forEach((key) => {
29
+ if (key === 'parent') return;
30
+ const value = node[key];
31
+ if (Array.isArray(value)) value.forEach((child) => collectElements(child, out));
32
+ else if (value && typeof value.type === 'string') collectElements(value, out);
33
+ });
34
+ return out;
35
+ };
36
+
37
+ /** Parse `code`, return every messageId the rule would emit (in source order). */
38
+ const lint = (code) => {
39
+ const ast = parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
40
+ linkParents(ast.program);
41
+ return collectElements(ast.program)
42
+ .map((node) => analyzeElement(node))
43
+ .filter(Boolean);
44
+ };
45
+
46
+ const firstElement = (code) => {
47
+ const ast = parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
48
+ linkParents(ast.program);
49
+ return collectElements(ast.program)[0];
50
+ };
51
+
52
+ // ─── isStaticExpression ─────────────────────────────────────────────────────
53
+
54
+ describe('GIVEN "no-static-key-in-map" / isStaticExpression', () => {
55
+ const expr = (code) => parse(`(${code})`, { plugins: ['typescript'] }).program.body[0].expression;
56
+
57
+ it.each([
58
+ ['"row"', true],
59
+ ['42', true],
60
+ ['true', true],
61
+ ['`row`', true],
62
+ ['`row-${i}`', false],
63
+ ['i', false],
64
+ ['item.id', false],
65
+ ['getKey()', false],
66
+ ['"row" as string', true],
67
+ ])('THEN %s → static:%s', (code, isStatic) => {
68
+ expect(isStaticExpression(expr(code))).toBe(isStatic);
69
+ });
70
+ });
71
+
72
+ // ─── getStaticKeyAttr ───────────────────────────────────────────────────────
73
+
74
+ describe('GIVEN "no-static-key-in-map" / getStaticKeyAttr', () => {
75
+ it('THEN a string key is static', () => {
76
+ expect(getStaticKeyAttr(firstElement('const x = <A key="row" />;'))).toBeTruthy();
77
+ });
78
+
79
+ it('THEN a braced literal key is static', () => {
80
+ expect(getStaticKeyAttr(firstElement('const x = <A key={"row"} />;'))).toBeTruthy();
81
+ expect(getStaticKeyAttr(firstElement('const x = <A key={1} />;'))).toBeTruthy();
82
+ expect(getStaticKeyAttr(firstElement('const x = <A key={`row`} />;'))).toBeTruthy();
83
+ });
84
+
85
+ it('THEN a <Fragment key="…"> is static', () => {
86
+ expect(getStaticKeyAttr(firstElement('const x = <Fragment key="rows" />;'))).toBeTruthy();
87
+ });
88
+
89
+ it('THEN a dynamic key is NOT static', () => {
90
+ expect(getStaticKeyAttr(firstElement('const x = <A key={i} />;'))).toBeNull();
91
+ expect(getStaticKeyAttr(firstElement('const x = <A key={item.id} />;'))).toBeNull();
92
+ expect(getStaticKeyAttr(firstElement('const x = <A key={`row-${i}`} />;'))).toBeNull();
93
+ });
94
+
95
+ it('THEN a missing key is NOT static', () => {
96
+ expect(getStaticKeyAttr(firstElement('const x = <A />;'))).toBeNull();
97
+ });
98
+ });
99
+
100
+ // ─── positions that DO trigger ─────────────────────────────────────────────
101
+
102
+ describe('GIVEN "no-static-key-in-map" / flagged positions', () => {
103
+ it('THEN a static key on a .map arrow-body element', () => {
104
+ expect(lint('const x = list.map((i) => <Row key="row" />);')).toEqual(['staticKeyInIterator']);
105
+ });
106
+
107
+ it('THEN a static key on a .map block-return element', () => {
108
+ expect(lint('const x = list.map((i) => { return <Row key="row" />; });')).toEqual(['staticKeyInIterator']);
109
+ });
110
+
111
+ it('THEN a static <Fragment> key inside .map', () => {
112
+ const code = 'const x = list.map((i) => <Fragment key="rows"><A/><B/></Fragment>);';
113
+ expect(lint(code)).toEqual(['staticKeyInIterator']);
114
+ });
115
+
116
+ it('THEN a conditional element inside .map with a static key', () => {
117
+ expect(lint('const x = list.map((i) => i.ok && <Row key="row" />);')).toEqual(['staticKeyInIterator']);
118
+ expect(lint('const x = list.map((i) => (i.ok ? <A key="a" /> : <B key="b" />));'))
119
+ .toEqual(['staticKeyInIterator', 'staticKeyInIterator']);
120
+ });
121
+
122
+ it('THEN every static-keyed element of an array returned from .flatMap', () => {
123
+ const code = 'const x = list.flatMap((i) => [<A key="a" />, <B key="b" />]);';
124
+ expect(lint(code)).toEqual(['staticKeyInIterator', 'staticKeyInIterator']);
125
+ });
126
+
127
+ it('THEN a parenthesised / cast list item is still flagged', () => {
128
+ expect(lint('const x = list.map((i) => (<Row key="row" />));')).toEqual(['staticKeyInIterator']);
129
+ });
130
+ });
131
+
132
+ // ─── positions that do NOT trigger ─────────────────────────────────────────
133
+
134
+ describe('GIVEN "no-static-key-in-map" / allowed positions', () => {
135
+ it('THEN a dynamic key in .map is fine', () => {
136
+ expect(lint('const x = list.map((r) => <Row key={r.id} />);')).toEqual([]);
137
+ expect(lint('const x = list.map((r, i) => <Row key={i} />);')).toEqual([]);
138
+ expect(lint('const x = list.map((r, i) => <Row key={`row-${i}`} />);')).toEqual([]);
139
+ });
140
+
141
+ it('THEN a static key on a NESTED element (not the list-item root) is fine', () => {
142
+ const code = 'const x = list.map((r) => <ul key={r.id}><li key="only">{r.n}</li></ul>);';
143
+ expect(lint(code)).toEqual([]);
144
+ });
145
+
146
+ it('THEN static keys among the children of a fragment list-item root are fine', () => {
147
+ const code = 'const x = list.map((r) => <Fragment key={r.id}><A key="a" /><B key="b" /></Fragment>);';
148
+ expect(lint(code)).toEqual([]);
149
+ });
150
+
151
+ it('THEN a static key outside any iterator is fine', () => {
152
+ expect(lint('const x = <Row key="row" />;')).toEqual([]);
153
+ expect(lint('const x = cond && <Row key="row" />;')).toEqual([]);
154
+ });
155
+
156
+ it('THEN a missing key is not this rule\'s concern', () => {
157
+ expect(lint('const x = list.map((r) => <Row />);')).toEqual([]);
158
+ });
159
+
160
+ it('THEN forEach / other non-iterator callbacks are ignored', () => {
161
+ expect(lint('list.forEach((r) => render(<Row key="row" />));')).toEqual([]);
162
+ });
163
+ });
164
+
165
+ // ─── isListItemRoot (white-box) ────────────────────────────────────────────
166
+
167
+ describe('GIVEN "no-static-key-in-map" / isListItemRoot', () => {
168
+ it('THEN the arrow body of .map is a list-item root', () => {
169
+ expect(isListItemRoot(firstElement('const x = list.map((i) => <A key="a" />);'))).toBe(true);
170
+ });
171
+
172
+ it('THEN a nested element is not', () => {
173
+ // collectElements order is outer-first, so [1] is the inner <li>
174
+ const ast = parse('const x = list.map((i) => <ul><li key="x" /></ul>);', {
175
+ sourceType: 'module',
176
+ plugins: ['jsx'],
177
+ });
178
+ linkParents(ast.program);
179
+ const inner = collectElements(ast.program)[1];
180
+ expect(isListItemRoot(inner)).toBe(false);
181
+ });
182
+
183
+ it('THEN an element outside a .map is not', () => {
184
+ expect(isListItemRoot(firstElement('const x = <A key="a" />;'))).toBe(false);
185
+ });
186
+ });