@tcy/eslint-rules 1.7.0 → 1.9.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.
Files changed (43) hide show
  1. package/coverage/clover.xml +122 -4
  2. package/coverage/coverage-final.json +2 -0
  3. package/coverage/lcov-report/index.html +19 -19
  4. package/coverage/lcov-report/src/array-elements-per-line.js.html +1 -1
  5. package/coverage/lcov-report/src/back/back.js.html +1 -1
  6. package/coverage/lcov-report/src/back/http.js.html +1 -1
  7. package/coverage/lcov-report/src/back/index.html +1 -1
  8. package/coverage/lcov-report/src/back/recommended.js.html +1 -1
  9. package/coverage/lcov-report/src/bin/eslint-cache-guard.js.html +1 -1
  10. package/coverage/lcov-report/src/bin/index.html +1 -1
  11. package/coverage/lcov-report/src/client/client.js.html +8 -2
  12. package/coverage/lcov-report/src/client/index.html +1 -1
  13. package/coverage/lcov-report/src/client/recommended.js.html +1 -1
  14. package/coverage/lcov-report/src/decorator-type-enforcement.js.html +1 -1
  15. package/coverage/lcov-report/src/enforce-tailwind-important.js.html +1 -1
  16. package/coverage/lcov-report/src/export-specifiers-per-line.js.html +1 -1
  17. package/coverage/lcov-report/src/import-specifiers-per-line.js.html +1 -1
  18. package/coverage/lcov-report/src/index.html +39 -9
  19. package/coverage/lcov-report/src/index.js.html +1 -1
  20. package/coverage/lcov-report/src/jsx-boolean-shorthand.js.html +1 -1
  21. package/coverage/lcov-report/src/jsx-expression-string-literals.js.html +1 -1
  22. package/coverage/lcov-report/src/jsx-ref-string-exists.js.html +1 -1
  23. package/coverage/lcov-report/src/no-static-key-in-map.js.html +631 -0
  24. package/coverage/lcov-report/src/plugin.js.html +14 -2
  25. package/coverage/lcov-report/src/recommended.js.html +1 -1
  26. package/coverage/lcov-report/src/require-fragment-key.js.html +787 -0
  27. package/coverage/lcov-report/src/route-dto-required.js.html +1 -1
  28. package/coverage/lcov-report/src/v-model-name-match.js.html +1 -1
  29. package/coverage/lcov-report/src/vuejs-define-component.js.html +1 -1
  30. package/coverage/lcov-report/src/vuejs-define-workspace.js.html +1 -1
  31. package/coverage/lcov.info +316 -0
  32. package/decl/back/back.d.ts +42 -0
  33. package/decl/client/client.d.ts +44 -0
  34. package/decl/no-static-key-in-map.d.ts +66 -0
  35. package/decl/plugin.d.ts +42 -0
  36. package/decl/require-fragment-key.d.ts +69 -0
  37. package/package.json +9 -9
  38. package/src/client/client.js +2 -0
  39. package/src/no-static-key-in-map.js +182 -0
  40. package/src/plugin.js +4 -0
  41. package/src/require-fragment-key.js +234 -0
  42. package/tests/no-static-key-in-map.spec.js +186 -0
  43. package/tests/require-fragment-key.spec.js +160 -0
@@ -18,5 +18,7 @@ export default {
18
18
  'tcy/v-model-name-match': 'error',
19
19
  'tcy/vuejs-define-component': 'error',
20
20
  'tcy/vuejs-define-workspace': 'error',
21
+ 'tcy/require-fragment-key': 'error',
22
+ 'tcy/no-static-key-in-map': 'error',
21
23
  }
22
24
  }
@@ -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
@@ -10,6 +10,8 @@ import decoratorTypeEnforcement from './decorator-type-enforcement.js'
10
10
  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
+ import requireFragmentKey from './require-fragment-key.js'
14
+ import noStaticKeyInMap from './no-static-key-in-map.js'
13
15
 
14
16
  export default {
15
17
  'import-specifiers-per-line': importSpecifiersPerLineRule,
@@ -24,4 +26,6 @@ export default {
24
26
  'vuejs-define-component': vuejsDefineComponent,
25
27
  'vuejs-define-workspace': vuejsDefineWorkspace,
26
28
  'route-dto-required': routeDtoRequired,
29
+ 'require-fragment-key': requireFragmentKey,
30
+ 'no-static-key-in-map': noStaticKeyInMap,
27
31
  }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * @fileoverview require-fragment-key
3
+ *
4
+ * Reports a key-less Fragment (`<>…</>` or `<Fragment>` without `key`) *only* in
5
+ * the positions where Vue's children diff can actually misalign without it:
6
+ *
7
+ * A. list item — `list.map(() => <>…</>)`
8
+ * B. conditional sibling — `{cond && <>…</>}` / `cond ? <>…</> : x`, when the
9
+ * conditional is one of several children in a JSX element / fragment / array
10
+ * (the surrounding child list can change shape at runtime).
11
+ *
12
+ * It stays silent where a key is not required:
13
+ *
14
+ * C. sole return / sole child — `() => <>…</>`, `render() { return <>…</> }`,
15
+ * `default: () => <>…</>`, `<Parent><>…</></Parent>`
16
+ * D. static (non-conditional) sibling
17
+ * E. the Fragment already carries a `key`
18
+ *
19
+ * With `{ strict: true }` (the default) case B fires only when at least one
20
+ * sibling is *also* dynamically rendered (another conditional or a `.map`) —
21
+ * a lone conditional in an otherwise static list cannot drift the diff.
22
+ */
23
+
24
+ const ITERATOR_METHODS = new Set(['map', 'flatMap']);
25
+
26
+ const TRANSPARENT_EXPRESSIONS = new Set([
27
+ 'JSXExpressionContainer',
28
+ 'ParenthesizedExpression',
29
+ 'TSAsExpression',
30
+ 'TSNonNullExpression',
31
+ 'TSSatisfiesExpression',
32
+ ]);
33
+
34
+ /** A `<>…</>` node, or a `<Fragment>` / `<X.Fragment>` element with no `key`. */
35
+ export const isKeylessFragment = (node) => {
36
+ if (!node) return false;
37
+ if (node.type === 'JSXFragment') return true;
38
+ if (node.type !== 'JSXElement') return false;
39
+
40
+ const { name } = node.openingElement;
41
+ const local = name.type === 'JSXMemberExpression' ? name.property.name : name.name;
42
+ if (local !== 'Fragment') return false;
43
+
44
+ return !node.openingElement.attributes.some(
45
+ (attr) => (attr.type === 'JSXAttribute' && attr.name.name === 'key')
46
+ // a spread might carry a key — don't guess, treat as keyed
47
+ || attr.type === 'JSXSpreadAttribute',
48
+ );
49
+ };
50
+
51
+ const isSignificantChild = (child) => {
52
+ if (child.type === 'JSXText') return child.value.trim() !== '';
53
+ if (child.type === 'JSXExpressionContainer') return child.expression.type !== 'JSXEmptyExpression';
54
+ return true; // JSXElement | JSXFragment | JSXSpreadChild
55
+ };
56
+
57
+ const containsJsx = (node) => {
58
+ if (!node) return false;
59
+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') return true;
60
+ if (node.type === 'ConditionalExpression') {
61
+ return containsJsx(node.consequent) || containsJsx(node.alternate);
62
+ }
63
+ if (node.type === 'LogicalExpression') {
64
+ return containsJsx(node.left) || containsJsx(node.right);
65
+ }
66
+ if (TRANSPARENT_EXPRESSIONS.has(node.type)) return containsJsx(node.expression);
67
+ return false;
68
+ };
69
+
70
+ /** Is this JSX child rendered *dynamically* (a condition or an iterator)? */
71
+ const isDynamicChild = (child) => {
72
+ if (child.type !== 'JSXExpressionContainer') return false;
73
+
74
+ const expr = child.expression;
75
+ if (expr.type === 'LogicalExpression' || expr.type === 'ConditionalExpression') {
76
+ return containsJsx(expr);
77
+ }
78
+ return (
79
+ expr.type === 'CallExpression'
80
+ && expr.callee.type === 'MemberExpression'
81
+ && expr.callee.property.type === 'Identifier'
82
+ && ITERATOR_METHODS.has(expr.callee.property.name)
83
+ );
84
+ };
85
+
86
+ const isIteratorCallback = (fnNode) => {
87
+ const call = fnNode.parent;
88
+ return (
89
+ call
90
+ && call.type === 'CallExpression'
91
+ && call.arguments[0] === fnNode
92
+ && call.callee.type === 'MemberExpression'
93
+ && call.callee.property.type === 'Identifier'
94
+ && ITERATOR_METHODS.has(call.callee.property.name)
95
+ );
96
+ };
97
+
98
+ /**
99
+ * Walk outward from the fragment through transparent wrappers and conditional
100
+ * operators, and classify the first structural ancestor.
101
+ *
102
+ * @returns {{ kind: string, conditional?: boolean, siblingCount?: number, dynamicSibling?: boolean }}
103
+ */
104
+ export const classifyFragment = (fragment) => {
105
+ let cur = fragment;
106
+ let node = fragment.parent;
107
+ let conditional = false;
108
+
109
+ while (node) {
110
+ switch (node.type) {
111
+ case 'JSXExpressionContainer':
112
+ case 'ParenthesizedExpression':
113
+ case 'TSAsExpression':
114
+ case 'TSNonNullExpression':
115
+ case 'TSSatisfiesExpression':
116
+ case 'BlockStatement':
117
+ case 'ReturnStatement':
118
+ cur = node;
119
+ node = node.parent;
120
+ break;
121
+
122
+ case 'LogicalExpression':
123
+ if (node.right === cur || node.operator === '??') conditional = true;
124
+ cur = node;
125
+ node = node.parent;
126
+ break;
127
+
128
+ case 'ConditionalExpression':
129
+ if (node.consequent === cur || node.alternate === cur) conditional = true;
130
+ cur = node;
131
+ node = node.parent;
132
+ break;
133
+
134
+ case 'JSXElement':
135
+ case 'JSXFragment': {
136
+ // `cur` is the entry in `node.children` that holds our fragment
137
+ const others = node.children.filter((c) => c !== cur && isSignificantChild(c));
138
+ return {
139
+ kind: 'jsx-child',
140
+ conditional,
141
+ siblingCount: others.length,
142
+ dynamicSibling: others.some(isDynamicChild),
143
+ };
144
+ }
145
+
146
+ case 'ArrayExpression': {
147
+ const others = node.elements.filter((el) => el && el !== cur);
148
+ return {
149
+ kind: 'jsx-child',
150
+ conditional,
151
+ siblingCount: others.length,
152
+ dynamicSibling: others.some(containsJsx),
153
+ };
154
+ }
155
+
156
+ case 'ArrowFunctionExpression':
157
+ case 'FunctionExpression':
158
+ case 'FunctionDeclaration':
159
+ return { kind: isIteratorCallback(node) ? 'map-callback' : 'return' };
160
+
161
+ default:
162
+ return { kind: 'other' };
163
+ }
164
+ }
165
+ return { kind: 'other' };
166
+ };
167
+
168
+ /**
169
+ * @returns {'listItem' | 'conditionalSibling' | null}
170
+ */
171
+ export const analyzeFragment = (node, { strict = true } = {}) => {
172
+ if (!isKeylessFragment(node)) return null;
173
+
174
+ const {
175
+ kind,
176
+ conditional = false,
177
+ siblingCount = 0,
178
+ dynamicSibling = false,
179
+ } = classifyFragment(node);
180
+
181
+ if (kind === 'map-callback') return 'listItem';
182
+
183
+ if (
184
+ kind === 'jsx-child'
185
+ && conditional
186
+ && siblingCount >= 1
187
+ && (!strict || dynamicSibling)
188
+ ) {
189
+ return 'conditionalSibling';
190
+ }
191
+
192
+ return null;
193
+ };
194
+
195
+ export default {
196
+ meta: {
197
+ type: 'problem',
198
+ docs: {
199
+ description:
200
+ 'Require a `key` on a Fragment only when it is a list item or a conditional sibling '
201
+ + "(positions where Vue's un-keyed children diff can misalign).",
202
+ recommended: false,
203
+ },
204
+ schema: [
205
+ {
206
+ type: 'object',
207
+ properties: { strict: { type: 'boolean' } },
208
+ additionalProperties: false,
209
+ },
210
+ ],
211
+ messages: {
212
+ listItem:
213
+ 'This Fragment is a list item (`.map`). Give it a keyed root: `<Fragment key={…}>…</Fragment>`.',
214
+ conditionalSibling:
215
+ 'This conditional Fragment shares a child list with other dynamic siblings. '
216
+ + 'Vue diffs those children by position — give it `<Fragment key="…">…</Fragment>` '
217
+ + '(a stable literal is enough).',
218
+ },
219
+ },
220
+
221
+ create(context) {
222
+ const options = context.options[0] || {};
223
+
224
+ const check = (node) => {
225
+ const messageId = analyzeFragment(node, options);
226
+ if (messageId) context.report({ node, messageId });
227
+ };
228
+
229
+ return {
230
+ JSXFragment: check,
231
+ JSXElement: check,
232
+ };
233
+ },
234
+ };
@@ -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
+ });