eslint-plugin-kerfjs 5.0.0-beta.13 → 5.0.0-beta.131

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 (37) hide show
  1. package/README.md +85 -21
  2. package/docs/rules/ai-assistant-configs.md +17 -6
  3. package/docs/rules/no-generated-view-edits.md +42 -0
  4. package/docs/rules/no-inline-jsx-event-handlers.md +2 -2
  5. package/docs/rules/no-nested-mount.md +6 -1
  6. package/docs/rules/no-raw-with-dynamic-arg.md +7 -7
  7. package/docs/rules/prefer-attr-selector.md +7 -7
  8. package/docs/rules/prefer-module-jsx-augmentation.md +8 -4
  9. package/docs/rules/require-data-key-in-each.md +16 -6
  10. package/docs/rules/require-delegate-disposer.md +10 -5
  11. package/docs/rules/ui-component-ownership.md +43 -0
  12. package/docs/rules/ui-composition.md +116 -0
  13. package/docs/rules/ui-css-values.md +51 -0
  14. package/docs/rules/ui-exceptional-shorthands.md +22 -0
  15. package/docs/rules/ui-preferences.md +41 -0
  16. package/docs/rules/ui-public-boundaries.md +48 -0
  17. package/docs/rules/ui-wiring.md +57 -0
  18. package/index.js +51 -1
  19. package/lib/html-template-classes.js +104 -0
  20. package/lib/rules/ai-assistant-configs.js +184 -23
  21. package/lib/rules/no-generated-view-edits.js +81 -0
  22. package/lib/rules/no-inline-jsx-event-handlers.js +1 -1
  23. package/lib/rules/no-nested-mount.js +2 -1
  24. package/lib/rules/no-raw-with-dynamic-arg.js +7 -6
  25. package/lib/rules/prefer-module-jsx-augmentation.js +3 -2
  26. package/lib/rules/require-data-key-in-each.js +38 -3
  27. package/lib/rules/require-delegate-disposer.js +2 -1
  28. package/lib/rules/ui-component-ownership.js +211 -0
  29. package/lib/rules/ui-composition.js +425 -0
  30. package/lib/rules/ui-css-values.js +3 -0
  31. package/lib/rules/ui-exceptional-shorthands.js +3 -0
  32. package/lib/rules/ui-preferences.js +116 -0
  33. package/lib/rules/ui-public-boundaries.js +196 -0
  34. package/lib/rules/ui-wiring.js +440 -0
  35. package/lib/ui-contract.js +643 -0
  36. package/lib/ui-css-value-contracts.js +317 -0
  37. package/package.json +8 -2
@@ -14,24 +14,94 @@
14
14
  * flag.
15
15
  */
16
16
  import { createHash } from 'node:crypto';
17
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
17
+ import {
18
+ existsSync,
19
+ mkdirSync,
20
+ readFileSync,
21
+ realpathSync,
22
+ writeFileSync,
23
+ } from 'node:fs';
18
24
  import { createRequire } from 'node:module';
19
- import { dirname, join } from 'node:path';
25
+ import { dirname, join, resolve, relative } from 'node:path';
20
26
 
21
27
  const MARKER = '<!-- KERF-APP-CANONICAL-END · your customizations below -->';
22
28
  const VERSION_RE = /kerf-skill-version:\s*(\d+\.\d+\.\d+(?:-[\w.]+)?)/;
23
29
  const VERSION_SCAN_BYTES = 512;
30
+ const SHARED_SKILL_PREFIX =
31
+ '---\nname: kerf-app\ndescription: Use the shared workspace guidance for Kerf application work.\n---\n\n@';
32
+ const SHARED_UI_SKILL_PREFIX =
33
+ '---\nname: kerf-ui\ndescription: Use shared workspace guidance and the installed @kerfjs/ui instructions.\n---\n\n@';
34
+ const SHARED_UI_SKILL_SUFFIX =
35
+ '\n\nIn the selected package, read `node_modules/@kerfjs/ui/llms.txt` first, then `node_modules/@kerfjs/ui/ai/skill.md` and the component references they name.\n';
36
+
37
+ function sharedGuidanceSource(cwd) {
38
+ try {
39
+ const state = JSON.parse(
40
+ readFileSync(join(cwd, '.kerf-ai-setup.json'), 'utf8'),
41
+ );
42
+ const sources = new Set(
43
+ Object.values(state.packages ?? {})
44
+ .map((entry) => entry.guidanceSource)
45
+ .filter(Boolean),
46
+ );
47
+ return sources.size === 1 ? [...sources][0] : null;
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ function guidanceRoot(cwd) {
54
+ let current = cwd;
55
+ while (true) {
56
+ if (existsSync(join(current, '.kerf-ai-setup.json'))) return current;
57
+ const parent = dirname(current);
58
+ if (parent === current) return cwd;
59
+ current = parent;
60
+ }
61
+ }
62
+
63
+ function sharedSkill(file, cwd, source) {
64
+ const importPath = relative(
65
+ dirname(join(cwd, file.dest)),
66
+ join(cwd, source),
67
+ ).replaceAll('\\', '/');
68
+ return file.name === 'ui-skill'
69
+ ? `${SHARED_UI_SKILL_PREFIX}${importPath}${SHARED_UI_SKILL_SUFFIX}`
70
+ : `${SHARED_SKILL_PREFIX}${importPath}\n`;
71
+ }
72
+
73
+ function usesUi(cwd) {
74
+ try {
75
+ const state = JSON.parse(
76
+ readFileSync(join(cwd, '.kerf-ai-setup.json'), 'utf8'),
77
+ );
78
+ if (
79
+ Object.values(state.packages ?? {}).some((entry) => entry.mode === 'ui')
80
+ )
81
+ return true;
82
+ } catch {
83
+ // A consumer may not have run setup yet.
84
+ }
85
+ try {
86
+ const manifest = JSON.parse(
87
+ readFileSync(join(cwd, 'package.json'), 'utf8'),
88
+ );
89
+ return ['dependencies', 'devDependencies', 'peerDependencies'].some(
90
+ (group) => Boolean(manifest[group]?.['@kerfjs/ui']),
91
+ );
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
24
96
 
25
97
  // Module-level once-per-lint-run guard. ESLint instantiates the rule
26
98
  // per-file; we do the project-level filesystem check the first time the
27
- // `Program` visitor runs and cache the result for the remaining files in
28
- // the same lint pass.
99
+ // `Program` visitor runs and skip it for the remaining files in the same
100
+ // lint pass.
29
101
  let CHECKED = false;
30
- let CACHED_RESULT = null;
31
102
 
32
103
  export function _resetForTests() {
33
104
  CHECKED = false;
34
- CACHED_RESULT = null;
35
105
  }
36
106
 
37
107
  function resolveManifestPath(cwd) {
@@ -105,9 +175,59 @@ export function classifyFile(file, bundleDir, cwd) {
105
175
  return { state: 'missing' };
106
176
  }
107
177
 
178
+ if (
179
+ (file.name === 'skill' || file.name === 'ui-skill') &&
180
+ /^---\nname: kerf-(?:app|ui)\n/.test(consumer) &&
181
+ /\n@[^\n]+\n/.test(consumer)
182
+ ) {
183
+ const prefix =
184
+ file.name === 'ui-skill' ? SHARED_UI_SKILL_PREFIX : SHARED_SKILL_PREFIX;
185
+ const suffix = file.name === 'ui-skill' ? SHARED_UI_SKILL_SUFFIX : '\n';
186
+ const match =
187
+ consumer.startsWith(prefix) && consumer.endsWith(suffix)
188
+ ? [null, consumer.slice(prefix.length, -suffix.length)]
189
+ : null;
190
+ if (!match)
191
+ return { state: 'forked', reason: 'malformed shared guidance import' };
192
+ const sourcePath = resolve(dirname(destAbs), match[1]);
193
+ const sourceRelative = relative(cwd, sourcePath);
194
+ if (sourceRelative === '..' || sourceRelative.startsWith('../'))
195
+ return {
196
+ state: 'forked',
197
+ reason: 'shared guidance import escapes the workspace',
198
+ };
199
+ let source;
200
+ try {
201
+ const actualRelative = relative(
202
+ realpathSync(cwd),
203
+ realpathSync(sourcePath),
204
+ );
205
+ if (actualRelative === '..' || actualRelative.startsWith('../'))
206
+ return {
207
+ state: 'forked',
208
+ reason: 'shared guidance import escapes the workspace',
209
+ };
210
+ source = readFileSync(sourcePath, 'utf8');
211
+ } catch {
212
+ return { state: 'forked', reason: 'shared guidance source is missing' };
213
+ }
214
+ if (
215
+ !/\bkerf(?:js)?\b/i.test(source) ||
216
+ !/(?:kerf:check|npm run check)/i.test(source)
217
+ )
218
+ return {
219
+ state: 'forked',
220
+ reason:
221
+ 'shared guidance source lacks Kerf or project check instructions',
222
+ };
223
+ return { state: 'ok' };
224
+ }
225
+
108
226
  const markerIdx = findMarkerIndex(consumer);
109
- if (markerIdx === -1) return { state: 'forked', reason: 'no canonical-end marker' };
110
- if (markerIdx === -2) return { state: 'forked', reason: 'multiple canonical-end markers' };
227
+ if (markerIdx === -1)
228
+ return { state: 'forked', reason: 'no canonical-end marker' };
229
+ if (markerIdx === -2)
230
+ return { state: 'forked', reason: 'multiple canonical-end markers' };
111
231
 
112
232
  const canonicalEnd = canonicalEndOffset(consumer);
113
233
  const consumerCanonical = consumer.slice(0, canonicalEnd);
@@ -134,7 +254,10 @@ export function classifyFile(file, bundleDir, cwd) {
134
254
  };
135
255
  }
136
256
  if (consumerCanonicalHash !== historicalHash) {
137
- return { state: 'forked', reason: 'content above marker has been edited' };
257
+ return {
258
+ state: 'forked',
259
+ reason: 'content above marker has been edited',
260
+ };
138
261
  }
139
262
  return {
140
263
  state: 'stale',
@@ -163,8 +286,12 @@ function loadBundle(cwd) {
163
286
 
164
287
  function isTriggered(name, cwd) {
165
288
  if (name === 'skill') return existsSync(join(cwd, '.claude'));
289
+ if (name === 'ui-skill')
290
+ return existsSync(join(cwd, '.claude')) && usesUi(cwd);
166
291
  if (name === 'cursorrules') {
167
- return existsSync(join(cwd, '.cursorrules')) || existsSync(join(cwd, '.cursor'));
292
+ return (
293
+ existsSync(join(cwd, '.cursorrules')) || existsSync(join(cwd, '.cursor'))
294
+ );
168
295
  }
169
296
  return false;
170
297
  }
@@ -176,12 +303,27 @@ function isTriggered(name, cwd) {
176
303
  export function runCheck(cwd) {
177
304
  const bundle = loadBundle(cwd);
178
305
  if (!bundle) return null;
306
+ const root = guidanceRoot(cwd);
179
307
  const results = [];
308
+ const sharedSource = sharedGuidanceSource(root);
180
309
  for (const file of bundle.manifest.files) {
181
- if (!isTriggered(file.name, cwd)) continue;
182
- results.push({ file, result: classifyFile(file, bundle.bundleDir, cwd) });
310
+ if (!isTriggered(file.name, root)) continue;
311
+ let result = classifyFile(file, bundle.bundleDir, root);
312
+ if (
313
+ (file.name === 'skill' || file.name === 'ui-skill') &&
314
+ sharedSource &&
315
+ result.state === 'ok'
316
+ ) {
317
+ const actual = readFileSync(join(root, file.dest), 'utf8');
318
+ if (actual !== sharedSkill(file, root, sharedSource))
319
+ result = {
320
+ state: 'forked',
321
+ reason: 'expected the configured shared guidance import',
322
+ };
323
+ }
324
+ results.push({ file, result });
183
325
  }
184
- return { results, bundleDir: bundle.bundleDir };
326
+ return { results, bundleDir: bundle.bundleDir, guidanceRoot: root };
185
327
  }
186
328
 
187
329
  /**
@@ -191,7 +333,12 @@ export function runCheck(cwd) {
191
333
  */
192
334
  export function applyFix(file, bundleDir, cwd, appendZone) {
193
335
  const bundlePath = join(bundleDir, file.bundle.replace(/^ai\//, ''));
194
- const canonical = readFileSync(bundlePath, 'utf8');
336
+ const sharedSource =
337
+ (file.name === 'skill' || file.name === 'ui-skill') &&
338
+ sharedGuidanceSource(cwd);
339
+ const canonical = sharedSource
340
+ ? sharedSkill(file, cwd, sharedSource)
341
+ : readFileSync(bundlePath, 'utf8');
195
342
  const dest = join(cwd, file.dest);
196
343
  mkdirSync(dirname(dest), { recursive: true });
197
344
  writeFileSync(dest, canonical + (appendZone || ''));
@@ -220,7 +367,7 @@ const meta = {
220
367
  stale:
221
368
  '{{tool}} drop-in at `{{dest}}` is stale (have {{consumerVersion}}, latest is {{bundledVersion}}). Run `eslint --fix` to update the canonical section above the `KERF-APP-CANONICAL-END` marker; your customizations below the marker are preserved.',
222
369
  forked:
223
- '{{tool}} drop-in at `{{dest}}` is forked: {{reason}}. Restore the canonical layout (one `KERF-APP-CANONICAL-END` marker, no edits above it) or disable this rule with `\'kerfjs/ai-assistant-configs\': \'off\'`.',
370
+ "{{tool}} drop-in at `{{dest}}` is forked: {{reason}}. Restore the canonical layout (one `KERF-APP-CANONICAL-END` marker, no edits above it) or disable this rule with `'kerfjs/ai-assistant-configs': 'off'`.",
224
371
  },
225
372
  // Mark as fixable so the CLI exposes this rule under `--fix`. The callback
226
373
  // writes to a separate file and returns null, so ESLint applies no edit to
@@ -239,15 +386,23 @@ function create(context) {
239
386
  // ESLint v9: `context.cwd` is a string. ESLint v8: `context.getCwd()`.
240
387
  const cwd = contextCwd(context);
241
388
  const checked = runCheck(cwd);
242
- CACHED_RESULT = checked;
243
389
  if (!checked) return;
244
390
 
245
391
  for (const { file, result } of checked.results) {
246
- if (file.name === 'skill' && !claudeEnabled) continue;
392
+ if (
393
+ (file.name === 'skill' || file.name === 'ui-skill') &&
394
+ !claudeEnabled
395
+ )
396
+ continue;
247
397
  if (file.name === 'cursorrules' && !cursorEnabled) continue;
248
398
  if (result.state === 'ok') continue;
249
399
 
250
- const tool = file.name === 'skill' ? 'Claude Code kerf-app skill' : 'Cursor kerf rules';
400
+ const tool =
401
+ file.name === 'skill'
402
+ ? 'Claude Code kerf-app skill'
403
+ : file.name === 'ui-skill'
404
+ ? 'Claude Code kerf-ui skill'
405
+ : 'Cursor kerf rules';
251
406
  const bundle = file.bundle; // e.g. 'ai/skill.md'
252
407
  const data = { tool, dest: file.dest, bundle };
253
408
 
@@ -257,7 +412,8 @@ function create(context) {
257
412
  messageId: 'missing',
258
413
  data,
259
414
  fix() {
260
- if (isFixCliRun()) applyFix(file, checked.bundleDir, cwd, '');
415
+ if (isFixCliRun())
416
+ applyFix(file, checked.bundleDir, checked.guidanceRoot, '');
261
417
  return null;
262
418
  },
263
419
  });
@@ -272,7 +428,12 @@ function create(context) {
272
428
  },
273
429
  fix() {
274
430
  if (isFixCliRun()) {
275
- applyFix(file, checked.bundleDir, cwd, result.appendZone);
431
+ applyFix(
432
+ file,
433
+ checked.bundleDir,
434
+ checked.guidanceRoot,
435
+ result.appendZone,
436
+ );
276
437
  }
277
438
  return null;
278
439
  },
@@ -291,9 +452,9 @@ function create(context) {
291
452
 
292
453
  function contextCwd(context) {
293
454
  return (
294
- (typeof context.cwd === 'string' && context.cwd)
295
- || (typeof context.getCwd === 'function' && context.getCwd())
296
- || process.cwd()
455
+ (typeof context.cwd === 'string' && context.cwd) ||
456
+ (typeof context.getCwd === 'function' && context.getCwd()) ||
457
+ process.cwd()
297
458
  );
298
459
  }
299
460
 
@@ -0,0 +1,81 @@
1
+ import { existsSync } from 'node:fs';
2
+
3
+ // Generated Kerf UI view modules (docs/26-ui-editor.md §5.2) are read-only:
4
+ // application code integrates through their exports and never edits them.
5
+ // The generator records a digest of the module body in its header; this rule
6
+ // recomputes it, so a hand edit (or a half-applied regeneration) is reported
7
+ // without access to the source document.
8
+
9
+ const STAMP =
10
+ /^\/\/ kui-view: \d+ contract (kui1:[0-9a-f]{16}) source kui1:[0-9a-f]{16} body (kui1:[0-9a-f]{16})$/;
11
+ const GENERATED = '// GENERATED by kerf-ui-view';
12
+ const HEADER_LINES = 3;
13
+ const VIEW_FILE = /\.view\.(?:d\.ts|ts|js)$/;
14
+ const MASK = 0xffffffffffffffffn;
15
+
16
+ /**
17
+ * `kui1:` + 16 hex digits of the 64-bit FNV-1a hash of `text`'s UTF-8 bytes —
18
+ * the same digest `@kerfjs/ui/view`'s `viewDigest` computes (pinned by a
19
+ * parity test), duplicated so the plugin needs no runtime dependency on it.
20
+ */
21
+ export function viewDigest(text) {
22
+ let hash = 0xcbf29ce484222325n;
23
+ for (const byte of new TextEncoder().encode(text)) {
24
+ hash ^= BigInt(byte);
25
+ hash = (hash * 0x100000001b3n) & MASK;
26
+ }
27
+ return `kui1:${hash.toString(16).padStart(16, '0')}`;
28
+ }
29
+
30
+ /** The `.kui.json` document a generated module's path would come from. */
31
+ const documentFor = (filename) => filename.replace(VIEW_FILE, '.kui.json');
32
+
33
+ export default {
34
+ meta: {
35
+ type: 'problem',
36
+ docs: {
37
+ description:
38
+ 'Disallow hand edits to generated Kerf UI view modules (*.view.ts).',
39
+ url: 'https://github.com/brianwestphal/kerf/blob/main/eslint-plugin/docs/rules/no-generated-view-edits.md',
40
+ },
41
+ schema: [],
42
+ messages: {
43
+ edited:
44
+ 'This generated view module was edited by hand (its body no longer matches its kerf-ui-view header). Regenerate it with `kerf-ui-view generate`; put behavior, overrides, and wiring in your own files that import it.',
45
+ header:
46
+ 'This generated view module has a damaged kerf-ui-view header. Regenerate it with `kerf-ui-view generate` instead of editing it.',
47
+ missing:
48
+ 'A module beside a `.kui.json` view document must be the generated one. Run `kerf-ui-view generate` rather than writing it by hand.',
49
+ },
50
+ },
51
+ create(context) {
52
+ const filename = context.filename ?? context.getFilename();
53
+ const sourceCode = context.sourceCode ?? context.getSourceCode();
54
+ return {
55
+ Program(node) {
56
+ // Git checkouts may convert line endings; the digest covers LF text.
57
+ const lines = sourceCode.text.replace(/\r\n/g, '\n').split('\n');
58
+ if (!lines[0]?.startsWith(GENERATED)) {
59
+ if (VIEW_FILE.test(filename) && existsSync(documentFor(filename))) {
60
+ context.report({ node, messageId: 'missing' });
61
+ }
62
+ return;
63
+ }
64
+ const stamp = STAMP.exec(lines[1] ?? '');
65
+ const contract = /^\/\/ kui-contract: (.*)$/.exec(lines[2] ?? '');
66
+ if (!stamp || !contract) {
67
+ context.report({ node, messageId: 'header' });
68
+ return;
69
+ }
70
+ // The body digest covers the code; the contract digest covers the
71
+ // recorded contract line (its canonical JSON).
72
+ if (
73
+ viewDigest(lines.slice(HEADER_LINES).join('\n')) !== stamp[2] ||
74
+ viewDigest(contract[1]) !== stamp[1]
75
+ ) {
76
+ context.report({ node, messageId: 'edited' });
77
+ }
78
+ },
79
+ };
80
+ },
81
+ };
@@ -7,7 +7,7 @@ const meta = {
7
7
  type: 'problem',
8
8
  docs: {
9
9
  description:
10
- "Disallow inline `onClick`-style JSX event handler attributes; use `data-action` + `delegate()` instead.",
10
+ 'Disallow inline `onClick`-style JSX event handler attributes; use `data-action` + `delegate()` instead.',
11
11
  url: 'https://github.com/brianwestphal/kerf/blob/main/eslint-plugin/docs/rules/no-inline-jsx-event-handlers.md',
12
12
  },
13
13
  schema: [],
@@ -34,7 +34,8 @@ function create(context) {
34
34
  let p = node.parent;
35
35
  while (p) {
36
36
  if (
37
- (p.type === 'ArrowFunctionExpression' || p.type === 'FunctionExpression') &&
37
+ (p.type === 'ArrowFunctionExpression' ||
38
+ p.type === 'FunctionExpression') &&
38
39
  isMountCall(p.parent) &&
39
40
  p.parent.arguments.includes(p)
40
41
  ) {
@@ -22,13 +22,13 @@ const meta = {
22
22
  type: 'problem',
23
23
  docs: {
24
24
  description:
25
- "Disallow `raw()` with dynamic arguments; `raw()` bypasses HTML escaping and passing dynamic values is an XSS vector.",
25
+ 'Disallow `raw()` with dynamic arguments; `raw()` bypasses HTML escaping and passing dynamic values is an XSS vector.',
26
26
  url: 'https://github.com/brianwestphal/kerf/blob/main/eslint-plugin/docs/rules/no-raw-with-dynamic-arg.md',
27
27
  },
28
28
  schema: [],
29
29
  messages: {
30
30
  dynamic:
31
- "`raw()` bypasses HTML auto-escaping. Passing a dynamic value is an XSS risk unless the input has been sanitized. Sanitize first (`DOMPurify.sanitize(...)`) then pass to `raw()`, or add `// eslint-disable-next-line kerfjs/no-raw-with-dynamic-arg` to mark a call as intentionally safe.",
31
+ '`raw()` bypasses HTML auto-escaping. Passing a dynamic value is an XSS risk unless the input has been sanitized. Sanitize first (`DOMPurify.sanitize(...)`) then pass to `raw()`, or add `// eslint-disable-next-line kerfjs/no-raw-with-dynamic-arg` to mark a call as intentionally safe.',
32
32
  },
33
33
  };
34
34
 
@@ -47,10 +47,11 @@ function create(context) {
47
47
  const callee = node.callee;
48
48
  if (!callee) return;
49
49
  // Match bare `raw(...)` and `kerfjs.raw(...)` / `kerf.raw(...)` shapes.
50
- const isRaw = (callee.type === 'Identifier' && callee.name === 'raw')
51
- || (callee.type === 'MemberExpression'
52
- && callee.property.type === 'Identifier'
53
- && callee.property.name === 'raw');
50
+ const isRaw =
51
+ (callee.type === 'Identifier' && callee.name === 'raw') ||
52
+ (callee.type === 'MemberExpression' &&
53
+ callee.property.type === 'Identifier' &&
54
+ callee.property.name === 'raw');
54
55
  if (!isRaw) return;
55
56
  if (node.arguments.length === 0) return;
56
57
  const arg = node.arguments[0];
@@ -10,7 +10,8 @@ function findGlobalJSXIntrinsics(moduleBlock) {
10
10
  for (const m of moduleBlock.body) {
11
11
  if (m.type !== 'TSModuleDeclaration') continue;
12
12
  const idNode = m.id;
13
- if (!idNode || idNode.type !== 'Identifier' || idNode.name !== 'JSX') continue;
13
+ if (!idNode || idNode.type !== 'Identifier' || idNode.name !== 'JSX')
14
+ continue;
14
15
  const inner = m.body;
15
16
  if (!inner || inner.type !== 'TSModuleBlock') continue;
16
17
  for (const member of inner.body) {
@@ -31,7 +32,7 @@ const meta = {
31
32
  type: 'problem',
32
33
  docs: {
33
34
  description:
34
- "Declaration-merge `JSX.IntrinsicElements` into `kerfjs/jsx-runtime`, not the global namespace.",
35
+ 'Declaration-merge `JSX.IntrinsicElements` into `kerfjs/jsx-runtime`, not the global namespace.',
35
36
  url: 'https://github.com/brianwestphal/kerf/blob/main/eslint-plugin/docs/rules/prefer-module-jsx-augmentation.md',
36
37
  },
37
38
  schema: [],
@@ -19,6 +19,32 @@ function findRootJSXFromBody(body) {
19
19
  return null;
20
20
  }
21
21
 
22
+ function isComponentRoot(name) {
23
+ return (
24
+ name.type === 'JSXMemberExpression' ||
25
+ (name.type === 'JSXIdentifier' && /^[A-Z]/.test(name.name))
26
+ );
27
+ }
28
+
29
+ function isKeyName(name) {
30
+ return name === 'data-key' || name === 'id';
31
+ }
32
+
33
+ function hasKeyInRootAttributes(attribute) {
34
+ const value = attribute.value;
35
+ const object = value?.type === 'JSXExpressionContainer' && value.expression;
36
+ if (!object || object.type !== 'ObjectExpression') return false;
37
+ for (let index = object.properties.length - 1; index >= 0; index--) {
38
+ const property = object.properties[index];
39
+ // A later spread or computed name could overwrite an earlier key.
40
+ if (property.type !== 'Property' || property.computed) return false;
41
+ const key = property.key;
42
+ if (isKeyName(key.type === 'Identifier' ? key.name : key.value))
43
+ return true;
44
+ }
45
+ return false;
46
+ }
47
+
22
48
  const meta = {
23
49
  type: 'problem',
24
50
  docs: {
@@ -38,10 +64,15 @@ const meta = {
38
64
  function create(context) {
39
65
  return {
40
66
  CallExpression(node) {
41
- if (node.callee.type !== 'Identifier' || node.callee.name !== 'each') return;
67
+ if (node.callee.type !== 'Identifier' || node.callee.name !== 'each')
68
+ return;
42
69
  const cb = node.arguments[1];
43
70
  if (!cb) return;
44
- if (cb.type !== 'ArrowFunctionExpression' && cb.type !== 'FunctionExpression') return;
71
+ if (
72
+ cb.type !== 'ArrowFunctionExpression' &&
73
+ cb.type !== 'FunctionExpression'
74
+ )
75
+ return;
45
76
  const root = findRootJSXFromBody(cb.body);
46
77
  if (!root) return;
47
78
  if (root.type === 'JSXFragment') {
@@ -49,11 +80,15 @@ function create(context) {
49
80
  return;
50
81
  }
51
82
  const attrs = root.openingElement.attributes;
83
+ const componentRoot = isComponentRoot(root.openingElement.name);
52
84
  const hasKey = attrs.some((a) => {
53
85
  if (a.type === 'JSXSpreadAttribute') return true;
54
86
  if (a.type !== 'JSXAttribute') return false;
55
87
  const n = a.name && a.name.name;
56
- return n === 'data-key' || n === 'id';
88
+ return (
89
+ isKeyName(n) ||
90
+ (componentRoot && n === 'rootAttributes' && hasKeyInRootAttributes(a))
91
+ );
57
92
  });
58
93
  if (!hasKey) {
59
94
  context.report({ node: root.openingElement, messageId: 'missingKey' });
@@ -52,7 +52,8 @@ function create(context) {
52
52
  // the disposer is being routed somewhere reachable — accept.
53
53
  const parent = node.parent;
54
54
  if (!parent) return;
55
- if (parent.type === 'UnaryExpression' && parent.operator === 'void') return;
55
+ if (parent.type === 'UnaryExpression' && parent.operator === 'void')
56
+ return;
56
57
  if (parent.type !== 'ExpressionStatement') return;
57
58
 
58
59
  context.report({