eslint-plugin-kerfjs 5.0.0-beta.132 → 5.0.0-beta.135

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/README.md CHANGED
@@ -13,7 +13,7 @@ This plugin sits alongside two other defense layers shipped by [`kerfjs`](https:
13
13
  | Opt-in dev-warns (`KERF_DEV_WARN_*`) | Hard Rules 4 (rebuilt listeners), 7 (untracked signals), 8 (narrow set) | Runtime |
14
14
  | **This plugin** | Hard Rules 2, 5, 6, 10, 12 — AST-shaped antipatterns; plus rename-safety / `raw()`-audit nudges and a project-hygiene check for the bundled AI-assistant configs | **Edit time** |
15
15
 
16
- The core syntax rules analyze the AST without TypeScript parser services. `ai-assistant-configs` reads the filesystem, and the optional UI rules also resolve catalog and profile artifacts. Consumers configure their own parser; no `@typescript-eslint/parser` _service_ is required.
16
+ The core syntax rules analyze the AST without TypeScript parser services. `ai-assistant-configs` reads the filesystem, and the optional UI rules also resolve catalog and profile artifacts. Consumers configure their own parser. The optional `prefer-signal-leaf` suggestion uses an existing TypeScript parser service.
17
17
 
18
18
  ## Install
19
19
 
@@ -77,7 +77,7 @@ settings: {
77
77
  }
78
78
  ```
79
79
 
80
- For deterministic generated configs, the same settings accept parsed `catalog`, `selectionCatalog`, and `profile` objects. File-based precedence is package defaults, then workspace profile, then root-to-leaf directory profiles. The rules load `application-ui-profile-sync.cjs` from the installed `@kerfjs/ui` package by default because ESLint rule creation is synchronous; `profileContractPath` is only needed when artifacts are vendored, and then its directory must also hold `application-ui-diagnostic-ids-v1.json` and `component-class-owners.cjs` (the class-to-component rule `KUI-L103` shares with `@kerfjs/ui`'s generated component pages) from the same `@kerfjs/ui` release. Every raw layer is schema- and catalog-reference-validated before merge, so a child cannot hide malformed or stale parent policy. Exceptions use exact `KUI-L*` diagnostic ids and repository-relative file or directory targets.
80
+ For deterministic generated configs, the same settings accept parsed `catalog`, `selectionCatalog`, and `profile` objects. File-based precedence is package defaults, then workspace profile, then root-to-leaf directory profiles. The rules load `application-ui-profile-sync.cjs` from the installed `@kerfjs/ui` package by default because ESLint rule creation is synchronous; `profileContractPath` is only needed when artifacts are vendored, and then its directory must also hold `application-ui-diagnostic-ids-v1.json` and `choice-wiring-mode.cjs` plus `component-class-owners.cjs` (the class-to-component rule `KUI-L103` shares with `@kerfjs/ui`'s generated component pages) from the same `@kerfjs/ui` release. Every raw layer is schema- and catalog-reference-validated before merge, so a child cannot hide malformed or stale parent policy. Exceptions use exact `KUI-L*` diagnostic ids and repository-relative file or directory targets.
81
81
 
82
82
  When linting a nested workspace package, set `workspaceRoot` to the repository root. Installed `@kerfjs/ui` assets still resolve from ESLint's package `cwd`, while profile discovery and exception targets use the workspace root.
83
83
 
@@ -118,6 +118,7 @@ Use flat config (`eslint.config.js`), shown above. The `legacy-recommended` expo
118
118
  | [`require-delegate-disposer`](docs/rules/require-delegate-disposer.md) | 5 — capture `delegate()` disposers when scope < page | `warn` |
119
119
  | [`no-nested-mount`](docs/rules/no-nested-mount.md) | 6 — one `mount()` per root | `error` |
120
120
  | [`prefer-module-jsx-augmentation`](docs/rules/prefer-module-jsx-augmentation.md) | 12 — augment `kerfjs/jsx-runtime`, not global | `error` |
121
+ | [`prefer-signal-leaf`](docs/rules/prefer-signal-leaf.md) | — (typed editor suggestion for a mounted DOM leaf) | off |
121
122
  | [`prefer-attr-selector`](docs/rules/prefer-attr-selector.md) | — (rename-safety nudge for `delegate()` selectors) | `warn` |
122
123
  | [`no-raw-with-dynamic-arg`](docs/rules/no-raw-with-dynamic-arg.md) | — (XSS audit trail) | `warn` |
123
124
  | [`ai-assistant-configs`](docs/rules/ai-assistant-configs.md) | — (project hygiene) | `warn` |
@@ -0,0 +1,43 @@
1
+ # `kerfjs/prefer-signal-leaf`
2
+
3
+ An editor suggestion can move a dependency from a Kerf mount render to one DOM text node or attribute. If a signal is the render's only dependency, subsequent writes update the bound node without running the render again.
4
+
5
+ ```tsx
6
+ import { mount, signal } from "kerfjs";
7
+
8
+ const label = signal("Ready");
9
+ mount(root, () => <span>{label.value}</span>);
10
+ // Editor suggestion: <span>{label}</span>
11
+ ```
12
+
13
+ ## Enabling the rule
14
+
15
+ Add a flat-config entry to the project's existing ESLint configuration. Install `@typescript-eslint/parser` and its supported TypeScript peer. The rule uses the TypeScript program supplied by the parser. All Kerf presets leave it off.
16
+
17
+ ```js
18
+ import kerfjs from "eslint-plugin-kerfjs";
19
+ import parser from "@typescript-eslint/parser";
20
+
21
+ export default [
22
+ {
23
+ files: ["**/*.tsx"],
24
+ languageOptions: { parser, parserOptions: { projectService: true } },
25
+ plugins: { kerfjs },
26
+ rules: { "kerfjs/prefer-signal-leaf": "warn" },
27
+ },
28
+ ];
29
+ ```
30
+
31
+ The file's TypeScript project needs strict null checks, automatic JSX (`react-jsx` or `react-jsxdev`), and `jsxImportSource: "kerfjs"`. An untyped file receives no suggestions. Files with JSX pragmas are skipped.
32
+
33
+ ## Which reads qualify?
34
+
35
+ - A direct text child containing just `name.value` with a string or number payload, or `title={name.value}` with a string payload.
36
+ - `name` is a stable `const` outside the render, initialized by a named `signal` or `computed` import from `kerfjs`. Aliases work. A similarly shaped object, a getter, or a nullable or erased signal type gives insufficient evidence.
37
+ - The element is returned directly by an inline callback passed to the imported Kerf `mount`. Its JSX ancestors are fragments or ordinary `div`, `span`, `small`, `em`, or `strong` elements. The narrow list avoids raw-text, form, SVG, parser-sensitive and custom-element contexts. Spreads, content editing and explicit morph ownership can change who controls a node, so those hosts and their descendants are skipped.
38
+
39
+ Reads used for branching, formatting, custom component props, and list rows need a separate decision about who should subscribe. A signal carrying `SafeHtml` can render markup when read in JSX, whereas a direct text binding would stringify its value.
40
+
41
+ ## Reviewing the suggestion
42
+
43
+ Review work elsewhere in the mount that relies on a rerender, including effects of calling other functions. Apply the suggestion when the text or title should update independently. Code that observes child-node boundaries, parser normalization of control characters, or mount invocation counts can observe the change. ESLint offers the edit in the editor and leaves the file alone under `--fix`. The runtime `valueOnlyRerender` warning observes actual renders and can surface patterns outside this rule's static checks.
package/index.js CHANGED
@@ -4,6 +4,7 @@ import noNestedMount from './lib/rules/no-nested-mount.js';
4
4
  import noRawWithDynamicArg from './lib/rules/no-raw-with-dynamic-arg.js';
5
5
  import preferAttrSelector from './lib/rules/prefer-attr-selector.js';
6
6
  import preferModuleJsxAugmentation from './lib/rules/prefer-module-jsx-augmentation.js';
7
+ import preferSignalLeaf from './lib/rules/prefer-signal-leaf.js';
7
8
  import requireDataKeyInEach from './lib/rules/require-data-key-in-each.js';
8
9
  import requireDelegateDisposer from './lib/rules/require-delegate-disposer.js';
9
10
  import uiComponentOwnership from './lib/rules/ui-component-ownership.js';
@@ -15,7 +16,7 @@ import uiPublicBoundaries from './lib/rules/ui-public-boundaries.js';
15
16
  import uiWiring from './lib/rules/ui-wiring.js';
16
17
 
17
18
  const plugin = {
18
- meta: { name: 'eslint-plugin-kerfjs', version: '5.0.0-beta.132' },
19
+ meta: { name: 'eslint-plugin-kerfjs', version: '5.0.0-beta.135' },
19
20
  rules: {
20
21
  'no-inline-jsx-event-handlers': noInlineJsxEventHandlers,
21
22
  'no-raw-with-dynamic-arg': noRawWithDynamicArg,
@@ -24,6 +25,7 @@ const plugin = {
24
25
  'no-nested-mount': noNestedMount,
25
26
  'prefer-module-jsx-augmentation': preferModuleJsxAugmentation,
26
27
  'prefer-attr-selector': preferAttrSelector,
28
+ 'prefer-signal-leaf': preferSignalLeaf,
27
29
  'ai-assistant-configs': aiAssistantConfigs,
28
30
  'ui-component-ownership': uiComponentOwnership,
29
31
  'ui-composition': uiComposition,
@@ -0,0 +1,206 @@
1
+ // Only hosts that parse in ordinary HTML flow and have no form/editing state.
2
+ const hosts = new Set(['div', 'span', 'small', 'em', 'strong']);
3
+ const ownershipAttributes = new Set([
4
+ 'contenteditable',
5
+ 'data-morph-skip',
6
+ 'data-morph-skip-children',
7
+ 'data-morph-preserve',
8
+ 'is',
9
+ 'xmlns',
10
+ 'children',
11
+ 'data-kfb',
12
+ 'data-kfbrow',
13
+ ]);
14
+
15
+ function definition(source, identifier) {
16
+ for (let scope = source.getScope(identifier); scope; scope = scope.upper) {
17
+ const variable = scope.set.get(identifier.name);
18
+ if (variable) return variable.defs.length === 1 ? variable.defs[0] : null;
19
+ }
20
+ return null;
21
+ }
22
+
23
+ function importedName(source, node) {
24
+ if (node.type !== 'Identifier') return null;
25
+ const def = definition(source, node);
26
+ if (
27
+ def?.type !== 'ImportBinding' ||
28
+ def.parent.source.value !== 'kerfjs' ||
29
+ def.node.type !== 'ImportSpecifier' ||
30
+ def.node.importKind === 'type' ||
31
+ def.parent.importKind === 'type'
32
+ )
33
+ return null;
34
+ return def.node.imported.name;
35
+ }
36
+
37
+ function ordinaryHost(element) {
38
+ const opening = element.openingElement;
39
+ if (opening.name.type !== 'JSXIdentifier' || !hosts.has(opening.name.name))
40
+ return false;
41
+ const seen = new Set();
42
+ for (const attribute of opening.attributes) {
43
+ if (
44
+ attribute.type !== 'JSXAttribute' ||
45
+ attribute.name.type !== 'JSXIdentifier'
46
+ )
47
+ return false;
48
+ const name = attribute.name.name.toLowerCase();
49
+ if (ownershipAttributes.has(name) || seen.has(name)) return false;
50
+ seen.add(name);
51
+ }
52
+ return true;
53
+ }
54
+
55
+ // Follow only direct JSX children to the inline callback return. A wrapper
56
+ // component, slot, helper call, or nested callback can change hole ownership.
57
+ function mountCallback(element, source) {
58
+ let node = element;
59
+ while (node.type === 'JSXElement' || node.type === 'JSXFragment') {
60
+ if (node.type === 'JSXElement' && !ordinaryHost(node)) return null;
61
+ node = node.parent;
62
+ }
63
+ if (node.type === 'ReturnStatement' && node.parent.type === 'BlockStatement')
64
+ node = node.parent.parent;
65
+ if (
66
+ node.type !== 'ArrowFunctionExpression' &&
67
+ node.type !== 'FunctionExpression'
68
+ )
69
+ return null;
70
+ const call = node.parent;
71
+ return call.type === 'CallExpression' &&
72
+ call.arguments[1] === node &&
73
+ importedName(source, call.callee) === 'mount'
74
+ ? node
75
+ : null;
76
+ }
77
+
78
+ function isScalar(checker, type, allowNumber) {
79
+ if (type.isUnion())
80
+ return type.types.every((member) => isScalar(checker, member, allowNumber));
81
+ const base = checker.getBaseTypeOfLiteralType(type);
82
+ return (
83
+ base === checker.getStringType() ||
84
+ (allowNumber && base === checker.getNumberType())
85
+ );
86
+ }
87
+
88
+ export default {
89
+ meta: {
90
+ type: 'suggestion',
91
+ docs: {
92
+ description:
93
+ 'Suggest binding a stable Kerf signal in a mounted scalar JSX leaf.',
94
+ },
95
+ schema: [],
96
+ hasSuggestions: true,
97
+ messages: {
98
+ leaf: 'This value read subscribes the mount render. Binding the signal updates just this hole; check whether other render work relies on those rerenders.',
99
+ bind: 'Pass the signal itself to the native JSX hole.',
100
+ },
101
+ },
102
+ create(context) {
103
+ const source = context.sourceCode;
104
+ const services = source.parserServices;
105
+ const program = services?.program;
106
+ if (!program || !services.esTreeNodeToTSNodeMap) return {};
107
+ const opts = program.getCompilerOptions();
108
+ // TypeScript JsxEmit.ReactJSX (4) and ReactJSXDev (5). Consume the parser's
109
+ // Program without loading TypeScript as a dependency in untyped consumers.
110
+ if (
111
+ (opts.jsx !== 4 && opts.jsx !== 5) ||
112
+ opts.jsxImportSource !== 'kerfjs' ||
113
+ !(opts.strictNullChecks ?? opts.strict)
114
+ )
115
+ return {};
116
+ if (
117
+ source
118
+ .getAllComments()
119
+ .some((comment) =>
120
+ /@jsx(?:ImportSource|Runtime|Frag)?\b/.test(comment.value),
121
+ )
122
+ )
123
+ return {};
124
+
125
+ return {
126
+ JSXExpressionContainer(container) {
127
+ const member = container.expression;
128
+ if (
129
+ member.type !== 'MemberExpression' ||
130
+ member.optional ||
131
+ member.computed ||
132
+ member.object.type !== 'Identifier' ||
133
+ member.property.name !== 'value' ||
134
+ source.getCommentsInside(member).length
135
+ )
136
+ return;
137
+ const parent = container.parent;
138
+ const text = parent.type === 'JSXElement';
139
+ if (
140
+ !text &&
141
+ !(parent.type === 'JSXAttribute' && parent.name.name === 'title')
142
+ )
143
+ return;
144
+ const owner = mountCallback(
145
+ text ? parent : parent.parent.parent,
146
+ source,
147
+ );
148
+ if (!owner) return;
149
+
150
+ const def = definition(source, member.object);
151
+ if (
152
+ def?.type !== 'Variable' ||
153
+ def.parent.kind !== 'const' ||
154
+ def.node.id.type !== 'Identifier' ||
155
+ (def.node.range[0] >= owner.range[0] &&
156
+ def.node.range[1] <= owner.range[1])
157
+ )
158
+ return;
159
+ const init = def.node.init;
160
+ if (
161
+ init?.type !== 'CallExpression' ||
162
+ !['signal', 'computed'].includes(importedName(source, init.callee))
163
+ )
164
+ return;
165
+ const checker = program.getTypeChecker();
166
+ const tsNode = (node) => services.esTreeNodeToTSNodeMap.get(node);
167
+ const signature = checker.getResolvedSignature(tsNode(init));
168
+ const annotation = def.node.id.typeAnnotation;
169
+ const receiver = annotation
170
+ ? checker.getTypeFromTypeNode(tsNode(annotation.typeAnnotation))
171
+ : checker.getTypeAtLocation(tsNode(member.object));
172
+ const value = checker.getPropertyOfType(receiver, 'value');
173
+ if (
174
+ !signature ||
175
+ !value ||
176
+ !isScalar(
177
+ checker,
178
+ checker.getTypeOfSymbolAtLocation(value, tsNode(init)),
179
+ text,
180
+ )
181
+ )
182
+ return;
183
+ // An annotation such as { value: string } loses the signal type even
184
+ // though the initializer was a real signal. Its proposed JSX must typecheck.
185
+ if (
186
+ !checker.isTypeAssignableTo(
187
+ receiver,
188
+ checker.getReturnTypeOfSignature(signature),
189
+ )
190
+ )
191
+ return;
192
+ context.report({
193
+ node: member,
194
+ messageId: 'leaf',
195
+ suggest: [
196
+ {
197
+ messageId: 'bind',
198
+ fix: (fixer) =>
199
+ fixer.replaceText(member, source.getText(member.object)),
200
+ },
201
+ ],
202
+ });
203
+ },
204
+ };
205
+ },
206
+ };
@@ -58,54 +58,21 @@ function entryModules(entryFile, currentFile, currentText) {
58
58
  return modules;
59
59
  }
60
60
 
61
- // Only the listbox mode needs wireChoiceChips. Static radio and toggle groups
62
- // use native inputs; an expression whose value is unknown still needs wiring.
63
- function choiceChipsNeedsWiring(attributes) {
64
- const multiple = attributes.find(
65
- (attribute) => attribute.name?.name === 'multiple',
66
- );
67
- if (!multiple) return false;
68
- if (!multiple.value) return true;
69
- if (multiple.value.type === 'Literal')
70
- return multiple.value.value !== 'toggle';
71
- const expression = multiple.value.expression;
72
- if (expression?.type === 'Literal')
73
- return expression.value !== 'toggle' && expression.value !== false;
74
- return true;
75
- }
76
-
77
- function sourceChoiceChipsNeedsWiring(source, name) {
78
- const opening = new RegExp(`<${name}(?=[\\s/>])`, 'g');
79
- for (const match of source.matchAll(opening)) {
80
- let braces = 0;
81
- let quote;
82
- let end = match.index + match[0].length;
83
- for (; end < source.length; end++) {
84
- const char = source[end];
85
- if (quote) {
86
- if (char === '\\') end++;
87
- else if (char === quote) quote = undefined;
88
- } else if (char === '"' || char === "'" || char === '`') quote = char;
89
- else if (char === '{') braces++;
90
- else if (char === '}') braces--;
91
- else if (char === '>' && braces === 0) break;
92
- }
93
- if (end === source.length) continue;
94
- const attributes = source.slice(match.index + match[0].length, end);
95
- const multiple = attributes.match(
96
- /(?:^|\s)multiple(?:\s*=\s*(?:\{\s*([^}]*)\s*\}|(["'])(.*?)\2))?(?=\s|\/|$)/,
97
- );
98
- if (!multiple) continue;
99
- if (
100
- multiple[3] === 'toggle' ||
101
- multiple[1]?.trim() === "'toggle'" ||
102
- multiple[1]?.trim() === '"toggle"' ||
103
- multiple[1]?.trim() === 'false'
104
- )
105
- continue;
106
- return true;
107
- }
108
- return false;
61
+ function literalAttributes(attributes) {
62
+ return attributes.map((attribute) => {
63
+ if (attribute.type === 'JSXSpreadAttribute') return ['...', null];
64
+ const value = attribute.value;
65
+ const expression =
66
+ value?.type === 'JSXExpressionContainer' ? value.expression : value;
67
+ return [
68
+ attribute.name.name,
69
+ value == null
70
+ ? true
71
+ : expression?.type === 'Literal'
72
+ ? expression.value
73
+ : null,
74
+ ];
75
+ });
109
76
  }
110
77
 
111
78
  // The entry graph is read from disk because ESLint visits one source file at a
@@ -138,7 +105,7 @@ function moduleUses(source, file, contract) {
138
105
  key &&
139
106
  new RegExp(`<${local}(?=[\\s/>])`).test(source) &&
140
107
  (key !== '@kerfjs/ui:choice-chips' ||
141
- sourceChoiceChipsNeedsWiring(source, local))
108
+ contract.choiceWiring.choiceUses(source, local))
142
109
  )
143
110
  uses.add(key);
144
111
  }
@@ -154,7 +121,7 @@ function moduleUses(source, file, contract) {
154
121
  key &&
155
122
  new RegExp(`<${namespace}\\.${name}(?=[\\s/>])`).test(source) &&
156
123
  (key !== '@kerfjs/ui:choice-chips' ||
157
- sourceChoiceChipsNeedsWiring(source, `${namespace}\\.${name}`))
124
+ contract.choiceWiring.choiceUses(source, `${namespace}.${name}`))
158
125
  )
159
126
  uses.add(key);
160
127
  }
@@ -314,7 +281,8 @@ export default {
314
281
  key &&
315
282
  !used.has(key) &&
316
283
  (key !== '@kerfjs/ui:choice-chips' ||
317
- choiceChipsNeedsWiring(node.attributes))
284
+ contract.choiceWiring.choiceMode(literalAttributes(node.attributes))
285
+ .required !== false)
318
286
  )
319
287
  used.set(key, node.name);
320
288
  },
@@ -385,6 +385,9 @@ export function loadUiContract(context) {
385
385
  publicTokens: new Set(
386
386
  catalog.entries.flatMap((entry) => entry.boundaries.publicTokens),
387
387
  ),
388
+ choiceWiring: loadCommonJs(
389
+ resolve(dirname(profileContractPath), 'choice-wiring-mode.cjs'),
390
+ ),
388
391
  error: undefined,
389
392
  };
390
393
  cache.set(key, { stamps, value });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-kerfjs",
3
- "version": "5.0.0-beta.132",
3
+ "version": "5.0.0-beta.135",
4
4
  "description": "ESLint rules that enforce kerf's hard rules — catches AI-shaped bugs at edit time.",
5
5
  "type": "module",
6
6
  "license": "MIT",