@md-code/component-uniqueness 0.1.1 → 0.1.3
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 +10 -0
- package/config.js +29 -4
- package/decision-maker.js +4 -8
- package/filter/drop-usages.js +4 -1
- package/filter/missing-component.js +68 -0
- package/logger.js +44 -0
- package/main.js +115 -9
- package/matcher/behavior.js +6 -2
- package/matcher/name.js +19 -2
- package/matcher/structure.js +55 -15
- package/normalize/candidate.js +4 -2
- package/normalize/dom.js +2 -0
- package/normalize/framework.js +37 -8
- package/normalize/style-resolver.js +24 -0
- package/normalize/style.js +1 -0
- package/normalize/words.js +40 -0
- package/package.json +2 -1
- package/playgrounds/framework-entrypoint.js +22 -3
- package/playgrounds/react.js +77 -8
- package/playgrounds/styled-components.js +132 -1
- package/report.js +159 -126
package/README.md
CHANGED
|
@@ -90,4 +90,14 @@ Options are read from the rule in `eslint.config.js`.
|
|
|
90
90
|
| `--app-roots a:b` | Folders to scan for the report (default: repo root) |
|
|
91
91
|
| `--repo-root <dir>` | Repo root (default: auto-detected) |
|
|
92
92
|
| `--out <file>` | Catalog path |
|
|
93
|
+
| `--include a.tsx:b.tsx` | Only scan matching app files |
|
|
94
|
+
| `--ignore-dirs a:b` | Extra directories to skip |
|
|
95
|
+
| `--thresholds dup:sim` | Confidence cut-offs, e.g. `0.5:0.3` |
|
|
96
|
+
| `--raw-html` | Also report raw HTML that should be a canonical component |
|
|
97
|
+
| `--parts` | Also report blocks inside components that duplicate a canonical |
|
|
98
|
+
| `--config file` | Read rule options from a specific `eslint.config.js` or options file |
|
|
99
|
+
| `--min-cluster N` | Min app components matching one canonical to flag it as a missing component (default 3) |
|
|
100
|
+
| `--log file` | Write a per-stage JSON log |
|
|
93
101
|
| `--verbose` | Also list what the filters dropped |
|
|
102
|
+
|
|
103
|
+
Rule options (`weights`, `thresholds`, `rawHtml`, `parts`, `include`, `ignoreDirs`) are always read from the consumer's `eslint.config.js` (rule `md-code/component-uniqueness`) or `md-code-component-uniqueness.config.js`; `--config` points to a specific file. CLI flags override the config.
|
package/config.js
CHANGED
|
@@ -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
|
|
234
|
+
const v = ruleValue(entry.rules);
|
|
224
235
|
if (v === undefined || v === null) continue;
|
|
225
236
|
return pickOptions(v);
|
|
226
237
|
}
|
|
@@ -229,11 +240,25 @@ const loadFlatOptions = async (file) => {
|
|
|
229
240
|
|
|
230
241
|
const loadLegacyOptions = async (file) => {
|
|
231
242
|
const mod = await loadModule(file);
|
|
232
|
-
const
|
|
233
|
-
return pickOptions(
|
|
243
|
+
const v = ruleValue((mod && mod.rules) || {});
|
|
244
|
+
return v === undefined || v === null ? null : pickOptions(v);
|
|
234
245
|
};
|
|
235
246
|
|
|
236
|
-
const loadRuleOptions = async (dir) => {
|
|
247
|
+
const loadRuleOptions = async (dir, explicitFile = null) => {
|
|
248
|
+
if (explicitFile) {
|
|
249
|
+
const file = path.isAbsolute(explicitFile) ? explicitFile : path.resolve(dir, explicitFile);
|
|
250
|
+
if (!fs.existsSync(file)) return null;
|
|
251
|
+
if (file.endsWith(".json")) {
|
|
252
|
+
const options = pickOptions(JSON.parse(fs.readFileSync(file, "utf8")));
|
|
253
|
+
return options ? { options, source: file } : null;
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
const options = file.startsWith("eslint.config") ? await loadFlatOptions(file) : pickOptions(await loadModule(file));
|
|
257
|
+
return options ? { options, source: file } : null;
|
|
258
|
+
} catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
237
262
|
let d = dir;
|
|
238
263
|
for (;;) {
|
|
239
264
|
const standalone = path.join(d, "md-code-component-uniqueness.config.js");
|
package/decision-maker.js
CHANGED
|
@@ -12,8 +12,8 @@ const DEFAULT_WEIGHTS = {
|
|
|
12
12
|
};
|
|
13
13
|
|
|
14
14
|
const DEFAULT_THRESHOLDS = {
|
|
15
|
-
duplicate: 0.
|
|
16
|
-
similar: 0.
|
|
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
|
|
81
|
-
const
|
|
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,
|
package/filter/drop-usages.js
CHANGED
|
@@ -2,7 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
const test = (match) => {
|
|
4
4
|
if ((match.app.usesCanonical || []).includes(match.canon.name)) {
|
|
5
|
-
return
|
|
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,68 @@
|
|
|
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).slice(0, 3).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
|
+
if (canonName) {
|
|
31
|
+
const canonWords = pascalWords(canonName).filter((w) => !GENERIC_WORDS.has(w.toLowerCase()));
|
|
32
|
+
if (canonWords.length > 0) {
|
|
33
|
+
return pascalCase(["shared", ...canonWords.slice(0, 2)]);
|
|
34
|
+
}
|
|
35
|
+
return `Shared${canonName}`;
|
|
36
|
+
}
|
|
37
|
+
return "SharedComponent";
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const findMissingComponents = (matches, { minCluster = DEFAULT_MIN_CLUSTER } = {}) => {
|
|
41
|
+
const byCanon = new Map();
|
|
42
|
+
for (const match of matches) {
|
|
43
|
+
const key = match.canon.name;
|
|
44
|
+
if (!byCanon.has(key)) byCanon.set(key, []);
|
|
45
|
+
byCanon.get(key).push(match);
|
|
46
|
+
}
|
|
47
|
+
const clusters = [];
|
|
48
|
+
const clusteredKeys = new Set();
|
|
49
|
+
for (const [canonName, group] of byCanon) {
|
|
50
|
+
const distinctApps = new Set(group.map((m) => m.app.name));
|
|
51
|
+
if (distinctApps.size < minCluster) continue;
|
|
52
|
+
clusteredKeys.add(canonName);
|
|
53
|
+
clusters.push({
|
|
54
|
+
name: suggestName(group.map((m) => m.app.name), canonName),
|
|
55
|
+
canon: group[0].canon,
|
|
56
|
+
matches: [...group].sort((a, b) => b.decision.confidence - a.decision.confidence),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
clusters.sort((a, b) => b.matches.length - a.matches.length || a.name.localeCompare(b.name));
|
|
60
|
+
const remaining = matches.filter((m) => !clusteredKeys.has(m.canon.name));
|
|
61
|
+
return { clusters, remaining };
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
module.exports = {
|
|
65
|
+
findMissingComponents,
|
|
66
|
+
suggestName,
|
|
67
|
+
DEFAULT_MIN_CLUSTER,
|
|
68
|
+
};
|
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, thresholds: null, rawHtml: false, parts: false, configFile: null };
|
|
39
61
|
for (let i = 0; i < argv.length; i += 1) {
|
|
40
62
|
const a = argv[i];
|
|
41
63
|
if (a === "--check") {
|
|
@@ -65,11 +87,35 @@ const parseArgs = (argv) => {
|
|
|
65
87
|
} else if (a === "--ignore-dirs") {
|
|
66
88
|
if (!argv[i + 1]) fail("--ignore-dirs requires a value (colon-separated list of directory names)");
|
|
67
89
|
cfg.ignoreDirs = argv[++i].split(":").filter(Boolean);
|
|
90
|
+
} else if (a === "--raw-html") {
|
|
91
|
+
cfg.rawHtml = true;
|
|
92
|
+
} else if (a === "--parts") {
|
|
93
|
+
cfg.parts = true;
|
|
68
94
|
} else if (a === "--verbose") {
|
|
69
95
|
cfg.verbose = true;
|
|
96
|
+
} else if (a === "--include") {
|
|
97
|
+
if (!argv[i + 1]) fail("--include requires a value (colon-separated list of file globs, e.g. a.tsx:b.tsx)");
|
|
98
|
+
cfg.include = argv[++i].split(":").filter(Boolean);
|
|
99
|
+
} else if (a === "--log") {
|
|
100
|
+
if (!argv[i + 1]) fail("--log requires a value (path to the stage log file)");
|
|
101
|
+
cfg.log = argv[++i];
|
|
102
|
+
} else if (a === "--thresholds") {
|
|
103
|
+
if (!argv[i + 1]) fail("--thresholds requires a value (duplicate:similar, e.g. 0.5:0.2)");
|
|
104
|
+
const [dup, sim] = argv[++i].split(":").map((s) => Number.parseFloat(s));
|
|
105
|
+
if (!Number.isFinite(dup) || !Number.isFinite(sim)) fail("--thresholds must be two numbers separated by a colon (duplicate:similar)");
|
|
106
|
+
cfg.thresholds = { duplicate: dup, similar: sim };
|
|
107
|
+
} else if (a === "--min-cluster") {
|
|
108
|
+
if (!argv[i + 1]) fail("--min-cluster requires a value (min app components matching one canonical to flag it as a missing component)");
|
|
109
|
+
const n = Number.parseInt(argv[i + 1], 10);
|
|
110
|
+
if (!Number.isFinite(n) || n < 2) fail("--min-cluster must be an integer >= 2");
|
|
111
|
+
cfg.minCluster = n;
|
|
112
|
+
i += 1;
|
|
113
|
+
} else if (a === "--config") {
|
|
114
|
+
if (!argv[i + 1]) fail("--config requires a value (path to an eslint.config.js or a standalone options file)");
|
|
115
|
+
cfg.configFile = argv[++i];
|
|
70
116
|
} 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("
|
|
117
|
+
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] [--thresholds dup:sim] [--raw-html] [--parts] [--config file] [--log file] [--min-cluster N] [--verbose]");
|
|
118
|
+
console.log("Rule options (weights, thresholds, rawHtml, parts, include, ignoreDirs) are read from the consumer's eslint.config.js (rule md-code/component-uniqueness) or md-code-component-uniqueness.config.js; --config points to a specific file. CLI flags override the config.");
|
|
73
119
|
process.exit(0);
|
|
74
120
|
} else {
|
|
75
121
|
fail(`unknown argument: ${a} (see --help)`);
|
|
@@ -116,8 +162,15 @@ const parseComponents = (files, canonNames, config, role = "CANONICAL") => {
|
|
|
116
162
|
continue;
|
|
117
163
|
}
|
|
118
164
|
for (const c of parsed) {
|
|
165
|
+
if (log.enabled()) {
|
|
166
|
+
log.stage("normalizer:before", { role, file: rel, name: c.name, tree: treeSummary(c.tree), rootTags: c.rootTags, a11y: c.a11y });
|
|
167
|
+
}
|
|
119
168
|
const candidate = buildCandidate(c, config);
|
|
120
|
-
|
|
169
|
+
const withPath = { ...candidate, path: rel };
|
|
170
|
+
if (log.enabled()) {
|
|
171
|
+
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 } });
|
|
172
|
+
}
|
|
173
|
+
comps.push(withPath);
|
|
121
174
|
}
|
|
122
175
|
}
|
|
123
176
|
return comps;
|
|
@@ -130,9 +183,21 @@ const matchPairs = (appComponents, canonComponents, config) => {
|
|
|
130
183
|
for (const canon of canonComponents) {
|
|
131
184
|
if (canon.path === app.path && canon.name === app.name) continue;
|
|
132
185
|
if (!canSeeCanon(app.path, canon.path, config.componentsFolder)) continue;
|
|
186
|
+
if (log.enabled()) {
|
|
187
|
+
log.stage("matcher:before", { app: candidateSummary(app, "candidate"), canon: candidateSummary(canon, "canonical") });
|
|
188
|
+
}
|
|
133
189
|
const signals = matchSignals(app, canon, { canonNames, frameworkMatcher });
|
|
190
|
+
if (log.enabled()) {
|
|
191
|
+
log.stage("matcher:after", { app: { name: app.name, path: app.path }, canon: { name: canon.name, path: canon.path }, signals });
|
|
192
|
+
}
|
|
193
|
+
if (log.enabled()) {
|
|
194
|
+
log.stage("decision:before", { app: { name: app.name, path: app.path }, canon: { name: canon.name, path: canon.path }, signals });
|
|
195
|
+
}
|
|
134
196
|
const decision = decide(app, canon, { signals, weights: config.weights, thresholds: config.thresholds });
|
|
135
|
-
if (
|
|
197
|
+
if (log.enabled()) {
|
|
198
|
+
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])) });
|
|
199
|
+
}
|
|
200
|
+
if (!decision.tier) continue;
|
|
136
201
|
matches.push({ app, canon, decision, tier: decision.tier, reason: decision.reason });
|
|
137
202
|
}
|
|
138
203
|
}
|
|
@@ -143,6 +208,9 @@ const applyFilters = (matches) => {
|
|
|
143
208
|
const kept = [];
|
|
144
209
|
const dropped = [];
|
|
145
210
|
for (const match of matches) {
|
|
211
|
+
if (log.enabled()) {
|
|
212
|
+
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 });
|
|
213
|
+
}
|
|
146
214
|
let hit = null;
|
|
147
215
|
for (const f of FILTERS) {
|
|
148
216
|
const reason = f.test(match);
|
|
@@ -151,12 +219,29 @@ const applyFilters = (matches) => {
|
|
|
151
219
|
break;
|
|
152
220
|
}
|
|
153
221
|
}
|
|
154
|
-
if (hit)
|
|
155
|
-
|
|
222
|
+
if (hit) {
|
|
223
|
+
dropped.push(hit);
|
|
224
|
+
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 });
|
|
225
|
+
} else {
|
|
226
|
+
kept.push(match);
|
|
227
|
+
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 });
|
|
228
|
+
}
|
|
156
229
|
}
|
|
157
230
|
return { kept, dropped };
|
|
158
231
|
};
|
|
159
232
|
|
|
233
|
+
const pairKey = (match) => [match.app.name, match.canon.name].sort().join("::");
|
|
234
|
+
|
|
235
|
+
const dedupPairs = (matches) => {
|
|
236
|
+
const best = new Map();
|
|
237
|
+
for (const match of matches) {
|
|
238
|
+
const key = pairKey(match);
|
|
239
|
+
const prev = best.get(key);
|
|
240
|
+
if (!prev || match.decision.confidence > prev.decision.confidence) best.set(key, match);
|
|
241
|
+
}
|
|
242
|
+
return [...best.values()];
|
|
243
|
+
};
|
|
244
|
+
|
|
160
245
|
const collectRawHtml = (appFiles, canonComponents, config, canonNames) => {
|
|
161
246
|
if (!config.rawHtml) return [];
|
|
162
247
|
const rows = [];
|
|
@@ -331,15 +416,25 @@ const buildComponentReport = async (args, repoRoot, roots, shouldSkip, config, r
|
|
|
331
416
|
|
|
332
417
|
const matches = matchPairs(appComponents, uniqueCanon, config);
|
|
333
418
|
const { kept, dropped } = applyFilters(matches);
|
|
419
|
+
const deduped = dedupPairs(kept);
|
|
334
420
|
stage("components matched");
|
|
421
|
+
const inLayer = (p) => (config.componentsFolder || []).some((d) => p.startsWith(d));
|
|
422
|
+
const layerMatches = deduped.filter((m) => inLayer(m.app.path));
|
|
423
|
+
const appMatches = deduped.filter((m) => !inLayer(m.app.path));
|
|
424
|
+
const { clusters, remaining } = findMissingComponents(appMatches, { minCluster: args.minCluster });
|
|
425
|
+
if (log.enabled()) {
|
|
426
|
+
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 });
|
|
427
|
+
}
|
|
428
|
+
stage("missing-component clustered");
|
|
335
429
|
const rawHtml = collectRawHtml(appFiles.files, uniqueCanon, config, canonNames);
|
|
336
430
|
stage("raw html done");
|
|
337
431
|
const parts = collectParts(appFiles.files, uniqueCanon, config, canonNames);
|
|
338
432
|
stage("parts done");
|
|
339
433
|
|
|
340
434
|
return {
|
|
341
|
-
matches:
|
|
435
|
+
matches: [...remaining, ...layerMatches],
|
|
342
436
|
dropped,
|
|
437
|
+
missingClusters: clusters,
|
|
343
438
|
rawHtml,
|
|
344
439
|
parts,
|
|
345
440
|
layerFolders: config.componentsFolder,
|
|
@@ -353,10 +448,12 @@ const main = async () => {
|
|
|
353
448
|
const args = parseArgs(process.argv.slice(2));
|
|
354
449
|
const cwd = process.cwd();
|
|
355
450
|
|
|
356
|
-
const loaded =
|
|
451
|
+
const loaded = await loadRuleOptions(cwd, args.configFile);
|
|
357
452
|
const configOptions = loaded ? { ...loaded.options } : {};
|
|
358
453
|
if (loaded) {
|
|
359
454
|
console.log(`[component-uniqueness] config from ${loaded.source}`);
|
|
455
|
+
} else if (!args.configFile) {
|
|
456
|
+
console.log("[component-uniqueness] no rule options found in eslint.config.js / md-code-component-uniqueness.config.js; using defaults");
|
|
360
457
|
}
|
|
361
458
|
if (args.ignoreDirs) {
|
|
362
459
|
const base = Array.isArray(configOptions.ignoreDirs) ? configOptions.ignoreDirs : [];
|
|
@@ -364,6 +461,11 @@ const main = async () => {
|
|
|
364
461
|
}
|
|
365
462
|
|
|
366
463
|
const config = normalizeOptions(configOptions);
|
|
464
|
+
if (args.include) config.include = [...new Set([...(config.include || []), ...args.include])];
|
|
465
|
+
if (args.thresholds) config.thresholds = { ...(config.thresholds || {}), ...args.thresholds };
|
|
466
|
+
if (args.rawHtml) config.rawHtml = true;
|
|
467
|
+
if (args.parts) config.parts = true;
|
|
468
|
+
if (args.log) log.enable(args.log);
|
|
367
469
|
await require("./playgrounds/style-entrypoint.js").whenReady(config);
|
|
368
470
|
const rootMarkers = config.rootMarkers;
|
|
369
471
|
const repoRoot = args.repoRoot ? path.resolve(cwd, args.repoRoot) : findRepoRoot(cwd, rootMarkers) || cwd;
|
|
@@ -373,6 +475,9 @@ const main = async () => {
|
|
|
373
475
|
if (!roots || roots.length === 0) {
|
|
374
476
|
fail("no scan roots: pass --roots <dir1>:<dir2> or set componentsFolder in the rule options (eslint.config.js / component-uniqueness.config.js)");
|
|
375
477
|
}
|
|
478
|
+
if (!config.componentsFolder || config.componentsFolder.length === 0) {
|
|
479
|
+
config.componentsFolder = roots;
|
|
480
|
+
}
|
|
376
481
|
|
|
377
482
|
const outPath = resolveAgainst(args.out || config.catalogPath, repoRoot);
|
|
378
483
|
const registry = args.registry ? loadRegistry({ ...config, registry: null, registryPath: args.registry }) : loadRegistry(config);
|
|
@@ -414,6 +519,7 @@ const main = async () => {
|
|
|
414
519
|
fs.writeFileSync(reportPath, renderComponentReport(comp, args.verbose));
|
|
415
520
|
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
521
|
}
|
|
522
|
+
log.flush();
|
|
417
523
|
};
|
|
418
524
|
|
|
419
525
|
if (require.main === module) {
|
package/matcher/behavior.js
CHANGED
|
@@ -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
|
|
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 };
|
package/matcher/structure.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
138
|
-
if (
|
|
139
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
160
|
-
|
|
161
|
-
|
|
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
|
|