@md-code/component-uniqueness 0.1.0 → 0.1.2

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
@@ -1,41 +1,17 @@
1
1
  # @md-code/component-uniqueness
2
2
 
3
- ESLint rule + CLI scanner that finds **duplicate components** in your app code by comparing them against your canonical component library. Cross-framework: React today, the same signature model is designed to carry over to Vue and Angular.
4
-
5
- ## How it works
3
+ ESLint rule and CLI that find components, raw HTML and copied JSX blocks that duplicate a component you already have in your design system.
6
4
 
7
5
  ```mermaid
8
- flowchart TD
9
- A["Canonical components<br/>(walk folders, extract signatures)"] --> B[("catalog.json")]
10
- A --> CD["canon-dup<br/>canonicals matched against each other (strict thresholds)<br/>duplicates dropped → unique canonical set"]
11
- CD --> A
12
- C["App code<br/>(every JSX element)"] --> D
13
-
14
- subgraph match["Match (4 matchers in parallel)"]
15
- D --> M1["name<br/>same or fuzzy name"]
16
- D --> M2["structural<br/>shared class tokens"]
17
- D --> M3["family<br/>token-profile cluster"]
18
- D --> M4["jsx-block<br/>subtree contains canonical"]
19
- B --> M1
20
- B --> M2
21
- B --> M3
22
- B --> M4
23
- end
24
-
25
- M1 --> F1
26
- M2 --> F1
27
- M3 --> F1
28
- M4 --> F1
29
-
30
- subgraph filter["Filter"]
31
- F1["drop-usages<br/>app already imports the canonical"]
32
- F1 --> F2["drop-child-element<br/>match is on a child, not the root"]
33
- end
34
-
35
- F2 --> E["report.md<br/>Markdown funnel of duplicates"]
36
- CD -. "own section" .-> E
6
+ flowchart LR
7
+ A["Canonical<br/>components"] --> M
8
+ B["App code<br/>components · elements · parts"] --> M
9
+ M["Match<br/>name · structure · behavior · a11y · framework"] --> F["Filter<br/>usages · child elements"]
10
+ F --> R["Report"]
37
11
  ```
38
12
 
13
+ Structure is compared as rendered HTML with the CSS your classes resolve to, so two differently written components with the same markup and styles match.
14
+
39
15
  ## Quick start
40
16
 
41
17
  ```sh
@@ -44,106 +20,74 @@ bun add -D @md-code/component-uniqueness
44
20
 
45
21
  ```js
46
22
  // eslint.config.js
47
- const uniqueness = require("@md-code/component-uniqueness/plugin");
23
+ const plugin = require("@md-code/component-uniqueness");
48
24
 
49
25
  module.exports = [
50
26
  {
51
- files: ["**/*.tsx"],
52
- plugins: { "md-code": uniqueness },
27
+ files: ["src/**/*.{ts,tsx}"],
28
+ plugins: { "md-code": plugin },
53
29
  rules: {
54
- "md-code/component-uniqueness": ["error", {
55
- componentsFolder: [
56
- { path: "core/ui/atoms", rank: 0 },
57
- { path: "core/ui/formation", rank: 1 },
58
- { path: "core/ui/partials", rank: 2 },
59
- ],
60
- catalogPath: "reports/component-catalog.json",
30
+ "md-code/duplicate-component": ["error", {
31
+ componentsFolder: ["src/ui/atoms", "src/ui/formation", "src/ui/partials"],
32
+ tsconfig: "src/ui/tsconfig.json",
33
+ rawHtml: true,
34
+ parts: true,
61
35
  }],
62
36
  },
63
37
  },
64
38
  ];
65
39
  ```
66
40
 
67
- The catalog is generated automatically on the first lint when the file is
68
- missing (from the `componentsFolder` option) — it is gitignored and never
69
- committed. You can also generate it explicitly:
41
+ Generate the catalog once before linting, and again when the canonical components change. It is read from `reports/component-catalog.json` and should be gitignored.
70
42
 
71
43
  ```sh
72
- bunx md-code-component-uniqueness
44
+ bunx component-uniqueness
73
45
  ```
74
46
 
75
- Run the linter as usual:
47
+ ## Layers
76
48
 
77
- ```sh
78
- bunx eslint "src/**/*.tsx"
79
- ```
49
+ `componentsFolder` is ordered: each folder is built from the ones before it. A file inside a folder is compared only with the folders to its left, so `formation` is checked against `atoms`, and `partials` against both. The first folder is the base and is not compared with anything. Files outside all of them are compared with every folder.
80
50
 
81
- ## CLI
51
+ ## What it reports
82
52
 
83
- ```sh
84
- bunx md-code-component-uniqueness [flags]
85
- ```
86
-
87
- | Flag | Description |
53
+ | messageId | Fires when |
88
54
  | --- | --- |
89
- | `--roots a:b` | Scan roots (overrides `componentsFolder` from config) |
90
- | `--out <file>` | Catalog output path (default `reports/component-catalog.json`) |
91
- | `--check` | CI gate — exit 1 if catalog is stale |
92
- | `--report [file]` | Write a Markdown duplicate report |
93
- | `--verbose` | Include the "Filtered out" section in the report |
94
- | `--app-roots a:b` | App-code roots for the report (default: repo root) |
95
- | `--repo-root <dir>` | Repo root (default: auto-discovered) |
55
+ | `duplicateComponent` | A component duplicates a canonical one |
56
+ | `rawHtml` | A raw element (`button`, `input`, `a`, …) should be a canonical component. Needs `rawHtml: true`. Not applied inside `componentsFolder` |
57
+ | `partOfComponent` | A block inside a component duplicates a canonical one. Needs `parts: true` |
96
58
 
97
- ## What it flags
59
+ A component that already renders the canonical one is a usage, not a duplicate, and is skipped.
98
60
 
99
- | Tier | Meaning |
100
- | --- | --- |
101
- | `name` | App component has the same name as a canonical one |
102
- | `name-fuzzy` | Name is a fuzzy match (e.g. `MyButton` vs `Button`) |
103
- | `structural-exact` | ≥ 80% of the canonical's distinctive class tokens are shared |
104
- | `structural-similar` | 40–80% shared |
105
- | `family` | Clusters by token profile (hand-built library pieces) |
106
- | `jsx-block` | A JSX subtree in app code contains the full tag-sequence of a canonical component |
61
+ ## Options
107
62
 
108
- ## What the ESLint rule reports
63
+ | Option | Default | Notes |
64
+ | --- | --- | --- |
65
+ | `componentsFolder` | `[]` | Canonical folders, lowest layer first |
66
+ | `tsconfig` | — | Used to resolve imports when a file has no `tsconfig` of its own |
67
+ | `rawHtml` | `false` | Also check raw elements |
68
+ | `parts` | `false` | Also check blocks inside components |
69
+ | `catalogPath` | `reports/component-catalog.json` | Where the catalog is read and written |
70
+ | `include` | `[]` | Lint only matching files. Files inside `componentsFolder` are always linted |
71
+ | `exclude` | stories, tests, `*.d.ts` | Globs to skip |
72
+ | `ignoreDirs` | `node_modules`, `dist`, `build` | Added to the defaults |
73
+ | `exts` | `.tsx` `.ts` `.jsx` `.js` | File extensions |
74
+ | `weights` | name 0.10, structure 0.5, behavior 0.2, a11y 0.1, framework 0.15 | Signal weights |
75
+ | `thresholds` | duplicate 0.6, similar 0.4 | Confidence cut-offs |
109
76
 
110
- | messageId | Fires when |
111
- | --- | --- |
112
- | `duplicateComponent` | A canonical component name is declared outside its registry directory |
113
- | `rawHtml` | A raw interactive element (`button`, `input`, `select`, …) is used outside the canonical packages — the element's behavior (its `type`, `role`, `aria-*`) maps to a canonical component |
114
- | `layoutPrimitive` | A hand-rolled element **behaves like** a canonical component: its behavioral signals (event handlers + behavioral `role`/`type`/`aria-*` tokens) are a subset of a canonical's. Derived entirely from the catalog — no hardcoded role/behavior lists |
115
- | `styledInApp` | A `styled.*` component is created outside the canonical packages |
116
- | `catalogDuplicate` | An element structurally duplicates a canonical one (shared a11y token, or ≥ 3 shared layout style keys with high similarity) — error level |
117
- | `similarComponent` | Same as above but below the error threshold — warning level |
77
+ ## CLI
118
78
 
119
- The behavioral check (`layoutPrimitive`) runs only outside the canonical
120
- folders — inside them, the canonical's own body is the source of truth. It
121
- keys off the **lowest-rank** canonical whose signal set contains the
122
- candidate's, so the most basic canonical wins.
79
+ ```sh
80
+ bunx component-uniqueness [flags]
81
+ ```
123
82
 
124
- ## Options (rule config)
83
+ Options are read from the rule in `eslint.config.js`.
125
84
 
126
- | Option | Default | Notes |
127
- | --- | --- | --- |
128
- | `componentsFolder` | `[]` | Canonical dirs. `{ path, rank }` objects or plain strings. Rank drives the behavioral check (lowest = most basic) |
129
- | `catalog` / `catalogPath` | — / `reports/component-catalog.json` | Inline catalog object, or path to load one |
130
- | `registry` / `registryPath` | — / `reports/component-registry.json` | Canonical name → allowed dirs, for `duplicateComponent` |
131
- | `includeDynamic` | `false` | Also load a dynamic (DOM-snapshot) catalog |
132
- | `dynamicCatalog` / `dynamicCatalogPath` | — | Inline / path for the dynamic catalog |
133
- | `tsconfig` | — | Fallback `tsconfig.json` (or any `.ts` file next to one) used to resolve imports when the file has no `tsconfig` of its own. Resolution is done by TypeScript; unresolved imports keep their component name |
134
- | `rawHtml` | `false` | Match every HTML element that carries behavior (an event handler, `role`/`aria-*`, or an interactive tag) against the canonical catalog with the same matchers and decision-maker as components. The best canonical at or above the duplicate threshold is suggested |
135
- | `exclude` | `*.stories.*`, `*.test.*`, `*.spec.*`, `*.d.ts`, `**/__tests__/**` | Globs, `^...$` regexes or `/.../ ` regexes to skip |
136
- | `include` | `[]` | If set, only matching files are linted |
137
- | `exts` | `.tsx`, `.ts`, `.jsx`, `.js` | File extensions to scan |
138
- | `ignoreDirs` | `node_modules`, `dist`, `build` | Directory names to skip while walking |
139
- | `rootMarkers` | `.git` | File names that mark the repo root (auto-discovery) |
140
- | `debt` | `{}` | Known-duplicate ledger (shrink-only) |
141
-
142
- ## Notes
143
-
144
- - The catalog is **generated on demand** by the rule when the file is missing
145
- (same code path as the CLI), so it can stay gitignored and CI works out of
146
- the box. The CLI is still useful for `--report` and `--check`.
147
- - The catalog is read once per ESLint process and cached.
148
- - A missing or stale catalog logs a warning; lint never crashes.
149
- - Everything is plain Node + `fs`/`path` — works identically on Linux, macOS, Windows.
85
+ | Flag | Description |
86
+ | --- | --- |
87
+ | `--report [file]` | Write a Markdown report of every finding |
88
+ | `--check` | Exit 1 if the catalog is stale |
89
+ | `--roots a:b` | Canonical folders, instead of `componentsFolder` |
90
+ | `--app-roots a:b` | Folders to scan for the report (default: repo root) |
91
+ | `--repo-root <dir>` | Repo root (default: auto-detected) |
92
+ | `--out <file>` | Catalog path |
93
+ | `--verbose` | Also list what the filters dropped |
package/config.js CHANGED
@@ -185,7 +185,7 @@ const isIgnored = (relPath, include, exclude) => {
185
185
  return false;
186
186
  };
187
187
 
188
- const RULE_NAME = "md-code/duplicate-component";
188
+ const RULE_NAME = "md-code/component-uniqueness";
189
189
  const RULE_SHORT = "md-code";
190
190
 
191
191
  const FLAT_CANDIDATES = ["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", "eslint.config.ts"];
@@ -214,13 +214,24 @@ const pickOptions = (v) => {
214
214
  return {};
215
215
  };
216
216
 
217
+ const isRuleKey = (key) => key === RULE_NAME || key === RULE_SHORT || key === "component-uniqueness" || key.endsWith("/component-uniqueness");
218
+
219
+ const ruleValue = (rules) => {
220
+ for (const [key, v] of Object.entries(rules)) {
221
+ if (!isRuleKey(key)) continue;
222
+ if (v === undefined || v === null) continue;
223
+ return v;
224
+ }
225
+ return null;
226
+ };
227
+
217
228
  const loadFlatOptions = async (file) => {
218
229
  const mod = await loadModule(file);
219
230
  const list = mod && mod.default !== undefined ? mod.default : mod;
220
231
  if (!Array.isArray(list)) return null;
221
232
  for (const entry of list) {
222
233
  if (!entry || typeof entry !== "object" || !entry.rules) continue;
223
- const v = entry.rules[RULE_NAME] ?? entry.rules[RULE_SHORT];
234
+ const v = ruleValue(entry.rules);
224
235
  if (v === undefined || v === null) continue;
225
236
  return pickOptions(v);
226
237
  }
@@ -229,8 +240,8 @@ const loadFlatOptions = async (file) => {
229
240
 
230
241
  const loadLegacyOptions = async (file) => {
231
242
  const mod = await loadModule(file);
232
- const rules = (mod && mod.rules) || {};
233
- return pickOptions(rules[RULE_NAME] ?? rules[RULE_SHORT]);
243
+ const v = ruleValue((mod && mod.rules) || {});
244
+ return v === undefined || v === null ? null : pickOptions(v);
234
245
  };
235
246
 
236
247
  const loadRuleOptions = async (dir) => {
package/decision-maker.js CHANGED
@@ -12,8 +12,8 @@ const DEFAULT_WEIGHTS = {
12
12
  };
13
13
 
14
14
  const DEFAULT_THRESHOLDS = {
15
- duplicate: 0.6,
16
- similar: 0.4,
15
+ duplicate: 0.4,
16
+ similar: 0.2,
17
17
  };
18
18
 
19
19
  const clamp01 = (x) => Math.max(0, Math.min(1, x));
@@ -77,12 +77,8 @@ const decide = (candidate, canon, ctx) => {
77
77
  tier = "similar";
78
78
  }
79
79
 
80
- const contributions = Object.fromEntries(Object.entries(signals).map(([k, s]) => [k, weights[k] * s.score]));
81
- const parts = [];
82
- for (const key of ["name", "structure", "behavior", "a11y", "framework"]) {
83
- if (signals[key].score > 0) parts.push(`${key} ${signals[key].score.toFixed(2)}`);
84
- }
85
- const reason = parts.length > 0 ? `confidence ${confidence.toFixed(2)} (${parts.join(", ")})` : `confidence ${confidence.toFixed(2)}`;
80
+ const parts = ["name", "structure", "behavior", "a11y", "framework"].map((key) => `${key} ${signals[key].score.toFixed(2)}`);
81
+ const reason = `confidence ${confidence.toFixed(2)} (${parts.join(", ")})`;
86
82
 
87
83
  return {
88
84
  isDuplicate,
@@ -2,7 +2,10 @@
2
2
 
3
3
  const test = (match) => {
4
4
  if ((match.app.usesCanonical || []).includes(match.canon.name)) {
5
- return `renders canonical ${match.canon.name} (usage, not a duplicate)`;
5
+ return `${match.app.name} renders ${match.canon.name} (composition, not a duplicate)`;
6
+ }
7
+ if ((match.canon.usesCanonical || []).includes(match.app.name)) {
8
+ return `${match.canon.name} renders ${match.app.name} (composition, not a duplicate)`;
6
9
  }
7
10
  return null;
8
11
  };
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+
3
+ const { pascalWords, GENERIC_WORDS } = require("../normalize/words.js");
4
+
5
+ const DEFAULT_MIN_CLUSTER = 3;
6
+
7
+ const pascalCase = (words) => words.map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()).join("");
8
+
9
+ const suggestName = (appNames, canonName = null) => {
10
+ const counts = new Map();
11
+ const order = [];
12
+ for (const name of appNames) {
13
+ for (const w of pascalWords(name)) {
14
+ const k = w.toLowerCase();
15
+ if (!counts.has(k)) {
16
+ counts.set(k, 0);
17
+ order.push(k);
18
+ }
19
+ counts.set(k, counts.get(k) + 1);
20
+ }
21
+ }
22
+ const common = order.filter((k) => counts.get(k) >= 2);
23
+ const meaningful = common.filter((k) => !GENERIC_WORDS.has(k));
24
+ const base = (meaningful.length > 0 ? meaningful : common).map((k) => k[0].toUpperCase() + k.slice(1));
25
+ if (base.length > 0) {
26
+ const name = pascalCase(base);
27
+ if (meaningful.length > 0) return name;
28
+ return canonName ? `${name}${canonName}` : name;
29
+ }
30
+ const first = appNames[0];
31
+ return first ? pascalWords(first).map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()).join("") : "Component";
32
+ };
33
+
34
+ const findMissingComponents = (matches, { minCluster = DEFAULT_MIN_CLUSTER } = {}) => {
35
+ const byCanon = new Map();
36
+ for (const match of matches) {
37
+ const key = match.canon.name;
38
+ if (!byCanon.has(key)) byCanon.set(key, []);
39
+ byCanon.get(key).push(match);
40
+ }
41
+ const clusters = [];
42
+ const clusteredKeys = new Set();
43
+ for (const [canonName, group] of byCanon) {
44
+ const distinctApps = new Set(group.map((m) => m.app.name));
45
+ if (distinctApps.size < minCluster) continue;
46
+ clusteredKeys.add(canonName);
47
+ clusters.push({
48
+ name: suggestName(group.map((m) => m.app.name), canonName),
49
+ canon: group[0].canon,
50
+ matches: [...group].sort((a, b) => b.decision.confidence - a.decision.confidence),
51
+ });
52
+ }
53
+ clusters.sort((a, b) => b.matches.length - a.matches.length || a.name.localeCompare(b.name));
54
+ const remaining = matches.filter((m) => !clusteredKeys.has(m.canon.name));
55
+ return { clusters, remaining };
56
+ };
57
+
58
+ module.exports = {
59
+ findMissingComponents,
60
+ suggestName,
61
+ DEFAULT_MIN_CLUSTER,
62
+ };
package/index.js CHANGED
@@ -35,6 +35,14 @@ const isComponentBinding = (node) => {
35
35
  return true;
36
36
  };
37
37
 
38
+ const normalizedCanons = new WeakMap();
39
+
40
+ const normalizeCanon = (canon, config) => {
41
+ if (!normalizedCanons.has(canon)) normalizedCanons.set(canon, buildCandidate(canon, config));
42
+
43
+ return normalizedCanons.get(canon);
44
+ };
45
+
38
46
  const createRule = () => {
39
47
  return {
40
48
  meta: {
@@ -96,7 +104,6 @@ const createRule = () => {
96
104
  }
97
105
  const normalizeComp = (comp) => buildCandidate(comp, config);
98
106
 
99
- const normCanons = new Map();
100
107
  for (const comp of parsed) {
101
108
  if (!comp.isExported) continue;
102
109
  const candidate = normalizeComp({ ...comp, path: relPath });
@@ -104,11 +111,7 @@ const createRule = () => {
104
111
  for (const canon of catalogComponents) {
105
112
  if (canon.name === candidate.name) continue;
106
113
  if (!canSeeCanon(relPath, canon.path, config.componentsFolder)) continue;
107
- let normCanon = normCanons.get(canon.name);
108
- if (!normCanon) {
109
- normCanon = normalizeComp(canon);
110
- normCanons.set(canon.name, normCanon);
111
- }
114
+ const normCanon = normalizeCanon(canon, config);
112
115
  const signals = matchSignals(candidate, normCanon, { canonNames, frameworkMatcher });
113
116
  const decision = decide(candidate, normCanon, { signals, weights: config.weights, thresholds: config.thresholds });
114
117
  pairs.push({ canon: normCanon, signals, decision });
@@ -127,11 +130,7 @@ const createRule = () => {
127
130
  }
128
131
  }
129
132
  if (config.rawHtml && !isInComponentsFolder) {
130
- const canons = catalogComponents.map((canon) => {
131
- if (!normCanons.has(canon.name)) normCanons.set(canon.name, normalizeComp(canon));
132
-
133
- return normCanons.get(canon.name);
134
- });
133
+ const canons = catalogComponents.map((canon) => normalizeCanon(canon, config));
135
134
  let elements = [];
136
135
  try {
137
136
  elements = parseElements(filename, canonNames, config);
@@ -151,11 +150,7 @@ const createRule = () => {
151
150
  }
152
151
  }
153
152
  if (config.parts) {
154
- const canons = catalogComponents.map((canon) => {
155
- if (!normCanons.has(canon.name)) normCanons.set(canon.name, normalizeComp(canon));
156
-
157
- return normCanons.get(canon.name);
158
- });
153
+ const canons = catalogComponents.map((canon) => normalizeCanon(canon, config));
159
154
  for (const { part, best } of findParts(filename, relPath, canons, config, new Set(canonNames))) {
160
155
  context.report({
161
156
  loc: { start: { line: part.line, column: part.column }, end: { line: part.endLine, column: 0 } },
@@ -173,6 +168,17 @@ const createRule = () => {
173
168
  };
174
169
  };
175
170
 
176
- module.exports = createRule();
171
+ const rule = createRule();
172
+ const pkg = require("./package.json");
173
+
174
+ module.exports = {
175
+ meta: {
176
+ name: pkg.name,
177
+ version: pkg.version,
178
+ },
179
+ rules: {
180
+ "component-uniqueness": rule,
181
+ },
182
+ };
177
183
  module.exports.RULE_NAME = RULE_NAME;
178
184
  module.exports.RULE_SHORT = RULE_SHORT;
package/logger.js ADDED
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+
6
+ const state = {
7
+ enabled: false,
8
+ stream: null,
9
+ file: null,
10
+ };
11
+
12
+ const enabled = () => state.enabled;
13
+
14
+ const enable = (file) => {
15
+ if (!file) return;
16
+ const abs = path.resolve(process.cwd(), file);
17
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
18
+ if (state.stream) state.stream.end();
19
+ state.stream = fs.createWriteStream(abs, { flags: "w" });
20
+ state.file = abs;
21
+ state.enabled = true;
22
+ };
23
+
24
+ const disable = () => {
25
+ if (state.stream) state.stream.end();
26
+ state.stream = null;
27
+ state.file = null;
28
+ state.enabled = false;
29
+ };
30
+
31
+ const write = (entry) => {
32
+ if (!state.enabled || !state.stream) return;
33
+ state.stream.write(`${JSON.stringify(entry)}\n`);
34
+ };
35
+
36
+ const stage = (name, data) => {
37
+ write({ ts: Date.now(), stage: name, ...data });
38
+ };
39
+
40
+ const flush = () => {
41
+ if (state.stream) state.stream.end();
42
+ };
43
+
44
+ module.exports = { enable, disable, enabled, stage, write, flush };
package/main.js CHANGED
@@ -24,18 +24,40 @@ const { getFrameworkMatcher } = require("./matcher/framework");
24
24
  const { decide, bestOf } = require("./decision-maker");
25
25
  const dropUsages = require("./filter/drop-usages");
26
26
  const dropChildElement = require("./filter/drop-child-element");
27
+ const { findMissingComponents } = require("./filter/missing-component");
27
28
  const { renderComponentReport } = require("./report");
29
+ const log = require("./logger");
28
30
 
29
31
  const FILTERS = [dropUsages, dropChildElement];
30
32
  const frameworkMatcher = getFrameworkMatcher("react");
31
33
 
34
+ const treeSummary = (tree) => {
35
+ if (!tree) return null;
36
+ const walk = (n) => {
37
+ const kids = (n.children || []).map(walk);
38
+ return { tag: n.tag, css: n.css ? Object.keys(n.css).length : 0, children: kids };
39
+ };
40
+ return walk(tree);
41
+ };
42
+
43
+ const candidateSummary = (c, role) => ({
44
+ role,
45
+ name: c.name,
46
+ path: c.path,
47
+ rootTags: c.rootTags,
48
+ tree: treeSummary(c.tree),
49
+ domTree: treeSummary(c.dom && c.dom.tree),
50
+ framework: c.framework ? { props: c.framework.props, events: c.framework.events, names: c.framework.names, open: c.framework.open } : null,
51
+ a11y: c.a11y,
52
+ });
53
+
32
54
  const fail = (message) => {
33
55
  console.error(`[component-uniqueness] ${message}`);
34
56
  process.exit(1);
35
57
  };
36
58
 
37
59
  const parseArgs = (argv) => {
38
- const cfg = { roots: null, out: null, registry: null, repoRoot: null, check: false, report: null, appRoots: null, ignoreDirs: null, verbose: false };
60
+ const cfg = { roots: null, out: null, registry: null, repoRoot: null, check: false, report: null, appRoots: null, ignoreDirs: null, verbose: false, include: null, log: null, minCluster: 3 };
39
61
  for (let i = 0; i < argv.length; i += 1) {
40
62
  const a = argv[i];
41
63
  if (a === "--check") {
@@ -67,9 +89,21 @@ const parseArgs = (argv) => {
67
89
  cfg.ignoreDirs = argv[++i].split(":").filter(Boolean);
68
90
  } else if (a === "--verbose") {
69
91
  cfg.verbose = true;
92
+ } else if (a === "--include") {
93
+ if (!argv[i + 1]) fail("--include requires a value (colon-separated list of file globs, e.g. a.tsx:b.tsx)");
94
+ cfg.include = argv[++i].split(":").filter(Boolean);
95
+ } else if (a === "--log") {
96
+ if (!argv[i + 1]) fail("--log requires a value (path to the stage log file)");
97
+ cfg.log = argv[++i];
98
+ } else if (a === "--min-cluster") {
99
+ if (!argv[i + 1]) fail("--min-cluster requires a value (min app components matching one canonical to flag it as a missing component)");
100
+ const n = Number.parseInt(argv[i + 1], 10);
101
+ if (!Number.isFinite(n) || n < 2) fail("--min-cluster must be an integer >= 2");
102
+ cfg.minCluster = n;
103
+ i += 1;
70
104
  } else if (a === "--help" || a === "-h") {
71
- console.log("Usage: component-uniqueness [--roots a:b] [--out file] [--registry file] [--repo-root dir] [--check] [--report [file.md]] [--app-roots a:b] [--ignore-dirs a:b] [--verbose]");
72
- console.log("Without --roots, the options are read from the consumer's eslint.config.js (rule md-code/duplicate-component) or component-uniqueness.config.js.");
105
+ console.log("Usage: component-uniqueness [--roots a:b] [--out file] [--registry file] [--repo-root dir] [--check] [--report [file.md]] [--app-roots a:b] [--ignore-dirs a:b] [--include a.tsx:b.tsx] [--log file] [--min-cluster N] [--verbose]");
106
+ console.log("Without --roots, the options are read from the consumer's eslint.config.js (rule md-code/component-uniqueness) or component-uniqueness.config.js.");
73
107
  process.exit(0);
74
108
  } else {
75
109
  fail(`unknown argument: ${a} (see --help)`);
@@ -116,8 +150,15 @@ const parseComponents = (files, canonNames, config, role = "CANONICAL") => {
116
150
  continue;
117
151
  }
118
152
  for (const c of parsed) {
153
+ if (log.enabled()) {
154
+ log.stage("normalizer:before", { role, file: rel, name: c.name, tree: treeSummary(c.tree), rootTags: c.rootTags, a11y: c.a11y });
155
+ }
119
156
  const candidate = buildCandidate(c, config);
120
- comps.push({ ...candidate, path: rel });
157
+ const withPath = { ...candidate, path: rel };
158
+ if (log.enabled()) {
159
+ log.stage("normalizer:after", { role, file: rel, name: c.name, tree: treeSummary(c.tree), domTree: treeSummary(candidate.dom && candidate.dom.tree), framework: { props: candidate.framework.props, events: candidate.framework.events, names: candidate.framework.names, open: candidate.framework.open } });
160
+ }
161
+ comps.push(withPath);
121
162
  }
122
163
  }
123
164
  return comps;
@@ -130,9 +171,21 @@ const matchPairs = (appComponents, canonComponents, config) => {
130
171
  for (const canon of canonComponents) {
131
172
  if (canon.path === app.path && canon.name === app.name) continue;
132
173
  if (!canSeeCanon(app.path, canon.path, config.componentsFolder)) continue;
174
+ if (log.enabled()) {
175
+ log.stage("matcher:before", { app: candidateSummary(app, "candidate"), canon: candidateSummary(canon, "canonical") });
176
+ }
133
177
  const signals = matchSignals(app, canon, { canonNames, frameworkMatcher });
178
+ if (log.enabled()) {
179
+ log.stage("matcher:after", { app: { name: app.name, path: app.path }, canon: { name: canon.name, path: canon.path }, signals });
180
+ }
181
+ if (log.enabled()) {
182
+ log.stage("decision:before", { app: { name: app.name, path: app.path }, canon: { name: canon.name, path: canon.path }, signals });
183
+ }
134
184
  const decision = decide(app, canon, { signals, weights: config.weights, thresholds: config.thresholds });
135
- if (!decision.isDuplicate) continue;
185
+ if (log.enabled()) {
186
+ log.stage("decision:after", { app: { name: app.name, path: app.path }, canon: { name: canon.name, path: canon.path }, confidence: decision.confidence, tier: decision.tier, isDuplicate: decision.isDuplicate, weights: decision.weights, signals: Object.fromEntries(Object.entries(decision.signals).map(([k, s]) => [k, s.score])) });
187
+ }
188
+ if (!decision.tier) continue;
136
189
  matches.push({ app, canon, decision, tier: decision.tier, reason: decision.reason });
137
190
  }
138
191
  }
@@ -143,6 +196,9 @@ const applyFilters = (matches) => {
143
196
  const kept = [];
144
197
  const dropped = [];
145
198
  for (const match of matches) {
199
+ if (log.enabled()) {
200
+ log.stage("filter:before", { app: { name: match.app.name, path: match.app.path }, canon: { name: match.canon.name, path: match.canon.path }, confidence: match.decision.confidence });
201
+ }
146
202
  let hit = null;
147
203
  for (const f of FILTERS) {
148
204
  const reason = f.test(match);
@@ -151,12 +207,29 @@ const applyFilters = (matches) => {
151
207
  break;
152
208
  }
153
209
  }
154
- if (hit) dropped.push(hit);
155
- else kept.push(match);
210
+ if (hit) {
211
+ dropped.push(hit);
212
+ if (log.enabled()) log.stage("filter:after", { app: { name: match.app.name, path: match.app.path }, canon: { name: match.canon.name, path: match.canon.path }, outcome: "dropped", filter: hit.filter, reason: hit.reason });
213
+ } else {
214
+ kept.push(match);
215
+ if (log.enabled()) log.stage("filter:after", { app: { name: match.app.name, path: match.app.path }, canon: { name: match.canon.name, path: match.canon.path }, outcome: "kept", confidence: match.decision.confidence });
216
+ }
156
217
  }
157
218
  return { kept, dropped };
158
219
  };
159
220
 
221
+ const pairKey = (match) => [match.app.name, match.canon.name].sort().join("::");
222
+
223
+ const dedupPairs = (matches) => {
224
+ const best = new Map();
225
+ for (const match of matches) {
226
+ const key = pairKey(match);
227
+ const prev = best.get(key);
228
+ if (!prev || match.decision.confidence > prev.decision.confidence) best.set(key, match);
229
+ }
230
+ return [...best.values()];
231
+ };
232
+
160
233
  const collectRawHtml = (appFiles, canonComponents, config, canonNames) => {
161
234
  if (!config.rawHtml) return [];
162
235
  const rows = [];
@@ -331,15 +404,22 @@ const buildComponentReport = async (args, repoRoot, roots, shouldSkip, config, r
331
404
 
332
405
  const matches = matchPairs(appComponents, uniqueCanon, config);
333
406
  const { kept, dropped } = applyFilters(matches);
407
+ const deduped = dedupPairs(kept);
334
408
  stage("components matched");
409
+ const { clusters, remaining } = findMissingComponents(deduped, { minCluster: args.minCluster });
410
+ if (log.enabled()) {
411
+ log.stage("missing-component", { minCluster: args.minCluster, clusters: clusters.map((c) => ({ name: c.name, canon: c.canon.name, apps: c.matches.map((m) => m.app.name) })), remaining: remaining.length });
412
+ }
413
+ stage("missing-component clustered");
335
414
  const rawHtml = collectRawHtml(appFiles.files, uniqueCanon, config, canonNames);
336
415
  stage("raw html done");
337
416
  const parts = collectParts(appFiles.files, uniqueCanon, config, canonNames);
338
417
  stage("parts done");
339
418
 
340
419
  return {
341
- matches: kept,
420
+ matches: remaining,
342
421
  dropped,
422
+ missingClusters: clusters,
343
423
  rawHtml,
344
424
  parts,
345
425
  layerFolders: config.componentsFolder,
@@ -364,6 +444,8 @@ const main = async () => {
364
444
  }
365
445
 
366
446
  const config = normalizeOptions(configOptions);
447
+ if (args.include) config.include = [...new Set([...(config.include || []), ...args.include])];
448
+ if (args.log) log.enable(args.log);
367
449
  await require("./playgrounds/style-entrypoint.js").whenReady(config);
368
450
  const rootMarkers = config.rootMarkers;
369
451
  const repoRoot = args.repoRoot ? path.resolve(cwd, args.repoRoot) : findRepoRoot(cwd, rootMarkers) || cwd;
@@ -414,6 +496,7 @@ const main = async () => {
414
496
  fs.writeFileSync(reportPath, renderComponentReport(comp, args.verbose));
415
497
  console.log(`[component-uniqueness] wrote report ${reportPath} (${comp.matches.length} duplicate component(s), ${comp.rawHtml.length} raw-html element(s) across ${comp.files} file(s))`);
416
498
  }
499
+ log.flush();
417
500
  };
418
501
 
419
502
  if (require.main === module) {
@@ -13,15 +13,19 @@ const matchBehavior = (candidate, canon) => {
13
13
  const candA = new Set((candidate.framework && candidate.framework.events) || []);
14
14
  const canonA = new Set((canon.framework && canon.framework.events) || []);
15
15
  const shared = new Set([...candA].filter((event) => canonA.has(event)));
16
- const score = jaccard(candA, canonA);
16
+ const base = jaccard(candA, canonA);
17
+ const union = candA.size + canonA.size - shared.size;
18
+ const smallSetDiscount = Math.min(1, union / 2);
19
+ const score = base * smallSetDiscount;
17
20
  return {
18
21
  score,
19
22
  evidence: {
20
23
  candidateEvents: [...candA].sort(),
21
24
  canonicalEvents: [...canonA].sort(),
22
25
  sharedEvents: [...shared].sort(),
26
+ smallSetDiscount: Math.round(smallSetDiscount * 100) / 100,
23
27
  },
24
28
  };
25
- };;
29
+ };
26
30
 
27
31
  module.exports = { matchBehavior };
package/matcher/name.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const path = require("node:path");
4
+ const { pascalWords, GENERIC_WORDS } = require("../normalize/words.js");
4
5
 
5
6
  const FUZZY_NAME_MIN_LEN = 5;
6
7
  const FUZZY_BASENAME_MIN_LEN = 4;
@@ -14,10 +15,20 @@ const kebabToPascal = (s) =>
14
15
 
15
16
  const basenameToPascal = (file) => kebabToPascal(path.basename(file, path.extname(file)));
16
17
 
17
- const pascalWords = (s) => String(s || "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);
18
18
  const kebabWords = (s) => String(s || "").split(/[^A-Za-z0-9]+/).filter(Boolean);
19
19
  const singular = (w) => (w.length > 3 && w.endsWith("s") && !w.endsWith("ss") ? w.slice(0, -1) : w);
20
20
 
21
+ const wordSim = (a, b) => {
22
+ const wa = new Set(pascalWords(a).map((w) => singular(w.toLowerCase())).filter((w) => w.length >= 3 && !GENERIC_WORDS.has(w)));
23
+ const wb = new Set(pascalWords(b).map((w) => singular(w.toLowerCase())).filter((w) => w.length >= 3 && !GENERIC_WORDS.has(w)));
24
+ if (wa.size === 0 || wb.size === 0) return 0;
25
+ let inter = 0;
26
+ for (const w of wa) if (wb.has(w)) inter += 1;
27
+ const union = wa.size + wb.size - inter;
28
+
29
+ return union === 0 ? 0 : inter / union;
30
+ };
31
+
21
32
  const fuzzyNameHit = (appName, canonNames) => {
22
33
  const words = pascalWords(appName);
23
34
  if (words.length === 0) return null;
@@ -83,6 +94,8 @@ const matchName = (candidate, canon, ctx) => {
83
94
  fuzzy = fuzzyNameHit(candidate.name, [canon.name]) || fuzzyBasenameHit(candidate.path, [canon.name]);
84
95
  }
85
96
 
97
+ const word = wordSim(candidate.name, canon.name);
98
+
86
99
  let score = 0;
87
100
  let matchType = null;
88
101
  if (exactName) {
@@ -93,14 +106,18 @@ const matchName = (candidate, canon, ctx) => {
93
106
  matchType = "exact-basename";
94
107
  } else if (fuzzy) {
95
108
  const byName = !!fuzzyNameHit(candidate.name, [canon.name]);
96
- score = byName ? 0.7 : 0.6;
109
+ score = (byName ? 0.7 : 0.6) * (0.5 + 0.5 * word);
97
110
  matchType = byName ? "fuzzy-name" : "fuzzy-basename";
111
+ } else if (word > 0) {
112
+ score = 0.6 * word;
113
+ matchType = "word-overlap";
98
114
  }
99
115
 
100
116
  const evidence = {
101
117
  exactName,
102
118
  exactBasename,
103
119
  fuzzy: fuzzy ? fuzzy.name : null,
120
+ wordSim: Math.round(word * 100) / 100,
104
121
  matchType,
105
122
  };
106
123
  return { score, evidence };
@@ -1,11 +1,16 @@
1
1
  "use strict";
2
2
 
3
- const { NON_SEMANTIC_TAGS } = require("../normalize/dom.js");
3
+ const { NON_SEMANTIC_TAGS, isPascalCase } = require("../normalize/dom.js");
4
4
 
5
- const SINGLE_NODE_CEILING = 0.7;
6
- const FEW_NODES_CEILING = 0.85;
7
5
  const CONFLICT_PENALTY = 0.6;
8
6
  const CONFLICTED_RICH_CEILING = 0.8;
7
+ const RICH_DISTINCT_MIN = 3;
8
+ const CEILING_LADDER = [0.3, 0.5, 0.7, 0.9, 1.0];
9
+ const MISSING_CHILD_PENALTY = 0.15;
10
+ const NEAR_IDENTICAL_CEILING = 0.98;
11
+
12
+ const isTextNode = (node) => node.tag === "children" || node.tag === "text";
13
+ const isIconNode = (node) => isPascalCase(node.tag);
9
14
 
10
15
  const pairsOf = (css) => new Set(Object.entries(css || {}).map(([prop, value]) => `${prop}:${value}`));
11
16
 
@@ -19,13 +24,34 @@ const jaccard = (a, b) => {
19
24
 
20
25
  const coverage = (a, b) => (a.size === 0 ? 0 : overlap(a, b) / a.size);
21
26
 
27
+ const textSim = (a, b) => {
28
+ const ta = String(a.text || "").toLowerCase().trim();
29
+ const tb = String(b.text || "").toLowerCase().trim();
30
+ if (!ta && !tb) return 1;
31
+ if (!ta || !tb) return 0;
32
+
33
+ return ta === tb ? 1 : 0;
34
+ };
35
+
36
+ const tagMatch = (a, b) => {
37
+ if (a.tag === b.tag) return 1;
38
+ if (a.interactive && b.interactive) return 1;
39
+
40
+ return 0;
41
+ };
42
+
22
43
  const nodeSimilarity = (a, b) => {
23
- const tag = a.tag === b.tag ? 1 : 0;
44
+ if (isTextNode(a) && isTextNode(b)) return textSim(a, b);
45
+ if (isIconNode(a) && isIconNode(b)) return a.tag === b.tag ? 1 : 0.1;
46
+ const tag = tagMatch(a, b);
24
47
  const pa = pairsOf(a.css);
25
48
  const pb = pairsOf(b.css);
26
- if (pa.size === 0 && pb.size === 0) return tag;
49
+ let score = pa.size === 0 && pb.size === 0 ? tag : 0.6 * tag + 0.4 * jaccard(pa, pb);
50
+ const ta = String(a.text || "").trim();
51
+ const tb = String(b.text || "").trim();
52
+ if (ta || tb) score = 0.7 * score + 0.3 * textSim(a, b);
27
53
 
28
- return 0.6 * tag + 0.4 * jaccard(pa, pb);
54
+ return score;
29
55
  };
30
56
 
31
57
  const forestOf = (node) => (node.tag === "fragment" ? (node.children || []).flatMap(forestOf) : [node]);
@@ -93,7 +119,7 @@ const cssStats = (pairs) => {
93
119
 
94
120
  const rootNodeScore = (cand, target) => {
95
121
  const parts = [];
96
- if (!NON_SEMANTIC_TAGS.has(cand.tag)) parts.push({ w: 0.6, v: cand.tag === target.tag ? 1 : 0 });
122
+ if (!NON_SEMANTIC_TAGS.has(cand.tag)) parts.push({ w: 0.6, v: tagMatch(cand, target) });
97
123
  const candPairs = pairsOf(cand.css);
98
124
  if (candPairs.size > 0) parts.push({ w: 0.4, v: coverage(candPairs, pairsOf(target.css)) });
99
125
  const totalW = parts.reduce((sum, part) => sum + part.w, 0);
@@ -134,11 +160,20 @@ const sizeOf = (candidate) => {
134
160
  };
135
161
 
136
162
  const ceilingOf = (nodes, distinct, stats) => {
137
- if (nodes <= 1) return SINGLE_NODE_CEILING;
138
- if (nodes === 2) return SINGLE_NODE_CEILING + (1 - SINGLE_NODE_CEILING) * stats.agreement;
139
- if (distinct >= 3) return stats.conflicts > 0 ? CONFLICTED_RICH_CEILING : 1;
163
+ const base = CEILING_LADDER[Math.min(nodes - 1, CEILING_LADDER.length - 1)];
164
+ if (distinct >= RICH_DISTINCT_MIN && stats.conflicts > 0) return Math.min(base, CONFLICTED_RICH_CEILING);
165
+
166
+ return base;
167
+ };
168
+
169
+ const classTokensDiffer = (a, b) => {
170
+ const A = new Set(a || []);
171
+ const B = new Set(b || []);
172
+ if (A.size === 0 && B.size === 0) return false;
173
+ for (const token of A) if (!B.has(token)) return true;
174
+ for (const token of B) if (!A.has(token)) return true;
140
175
 
141
- return stats.conflicts > 0 ? SINGLE_NODE_CEILING : FEW_NODES_CEILING;
176
+ return false;
142
177
  };
143
178
 
144
179
  const matchStructure = (candidate, canon) => {
@@ -150,15 +185,20 @@ const matchStructure = (candidate, canon) => {
150
185
  let detail = null;
151
186
  if (applicable && cand && target) {
152
187
  if (candidate.partial) {
153
- score = rootNodeScore(cand, target);
188
+ const classesDiffer = classTokensDiffer(candidate.rawClasses, canon.rawClasses);
189
+ const base = rootNodeScore(cand, target);
190
+ score = Math.min(base, classesDiffer ? NEAR_IDENTICAL_CEILING : 1);
191
+ detail = { similarity: base, ceiling: classesDiffer ? NEAR_IDENTICAL_CEILING : 1, classesDiffer };
154
192
  } else {
155
193
  const result = compareForests(cand, target);
156
194
  const stats = cssStats(result.pairs);
157
195
  const a = sizeOf(candidate);
158
196
  const b = sizeOf(canon);
159
- const ceiling = ceilingOf(Math.min(a.nodes, b.nodes), Math.min(a.distinct, b.distinct), stats);
160
- score = Math.max(0, Math.min(result.score, ceiling) - CONFLICT_PENALTY * stats.ratio);
161
- detail = { similarity: result.score, ceiling, conflicts: stats.conflicts, conflictRatio: stats.ratio, agreement: stats.agreement, nodes: Math.min(a.nodes, b.nodes), distinct: Math.min(a.distinct, b.distinct) };
197
+ const classesDiffer = classTokensDiffer(candidate.rawClasses, canon.rawClasses);
198
+ const ceiling = Math.min(ceilingOf(Math.min(a.nodes, b.nodes), Math.min(a.distinct, b.distinct), stats), classesDiffer ? NEAR_IDENTICAL_CEILING : 1);
199
+ const missingRatio = Math.max(0, Math.max(a.nodes, b.nodes) - Math.min(a.nodes, b.nodes)) / Math.max(1, Math.max(a.nodes, b.nodes));
200
+ score = Math.max(0, Math.min(result.score, ceiling) - CONFLICT_PENALTY * stats.ratio - MISSING_CHILD_PENALTY * missingRatio);
201
+ detail = { similarity: result.score, ceiling, classesDiffer, conflicts: stats.conflicts, conflictRatio: stats.ratio, agreement: stats.agreement, missingRatio: Math.round(missingRatio * 100) / 100, nodes: Math.min(a.nodes, b.nodes), distinct: Math.min(a.distinct, b.distinct) };
162
202
  }
163
203
  }
164
204
 
@@ -2,11 +2,13 @@
2
2
 
3
3
  const { normalizeDom } = require("./dom.js");
4
4
  const { normalizeFramework } = require("./framework.js");
5
+ const { rawClassTokens } = require("../playgrounds/framework-entrypoint.js");
5
6
 
6
7
  const buildCandidate = (comp, config) => ({
7
8
  ...comp,
8
9
  dom: normalizeDom(comp.tree, config, comp.name),
9
- framework: normalizeFramework(comp.tree, comp.name),
10
+ framework: normalizeFramework(comp.rawTree || comp.tree, comp.name),
11
+ rawClasses: [...rawClassTokens(comp.rawTree || comp.tree)],
10
12
  });
11
13
 
12
14
  const buildElementCandidate = (element, config) => {
@@ -14,7 +16,7 @@ const buildElementCandidate = (element, config) => {
14
16
  if (framework.events.length === 0 && element.a11y.length === 0) return null;
15
17
  const dom = normalizeDom(element.tree, config, element.name);
16
18
 
17
- return { ...element, partial: true, dom, framework: { ...framework, names: [] } };
19
+ return { ...element, partial: true, dom, framework: { ...framework, names: [] }, rawClasses: [...rawClassTokens(element.tree)] };
18
20
  };
19
21
 
20
22
  module.exports = { buildCandidate, buildElementCandidate };
package/normalize/dom.js CHANGED
@@ -143,6 +143,8 @@ const styleObjectToCssText = (obj) => {
143
143
 
144
144
  const layoutOnly = (node) => ({
145
145
  tag: node.tag,
146
+ text: node.text || undefined,
147
+ interactive: !!node.interactive,
146
148
  css: Object.fromEntries(Object.entries(node.css || {}).filter(([prop]) => isLayoutProp(prop))),
147
149
  children: (node.children || []).map(layoutOnly),
148
150
  });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
 
3
- const { INTERACTIVE_TAGS } = require("./dom.js");
3
+ const { INTERACTIVE_TAGS, isPascalCase } = require("./dom.js");
4
4
 
5
5
  const EVENT_PREFIX = /^(on|ng|v-on:|@)/;
6
6
 
@@ -46,7 +46,7 @@ const eventsOf = (tree) => {
46
46
  const namesOf = (tree) => {
47
47
  const out = [];
48
48
  walk(tree, (node) => {
49
- if (node.tag) out.push(node.tag);
49
+ if (node.tag && isPascalCase(node.tag)) out.push(node.tag);
50
50
  });
51
51
  return out;
52
52
  };
@@ -76,14 +76,43 @@ const shared = (a, b) => {
76
76
  return [...new Set(a || [])].filter((item) => B.has(item)).sort();
77
77
  };
78
78
 
79
+ const smallSetDiscount = (arrA, arrB) => {
80
+ const A = new Set(arrA || []);
81
+ const B = new Set(arrB || []);
82
+ const inter = [...A].filter((x) => B.has(x)).length;
83
+ const union = A.size + B.size - inter;
84
+ return union === 0 ? 1 : Math.min(1, union / 2);
85
+ };
86
+
87
+ const setEqual = (a, b) => {
88
+ const A = new Set(a || []);
89
+ const B = new Set(b || []);
90
+ if (A.size !== B.size) return false;
91
+ for (const item of A) if (!B.has(item)) return false;
92
+
93
+ return true;
94
+ };
95
+
96
+ const SAME_NAMES_PROP_FLOOR = 0.95;
97
+ const SAME_NAMES_PROP_SPAN = 0.04;
98
+
79
99
  const frameworkSimilarity = (a, b, label) => {
80
- const props = jaccard(a && a.props, b && b.props);
81
- const events = jaccard(a && a.events, b && b.events);
82
- const names = jaccard(a && a.names, b && b.names);
100
+ const A = a || { props: [], events: [], names: [] };
101
+ const B = b || { props: [], events: [], names: [] };
102
+ const props = jaccard(A.props, B.props) * smallSetDiscount(A.props, B.props);
103
+ const events = jaccard(A.events, B.events) * smallSetDiscount(A.events, B.events);
104
+ const names = jaccard(A.names, B.names);
105
+ const passed = (p) => [...new Set([...p.props, ...p.events])];
106
+ const passedA = passed(A);
107
+ const passedB = passed(B);
108
+ if (A.names.length > 0 && names >= 1) {
109
+ if (setEqual(passedA, passedB)) return { score: 1, props, events, names };
110
+ return { score: SAME_NAMES_PROP_FLOOR + SAME_NAMES_PROP_SPAN * jaccard(passedA, passedB), props, events, names };
111
+ }
83
112
  const parts = [];
84
- if ((a && a.props.length) || (b && b.props.length)) parts.push({ w: 0.5, v: props });
85
- if ((a && a.events.length) || (b && b.events.length)) parts.push({ w: 0.2, v: events });
86
- if ((a && a.names.length) || (b && b.names.length)) parts.push({ w: 0.3, v: names });
113
+ if (A.props.length || B.props.length) parts.push({ w: 0.5, v: props });
114
+ if (A.events.length || B.events.length) parts.push({ w: 0.2, v: events });
115
+ if (A.names.length || B.names.length) parts.push({ w: 0.3, v: names });
87
116
  const totalW = parts.reduce((sum, part) => sum + part.w, 0);
88
117
  const score = totalW === 0 ? 0 : parts.reduce((sum, part) => sum + part.w * part.v, 0) / totalW;
89
118
  return { score, props, events, names };
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+
3
+ const pascalWords = (s) => String(s || "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);
4
+
5
+ const GENERIC_WORDS = new Set([
6
+ "button",
7
+ "field",
8
+ "input",
9
+ "select",
10
+ "box",
11
+ "list",
12
+ "item",
13
+ "row",
14
+ "cell",
15
+ "icon",
16
+ "label",
17
+ "value",
18
+ "text",
19
+ "data",
20
+ "info",
21
+ "meta",
22
+ "main",
23
+ "base",
24
+ "option",
25
+ "panel",
26
+ "view",
27
+ "form",
28
+ "card",
29
+ "tag",
30
+ "chip",
31
+ "badge",
32
+ "menu",
33
+ "bar",
34
+ "grid",
35
+ "table",
36
+ "section",
37
+ "state",
38
+ ]);
39
+
40
+ module.exports = { pascalWords, GENERIC_WORDS };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@md-code/component-uniqueness",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "ESLint rule and CLI that find duplicate components, raw HTML that should be a canonical component, and copied parts of components, by comparing structure, CSS, behavior, accessibility and framework profile.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -26,6 +26,7 @@
26
26
  "plugin.js",
27
27
  "config.js",
28
28
  "main.js",
29
+ "logger.js",
29
30
  "utils.js",
30
31
  "decision-maker.js",
31
32
  "report.js",
@@ -37,7 +38,7 @@
37
38
  ],
38
39
  "exports": {
39
40
  ".": "./index.js",
40
- "./plugin": "./plugin.js",
41
+ "./plugin": "./index.js",
41
42
  "./config": "./config.js",
42
43
  "./report": "./report.js",
43
44
  "./package.json": "./package.json"
@@ -60,6 +60,17 @@ const render = (tree, opts) => {
60
60
  return pg.render(tree, { stylesheet });
61
61
  };
62
62
 
63
+ const rawClassTokens = (tree) => {
64
+ const out = new Set();
65
+ const visit = (n) => {
66
+ if (!n) return;
67
+ if (typeof n.className === "string") for (const token of n.className.split(/\s+/)) if (token) out.add(token);
68
+ for (const child of n.children || []) visit(child);
69
+ };
70
+ visit(tree);
71
+ return out;
72
+ };
73
+
63
74
  module.exports = {
64
75
  getPlayground,
65
76
  getFramework,
@@ -68,4 +79,5 @@ module.exports = {
68
79
  parseParts,
69
80
  resolveCss,
70
81
  render,
82
+ rawClassTokens,
71
83
  };
@@ -5,7 +5,7 @@ const path = require("node:path");
5
5
  const ts = require("typescript");
6
6
  const { entries } = require("remeda");
7
7
  const style = require("../normalize/style.js");
8
- const { styleObjectToCssText, isPascalCase, isHtmlTag } = require("../normalize/dom.js");
8
+ const { styleObjectToCssText, isPascalCase, isHtmlTag, INTERACTIVE_TAGS } = require("../normalize/dom.js");
9
9
 
10
10
  const MAX_UNFOLD_DEPTH = 3;
11
11
  const MAX_TREE_NODES = 400;
@@ -478,7 +478,7 @@ const buildTree = (node, sf, ctx) => {
478
478
  cssText: styleObjectToCssText(styleObj),
479
479
  children,
480
480
  };
481
- if (!isHtmlTag(tag)) {
481
+ if (!isHtmlTag(tag) && !ctx.noUnfold) {
482
482
  const body = ctx.bodies.get(tag);
483
483
  if (body && ctx.depth < MAX_UNFOLD_DEPTH) {
484
484
  const inner = firstComponentNodeIn(body);
@@ -523,6 +523,9 @@ const childTrees = (node, sf, ctx) => {
523
523
  if (found.length === 0 && child.expression && ts.isIdentifier(child.expression) && child.expression.text === "children") {
524
524
  children.push({ tag: "children", attrs: {}, className: null, style: null, cssText: "", children: [] });
525
525
  }
526
+ } else if (ts.isJsxText(child)) {
527
+ const text = child.text.replace(/\s+/g, " ").trim();
528
+ if (text) children.push({ tag: "text", text, attrs: {}, className: null, style: null, cssText: "", children: [] });
526
529
  }
527
530
  }
528
531
  return children;
@@ -782,6 +785,32 @@ const parseParts = (fileAbs, canonicalNames, opts) => {
782
785
  return out;
783
786
  };
784
787
 
788
+ const declaredPropsOf = (node, sf) => {
789
+ let fn = null;
790
+ if (ts.isFunctionDeclaration(node)) fn = node;
791
+ else if (ts.isVariableStatement(node)) {
792
+ for (const d of node.declarationList.declarations) {
793
+ const init = d.initializer;
794
+ if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) fn = init;
795
+ break;
796
+ }
797
+ }
798
+ if (!fn || !fn.parameters || fn.parameters.length === 0) return [];
799
+ const param = fn.parameters[0];
800
+ const out = [];
801
+ const visit = (n) => {
802
+ if (!n) return;
803
+ if (ts.isObjectBindingPattern(n)) {
804
+ for (const el of n.elements) {
805
+ if (ts.isIdentifier(el.name)) out.push(el.name.text);
806
+ else visit(el.name);
807
+ }
808
+ }
809
+ };
810
+ if (ts.isObjectBindingPattern(param.name)) visit(param.name);
811
+ return [...new Set(out)].sort();
812
+ };
813
+
785
814
  const parseComponents = (fileAbs, canonicalNames, opts) => {
786
815
  useConfig(opts);
787
816
  const source = fs.readFileSync(fileAbs, "utf8");
@@ -804,13 +833,16 @@ const parseComponents = (fileAbs, canonicalNames, opts) => {
804
833
  if (!hasComponentMarkup(d.body)) continue;
805
834
  const root = firstComponentNodeIn(d.body);
806
835
  const tree = root ? buildTree(root, sf, { bodies, depth: 0, nodes: 0, resolveTag: (tag, props) => resolveTag(tag, fileAbs, 0, props) }) : null;
836
+ const rawTree = root ? buildTree(root, sf, { bodies, depth: 0, nodes: 0, noUnfold: true }) : null;
807
837
  const a11y = new Set();
808
838
  gatherA11y(d.body, sf, a11y);
809
839
  out.push({
810
840
  name: d.name,
811
841
  line: sf.getLineAndCharacterOfPosition(d.node.getStart(sf)).line + 1,
812
842
  isExported: isExported(d.node, sf) || localExportNames(sf).has(d.name),
843
+ declProps: declaredPropsOf(d.node, sf),
813
844
  tree,
845
+ rawTree,
814
846
  rootTags: [...rootTagsOf(d.body, sf)].sort(),
815
847
  actions: [],
816
848
  a11y: [...a11y].sort(),
@@ -853,6 +885,10 @@ const buildDom = (tree, doc) => {
853
885
  for (const [prop, values] of entries(tree.style)) el.style.setProperty(prop, Array.isArray(values) ? values.join(" ") : String(values));
854
886
  }
855
887
  for (const child of tree.children || []) {
888
+ if (child.tag === "text") {
889
+ el.appendChild(doc.createTextNode(child.text || ""));
890
+ continue;
891
+ }
856
892
  const node = buildDom(child, doc);
857
893
  if (node) el.appendChild(node);
858
894
  }
@@ -869,8 +905,11 @@ const nodesOf = (el, win, baselineOf) => {
869
905
  const value = computed.getPropertyValue(prop).trim();
870
906
  if (value && value !== base.getPropertyValue(prop).trim()) css[prop] = value;
871
907
  }
908
+ const tag = el.tagName.toLowerCase();
909
+ const interactive = INTERACTIVE_TAGS.has(tag) || el.getAttribute("role") === "button" || el.getAttribute("role") === "link" || [...el.attributes].some((attr) => /^(on|@)/.test(attr.name));
910
+ const text = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.nodeValue).join("").replace(/\s+/g, " ").trim();
872
911
 
873
- return [{ tag: el.tagName.toLowerCase(), css, children: kids }];
912
+ return [{ tag, css, interactive, text: text || undefined, children: kids }];
874
913
  };
875
914
 
876
915
  let sharedDom = null;
package/plugin.js CHANGED
@@ -1,14 +1,3 @@
1
1
  "use strict";
2
2
 
3
- const rule = require("./index");
4
- const pkg = require("./package.json");
5
-
6
- module.exports = {
7
- meta: {
8
- name: pkg.name,
9
- version: pkg.version,
10
- },
11
- rules: {
12
- "duplicate-component": rule,
13
- },
14
- };
3
+ module.exports = require("./index");
package/report.js CHANGED
@@ -21,7 +21,10 @@ const renderHeader = (comp) => {
21
21
  lines.push("# Component duplicates (component-level funnel)");
22
22
  lines.push("");
23
23
  lines.push(`Scanned ${comp.files} app file(s), ${comp.appCount} app component(s) against ${comp.canonCount} canonical component(s).`);
24
- lines.push(`Found ${comp.matches.length} duplicate component(s)${comp.dropped && comp.dropped.length > 0 ? ` (after filtering out ${comp.dropped.length} match(es))` : ""}.`);
24
+ const dupCount = comp.matches.filter((m) => m.decision.tier === "duplicate").length;
25
+ const simCount = comp.matches.filter((m) => m.decision.tier === "similar").length;
26
+ const missingCount = (comp.missingClusters || []).reduce((n, c) => n + c.matches.length, 0);
27
+ lines.push(`Found ${dupCount} duplicate component(s) and ${simCount} similar component(s)${comp.dropped && comp.dropped.length > 0 ? ` (after filtering out ${comp.dropped.length} match(es))` : ""}${missingCount > 0 ? `, plus ${missingCount} component(s) grouped under ${(comp.missingClusters || []).length} potentially missing component(s)` : ""}.`);
25
28
  lines.push("");
26
29
  return lines;
27
30
  };
@@ -40,6 +43,28 @@ const renderTierSection = (tier, rows, title = TIER_LABEL[tier]) => {
40
43
  return lines;
41
44
  };
42
45
 
46
+ const renderMissingSection = (clusters) => {
47
+ if (!clusters || clusters.length === 0) return [];
48
+ const lines = [];
49
+ lines.push(`## Potentially missing component (${clusters.length})`);
50
+ lines.push("");
51
+ lines.push("Several distinct components all matched the same canonical. This usually means the codebase is missing a shared component that would unify them — not that any single one is a duplicate. Consider extracting a new canonical component for each group below.");
52
+ lines.push("");
53
+ for (const cluster of clusters) {
54
+ lines.push(`### ${cluster.name}`);
55
+ lines.push("");
56
+ lines.push(`All ${cluster.matches.length} components below matched canonical \`${cluster.canon.name}\` (\`${cluster.canon.path}\`). They are structurally similar to each other but distinct enough that none is a clean duplicate — a shared \`${cluster.name}\` would likely cover them.`);
57
+ lines.push("");
58
+ lines.push("| Local component | Location | Matched canonical | Confidence | Why |");
59
+ lines.push("| --- | --- | --- | --- | --- |");
60
+ for (const m of cluster.matches) {
61
+ lines.push(`| ${m.app.name} | \`${m.app.path}:${m.app.line}\` | ${m.canon.name} | ${m.decision.confidence.toFixed(2)} | ${m.decision.reason} |`);
62
+ }
63
+ lines.push("");
64
+ }
65
+ return lines;
66
+ };
67
+
43
68
  const renderRawHtmlSection = (rows) => {
44
69
  if (rows.length === 0) return [];
45
70
  const lines = [];
@@ -105,6 +130,8 @@ const renderComponentReport = (comp, verbose) => {
105
130
  if (rows.length === 0) continue;
106
131
  lines.push(...renderTierSection(tier, rows));
107
132
  }
133
+ const missingClusters = (comp.missingClusters || []).filter((c) => !inLayer(c.canon.path));
134
+ lines.push(...renderMissingSection(missingClusters));
108
135
  if (comp.rawHtml && comp.rawHtml.length > 0) lines.push(...renderRawHtmlSection(comp.rawHtml));
109
136
  lines.push(...renderPartsSection(appParts));
110
137
  for (const tier of TIERS) {