@md-code/component-uniqueness 0.1.1 → 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/config.js +14 -3
- package/decision-maker.js +4 -8
- package/filter/drop-usages.js +4 -1
- package/filter/missing-component.js +62 -0
- package/logger.js +44 -0
- package/main.js +90 -7
- 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/words.js +40 -0
- package/package.json +2 -1
- package/playgrounds/framework-entrypoint.js +12 -0
- package/playgrounds/react.js +42 -3
- package/report.js +28 -1
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,8 +240,8 @@ 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
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.
|
|
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,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/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,8 +89,20 @@ 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]");
|
|
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]");
|
|
72
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 {
|
|
@@ -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
|
-
|
|
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 (
|
|
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)
|
|
155
|
-
|
|
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:
|
|
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) {
|
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
|
|
package/normalize/candidate.js
CHANGED
|
@@ -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
|
});
|
package/normalize/framework.js
CHANGED
|
@@ -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
|
|
81
|
-
const
|
|
82
|
-
const
|
|
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 (
|
|
85
|
-
if (
|
|
86
|
-
if (
|
|
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.
|
|
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",
|
|
@@ -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
|
};
|
package/playgrounds/react.js
CHANGED
|
@@ -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
|
|
912
|
+
return [{ tag, css, interactive, text: text || undefined, children: kids }];
|
|
874
913
|
};
|
|
875
914
|
|
|
876
915
|
let sharedDom = null;
|
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
|
-
|
|
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) {
|