@md-code/component-uniqueness 0.1.0

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/index.js ADDED
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+
3
+ const path = require("node:path");
4
+
5
+ const {
6
+ normalizeOptions,
7
+ inComponentsFolder,
8
+ canSeeCanon,
9
+ isIgnored,
10
+ loadRegistry,
11
+ loadCatalog,
12
+ RULE_NAME,
13
+ RULE_SHORT,
14
+ } = require("./config");
15
+ const { parseComponents, parseElements } = require("./playgrounds/framework-entrypoint.js");
16
+ const { buildCandidate, buildElementCandidate } = require("./normalize/candidate.js");
17
+ const { matchSignals } = require("./matcher");
18
+ const { getFrameworkMatcher } = require("./matcher/framework");
19
+ const { decide, bestOf } = require("./decision-maker");
20
+ const { matchPairs, applyFilters, findParts } = require("./main");
21
+
22
+ const frameworkMatcher = getFrameworkMatcher("react");
23
+
24
+ const isComponentBinding = (node) => {
25
+ if (!node || node.type !== "Identifier") return false;
26
+ if (!/^[A-Z]/.test(node.name)) return false;
27
+ let parent = node.parent;
28
+ while (parent) {
29
+ if (parent.type === "TSInterfaceDeclaration") return false;
30
+ if (parent.type === "TSTypeAliasDeclaration") return false;
31
+ if (parent.type === "TSModuleDeclaration") return false;
32
+ if (parent.type === "ExportNamedDeclaration" || parent.type === "ExportDefaultDeclaration") break;
33
+ parent = parent.parent;
34
+ }
35
+ return true;
36
+ };
37
+
38
+ const createRule = () => {
39
+ return {
40
+ meta: {
41
+ type: "problem",
42
+ docs: {
43
+ description: "Flag components that duplicate a canonical component, and raw HTML elements that should use the canonical packages.",
44
+ },
45
+ messages: {
46
+ duplicateComponent: "Component \"{{name}}\" duplicates the canonical \"{{canonName}}\" ({{reason}}).",
47
+ rawHtml: "Raw <{{tag}}> outside the canonical packages → replace with `{{component}}` from {{path}} ({{reason}}).",
48
+ partOfComponent: "This <{{tag}}> block in {{owner}} duplicates `{{component}}` from {{path}} ({{reason}}).",
49
+ },
50
+ schema: [
51
+ {
52
+ type: "object",
53
+ properties: {
54
+ registry: { type: "string" },
55
+ registryPath: { type: "string" },
56
+ catalog: { type: "array" },
57
+ catalogPath: { type: "string" },
58
+ includeDynamic: { type: "boolean" },
59
+ dynamicCatalog: { type: "array" },
60
+ dynamicCatalogPath: { type: "string" },
61
+ rawHtml: { type: "boolean" },
62
+ parts: { type: "boolean" },
63
+ tsconfig: { type: "string" },
64
+ weights: { type: "object" },
65
+ thresholds: { type: "object" },
66
+ componentsFolder: { type: "array" },
67
+ include: { type: "array" },
68
+ exclude: { type: "array" },
69
+ exts: { type: "array" },
70
+ ignoreDirs: { type: "array" },
71
+ rootMarkers: { type: "array" },
72
+ },
73
+ additionalProperties: false,
74
+ },
75
+ ],
76
+ },
77
+ create(context) {
78
+ const options = context.options && context.options[0] ? context.options[0] : {};
79
+ const config = normalizeOptions(options);
80
+ const filename = context.filename || (context.getFilename ? context.getFilename() : "");
81
+ const relPath = path.relative(context.cwd || process.cwd(), filename).split(path.sep).join("/");
82
+
83
+ const isInComponentsFolder = inComponentsFolder(relPath, config.componentsFolder);
84
+ if (isIgnored(relPath, isInComponentsFolder ? [] : config.include, config.exclude)) return {};
85
+
86
+ const registry = loadRegistry(config);
87
+ const catalogComponents = ((loadCatalog(config) || {}).components) || [];
88
+ const canonNames = [...new Set(catalogComponents.map((c) => c.name))];
89
+
90
+ const checkDuplicates = () => {
91
+ let parsed;
92
+ try {
93
+ parsed = parseComponents(filename, canonNames, config);
94
+ } catch {
95
+ return;
96
+ }
97
+ const normalizeComp = (comp) => buildCandidate(comp, config);
98
+
99
+ const normCanons = new Map();
100
+ for (const comp of parsed) {
101
+ if (!comp.isExported) continue;
102
+ const candidate = normalizeComp({ ...comp, path: relPath });
103
+ const pairs = [];
104
+ for (const canon of catalogComponents) {
105
+ if (canon.name === candidate.name) continue;
106
+ 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
+ }
112
+ const signals = matchSignals(candidate, normCanon, { canonNames, frameworkMatcher });
113
+ const decision = decide(candidate, normCanon, { signals, weights: config.weights, thresholds: config.thresholds });
114
+ pairs.push({ canon: normCanon, signals, decision });
115
+ }
116
+ pairs.sort((a, b) => b.decision.confidence - a.decision.confidence);
117
+ for (const p of pairs) {
118
+ if (!p.decision.isDuplicate) continue;
119
+ const { kept } = applyFilters([{ app: candidate, canon: p.canon, decision: p.decision, tier: p.decision.tier, reason: p.decision.reason }]);
120
+ if (kept.length === 0) continue;
121
+ const line = comp.line || 1;
122
+ context.report({
123
+ loc: { start: { line, column: 0 }, end: { line, column: 0 } },
124
+ messageId: "duplicateComponent",
125
+ data: { name: candidate.name, canonName: p.canon.name, reason: p.decision.reason },
126
+ });
127
+ }
128
+ }
129
+ 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
+ });
135
+ let elements = [];
136
+ try {
137
+ elements = parseElements(filename, canonNames, config);
138
+ } catch {
139
+ elements = [];
140
+ }
141
+ for (const element of elements) {
142
+ const candidate = buildElementCandidate(element, config);
143
+ if (!candidate) continue;
144
+ const best = bestOf(matchPairs([{ ...candidate, path: relPath }], canons, config));
145
+ if (!best) continue;
146
+ context.report({
147
+ loc: { start: { line: element.line, column: element.column }, end: { line: element.line, column: element.column } },
148
+ messageId: "rawHtml",
149
+ data: { tag: element.name, component: best.canon.name, path: best.canon.path, reason: best.decision.reason },
150
+ });
151
+ }
152
+ }
153
+ 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
+ });
159
+ for (const { part, best } of findParts(filename, relPath, canons, config, new Set(canonNames))) {
160
+ context.report({
161
+ loc: { start: { line: part.line, column: part.column }, end: { line: part.endLine, column: 0 } },
162
+ messageId: "partOfComponent",
163
+ data: { owner: part.owner, tag: part.rootTag, component: best.canon.name, path: best.canon.path, reason: best.decision.reason },
164
+ });
165
+ }
166
+ }
167
+ };
168
+
169
+ return {
170
+ "Program:exit": checkDuplicates,
171
+ };
172
+ },
173
+ };
174
+ };
175
+
176
+ module.exports = createRule();
177
+ module.exports.RULE_NAME = RULE_NAME;
178
+ module.exports.RULE_SHORT = RULE_SHORT;
package/main.js ADDED
@@ -0,0 +1,433 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+
7
+ const {
8
+ findRepoRoot,
9
+ isIgnored,
10
+ inComponentsFolder,
11
+ canSeeCanon,
12
+ DEFAULT_EXTS,
13
+ DEFAULT_IGNORE_DIRS,
14
+ loadRuleOptions,
15
+ normalizeOptions,
16
+ loadRegistry,
17
+ loadCatalog,
18
+ } = require("./config");
19
+ const { walk, writeCatalog } = require("./utils");
20
+ const { parseComponents: parseComponentsViaEntrypoint, parseElements: parseElementsViaEntrypoint, parseParts: parsePartsViaEntrypoint } = require("./playgrounds/framework-entrypoint.js");
21
+ const { buildCandidate, buildElementCandidate } = require("./normalize/candidate.js");
22
+ const { matchSignals } = require("./matcher");
23
+ const { getFrameworkMatcher } = require("./matcher/framework");
24
+ const { decide, bestOf } = require("./decision-maker");
25
+ const dropUsages = require("./filter/drop-usages");
26
+ const dropChildElement = require("./filter/drop-child-element");
27
+ const { renderComponentReport } = require("./report");
28
+
29
+ const FILTERS = [dropUsages, dropChildElement];
30
+ const frameworkMatcher = getFrameworkMatcher("react");
31
+
32
+ const fail = (message) => {
33
+ console.error(`[component-uniqueness] ${message}`);
34
+ process.exit(1);
35
+ };
36
+
37
+ const parseArgs = (argv) => {
38
+ const cfg = { roots: null, out: null, registry: null, repoRoot: null, check: false, report: null, appRoots: null, ignoreDirs: null, verbose: false };
39
+ for (let i = 0; i < argv.length; i += 1) {
40
+ const a = argv[i];
41
+ if (a === "--check") {
42
+ cfg.check = true;
43
+ } else if (a === "--report") {
44
+ const next = argv[i + 1];
45
+ if (next && !next.startsWith("--")) {
46
+ cfg.report = argv[++i];
47
+ } else {
48
+ cfg.report = "reports/component-duplicates-components.md";
49
+ }
50
+ } else if (a === "--roots") {
51
+ if (!argv[i + 1]) fail("--roots requires a value (colon-separated list of directories)");
52
+ cfg.roots = argv[++i].split(":").filter(Boolean);
53
+ } else if (a === "--out") {
54
+ if (!argv[i + 1]) fail("--out requires a value");
55
+ cfg.out = argv[++i];
56
+ } else if (a === "--registry") {
57
+ if (!argv[i + 1]) fail("--registry requires a value");
58
+ cfg.registry = argv[++i];
59
+ } else if (a === "--repo-root") {
60
+ if (!argv[i + 1]) fail("--repo-root requires a value");
61
+ cfg.repoRoot = argv[++i];
62
+ } else if (a === "--app-roots") {
63
+ if (!argv[i + 1]) fail("--app-roots requires a value (colon-separated list of directories)");
64
+ cfg.appRoots = argv[++i].split(":").filter(Boolean);
65
+ } else if (a === "--ignore-dirs") {
66
+ if (!argv[i + 1]) fail("--ignore-dirs requires a value (colon-separated list of directory names)");
67
+ cfg.ignoreDirs = argv[++i].split(":").filter(Boolean);
68
+ } else if (a === "--verbose") {
69
+ cfg.verbose = true;
70
+ } 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.");
73
+ process.exit(0);
74
+ } else {
75
+ fail(`unknown argument: ${a} (see --help)`);
76
+ }
77
+ }
78
+ return cfg;
79
+ };
80
+
81
+ const resolveAgainst = (value, repoRoot) => {
82
+ return path.isAbsolute(value) ? value : path.resolve(repoRoot, value);
83
+ };
84
+
85
+ const relPosix = (repoRoot, abs) => {
86
+ return path.relative(repoRoot, abs).split(path.sep).join("/");
87
+ };
88
+
89
+ const collectFiles = (roots, repoRoot, shouldSkip, skipDirs, exts, ignoreDirs) => {
90
+ const files = [];
91
+ let count = 0;
92
+ for (const relRoot of roots) {
93
+ const rootDir = resolveAgainst(relRoot, repoRoot);
94
+ if (!fs.existsSync(rootDir)) continue;
95
+ for (const file of walk(rootDir, exts, ignoreDirs)) {
96
+ if (shouldSkip(file)) continue;
97
+ if (skipDirs && [...skipDirs].some((d) => file === d || file.startsWith(d + path.sep))) continue;
98
+ const rel = relPosix(repoRoot, file);
99
+ count += 1;
100
+ files.push({ file, rel });
101
+ }
102
+ }
103
+ return { files, count };
104
+ };
105
+
106
+ const parseComponents = (files, canonNames, config, role = "CANONICAL") => {
107
+ const comps = [];
108
+ for (const { file, rel } of files) {
109
+ let parsed;
110
+ let source;
111
+ try {
112
+ source = fs.readFileSync(file, "utf8");
113
+ parsed = parseComponentsViaEntrypoint(file, canonNames, config);
114
+ } catch (err) {
115
+ console.warn(`[component-uniqueness] could not parse ${rel}: ${err && err.message ? err.message : err}`);
116
+ continue;
117
+ }
118
+ for (const c of parsed) {
119
+ const candidate = buildCandidate(c, config);
120
+ comps.push({ ...candidate, path: rel });
121
+ }
122
+ }
123
+ return comps;
124
+ };
125
+
126
+ const matchPairs = (appComponents, canonComponents, config) => {
127
+ const canonNames = [...new Set(canonComponents.map((c) => c.name))];
128
+ const matches = [];
129
+ for (const app of appComponents) {
130
+ for (const canon of canonComponents) {
131
+ if (canon.path === app.path && canon.name === app.name) continue;
132
+ if (!canSeeCanon(app.path, canon.path, config.componentsFolder)) continue;
133
+ const signals = matchSignals(app, canon, { canonNames, frameworkMatcher });
134
+ const decision = decide(app, canon, { signals, weights: config.weights, thresholds: config.thresholds });
135
+ if (!decision.isDuplicate) continue;
136
+ matches.push({ app, canon, decision, tier: decision.tier, reason: decision.reason });
137
+ }
138
+ }
139
+ return matches;
140
+ };
141
+
142
+ const applyFilters = (matches) => {
143
+ const kept = [];
144
+ const dropped = [];
145
+ for (const match of matches) {
146
+ let hit = null;
147
+ for (const f of FILTERS) {
148
+ const reason = f.test(match);
149
+ if (reason) {
150
+ hit = { match, filter: f.name, reason };
151
+ break;
152
+ }
153
+ }
154
+ if (hit) dropped.push(hit);
155
+ else kept.push(match);
156
+ }
157
+ return { kept, dropped };
158
+ };
159
+
160
+ const collectRawHtml = (appFiles, canonComponents, config, canonNames) => {
161
+ if (!config.rawHtml) return [];
162
+ const rows = [];
163
+ for (const { file, rel } of appFiles) {
164
+ if (inComponentsFolder(rel, config.componentsFolder)) continue;
165
+ let elements;
166
+ try {
167
+ elements = parseElementsViaEntrypoint(file, canonNames, config);
168
+ } catch (err) {
169
+ console.warn(`[component-uniqueness] could not parse elements of ${rel}: ${err && err.message ? err.message : err}`);
170
+ continue;
171
+ }
172
+ for (const element of elements) {
173
+ const candidate = buildElementCandidate(element, config);
174
+ if (!candidate) continue;
175
+ const best = bestOf(matchPairs([{ ...candidate, path: rel }], canonComponents, config));
176
+ if (!best) continue;
177
+ rows.push({
178
+ tag: element.name,
179
+ path: rel,
180
+ line: element.line,
181
+ suggestion: { component: best.canon.name, path: best.canon.path },
182
+ confidence: best.decision.confidence,
183
+ reason: best.decision.reason,
184
+ });
185
+ }
186
+ }
187
+
188
+ return rows;
189
+ };
190
+
191
+ const SIZE_RATIO = 3;
192
+ const MIN_PART_CANON_NODES = 3;
193
+ const sizeCache = new WeakMap();
194
+
195
+ const nodeCount = (tree) => {
196
+ if (!tree) return 0;
197
+ const own = tree.tag === "fragment" || tree.tag === "children" ? 0 : 1;
198
+
199
+ return own + (tree.children || []).reduce((sum, child) => sum + nodeCount(child), 0);
200
+ };
201
+
202
+ const sizeOf = (item) => {
203
+ if (!sizeCache.has(item)) sizeCache.set(item, nodeCount(item.tree));
204
+
205
+ return sizeCache.get(item);
206
+ };
207
+
208
+ const tagBag = (tree, bag = new Map()) => {
209
+ if (!tree) return bag;
210
+ if (tree.tag !== "fragment" && tree.tag !== "children") bag.set(tree.tag, (bag.get(tree.tag) || 0) + 1);
211
+ for (const child of tree.children || []) tagBag(child, bag);
212
+
213
+ return bag;
214
+ };
215
+
216
+ const bagCache = new WeakMap();
217
+
218
+ const bagOf = (item) => {
219
+ if (!bagCache.has(item)) bagCache.set(item, tagBag(item.tree));
220
+
221
+ return bagCache.get(item);
222
+ };
223
+
224
+ const bagDice = (a, b) => {
225
+ let shared = 0;
226
+ let total = 0;
227
+ for (const n of a.values()) total += n;
228
+ for (const n of b.values()) total += n;
229
+ for (const [tag, n] of a) shared += Math.min(n, b.get(tag) || 0);
230
+
231
+ return total === 0 ? 0 : (2 * shared) / total;
232
+ };
233
+
234
+ const MIN_TAG_DICE = 0.5;
235
+
236
+ const comparableCanons = (part, canonComponents) => {
237
+ const partSize = sizeOf(part);
238
+ const partBag = bagOf(part);
239
+
240
+ return canonComponents.filter((canon) => {
241
+ const size = sizeOf(canon);
242
+
243
+ return size >= MIN_PART_CANON_NODES && size <= partSize * SIZE_RATIO && partSize <= size * SIZE_RATIO && bagDice(partBag, bagOf(canon)) >= MIN_TAG_DICE;
244
+ });
245
+ };
246
+
247
+ const largestParts = (found) => {
248
+ const sorted = [...found].sort((a, b) => b.part.endLine - b.part.line - (a.part.endLine - a.part.line));
249
+ const kept = [];
250
+ for (const item of sorted) {
251
+ const inside = kept.some((k) => k.best.canon.name === item.best.canon.name && k.part.line <= item.part.line && k.part.endLine >= item.part.endLine);
252
+ if (!inside) kept.push(item);
253
+ }
254
+
255
+ return kept.sort((a, b) => a.part.line - b.part.line);
256
+ };
257
+
258
+ const findParts = (file, rel, canonComponents, config, canonNames) => {
259
+ let parts;
260
+ try {
261
+ parts = parsePartsViaEntrypoint(file, canonNames, config);
262
+ } catch (err) {
263
+ console.warn(`[component-uniqueness] could not parse parts of ${rel}: ${err && err.message ? err.message : err}`);
264
+
265
+ return [];
266
+ }
267
+ const found = [];
268
+ for (const part of parts) {
269
+ const pool = comparableCanons(part, canonComponents);
270
+ if (pool.length === 0) continue;
271
+ const candidate = { ...buildCandidate(part, config), path: rel };
272
+ const { kept } = applyFilters(matchPairs([candidate], pool, config));
273
+ const best = bestOf(kept);
274
+ if (best) found.push({ part, best });
275
+ }
276
+
277
+ return largestParts(found);
278
+ };
279
+
280
+ const collectParts = (appFiles, canonComponents, config, canonNames) => {
281
+ if (!config.parts) return [];
282
+ const rows = [];
283
+ for (const { file, rel } of appFiles) {
284
+ for (const { part, best } of findParts(file, rel, canonComponents, config, canonNames)) {
285
+ rows.push({
286
+ owner: part.owner,
287
+ tag: part.rootTag,
288
+ path: rel,
289
+ line: part.line,
290
+ endLine: part.endLine,
291
+ suggestion: { component: best.canon.name, path: best.canon.path },
292
+ confidence: best.decision.confidence,
293
+ reason: best.decision.reason,
294
+ });
295
+ }
296
+ }
297
+
298
+ return rows;
299
+ };
300
+
301
+ const stageLog = (enabled) => {
302
+ const started = Date.now();
303
+
304
+ return (label) => {
305
+ if (!enabled) return;
306
+ if (global.gc) global.gc();
307
+ console.log(`[component-uniqueness] ${label}: ${((Date.now() - started) / 1000).toFixed(1)}s, heap ${Math.round(process.memoryUsage().heapUsed / 1048576)} MB`);
308
+ };
309
+ };
310
+
311
+ const buildComponentReport = async (args, repoRoot, roots, shouldSkip, config, registry, catalogComponents) => {
312
+ const exts = config.exts || DEFAULT_EXTS;
313
+ const ignoreDirs = config.ignoreDirs;
314
+ const stage = stageLog(args.verbose);
315
+
316
+ const shouldSkipCanon = (abs) => isIgnored(relPosix(repoRoot, abs), [], config.exclude);
317
+ const canonFiles = collectFiles(roots, repoRoot, shouldSkipCanon, null, exts, ignoreDirs).files;
318
+ const canonComponents = parseComponents(canonFiles, null, config);
319
+ const canonNames = new Set(canonComponents.map((c) => c.name));
320
+ const uniqueCanon = parseComponents(canonFiles, canonNames, config);
321
+ stage(`canonical parsed (${uniqueCanon.length})`);
322
+
323
+ const appShouldSkip = (abs) => {
324
+ const rel = relPosix(repoRoot, abs);
325
+
326
+ return isIgnored(rel, inComponentsFolder(rel, config.componentsFolder) ? [] : config.include, config.exclude);
327
+ };
328
+ const appFiles = collectFiles(args.appRoots || ["."], repoRoot, appShouldSkip, null, exts, ignoreDirs);
329
+ const appComponents = parseComponents(appFiles.files, canonNames, config, "CANDIDATE");
330
+ stage(`app parsed (${appComponents.length})`);
331
+
332
+ const matches = matchPairs(appComponents, uniqueCanon, config);
333
+ const { kept, dropped } = applyFilters(matches);
334
+ stage("components matched");
335
+ const rawHtml = collectRawHtml(appFiles.files, uniqueCanon, config, canonNames);
336
+ stage("raw html done");
337
+ const parts = collectParts(appFiles.files, uniqueCanon, config, canonNames);
338
+ stage("parts done");
339
+
340
+ return {
341
+ matches: kept,
342
+ dropped,
343
+ rawHtml,
344
+ parts,
345
+ layerFolders: config.componentsFolder,
346
+ files: appFiles.count,
347
+ canonCount: uniqueCanon.length,
348
+ appCount: appComponents.length,
349
+ };
350
+ };
351
+
352
+ const main = async () => {
353
+ const args = parseArgs(process.argv.slice(2));
354
+ const cwd = process.cwd();
355
+
356
+ const loaded = args.roots ? null : await loadRuleOptions(cwd);
357
+ const configOptions = loaded ? { ...loaded.options } : {};
358
+ if (loaded) {
359
+ console.log(`[component-uniqueness] config from ${loaded.source}`);
360
+ }
361
+ if (args.ignoreDirs) {
362
+ const base = Array.isArray(configOptions.ignoreDirs) ? configOptions.ignoreDirs : [];
363
+ configOptions.ignoreDirs = [...new Set([...base, ...args.ignoreDirs])];
364
+ }
365
+
366
+ const config = normalizeOptions(configOptions);
367
+ await require("./playgrounds/style-entrypoint.js").whenReady(config);
368
+ const rootMarkers = config.rootMarkers;
369
+ const repoRoot = args.repoRoot ? path.resolve(cwd, args.repoRoot) : findRepoRoot(cwd, rootMarkers) || cwd;
370
+
371
+ const configRoots = (config.componentsFolder || []).map((d) => String(d).replace(/\\/g, "/").replace(/\/+$/, ""));
372
+ const roots = args.roots || configRoots;
373
+ if (!roots || roots.length === 0) {
374
+ fail("no scan roots: pass --roots <dir1>:<dir2> or set componentsFolder in the rule options (eslint.config.js / component-uniqueness.config.js)");
375
+ }
376
+
377
+ const outPath = resolveAgainst(args.out || config.catalogPath, repoRoot);
378
+ const registry = args.registry ? loadRegistry({ ...config, registry: null, registryPath: args.registry }) : loadRegistry(config);
379
+ const catalogComponents = ((loadCatalog(config) || {}).components) || [];
380
+
381
+ const include = config.include;
382
+ const exclude = config.exclude;
383
+ const shouldSkip = (abs) => isIgnored(relPosix(repoRoot, abs), include, exclude);
384
+ const exts = config.exts;
385
+ const ignoreDirs = config.ignoreDirs;
386
+
387
+ const shouldSkipCanon = (abs) => isIgnored(relPosix(repoRoot, abs), [], config.exclude);
388
+ const canonFiles = collectFiles(roots, repoRoot, shouldSkipCanon, null, exts, ignoreDirs).files;
389
+ const canonComponents = parseComponents(canonFiles, null, config);
390
+ const canonNames = new Set(canonComponents.map((c) => c.name));
391
+ const final = parseComponents(canonFiles, canonNames, config);
392
+
393
+ if (args.check) {
394
+ let current = null;
395
+ try {
396
+ current = JSON.parse(fs.readFileSync(outPath, "utf8"));
397
+ } catch {}
398
+ const same = current && JSON.stringify(current.components || []) === JSON.stringify(final);
399
+ if (!same) {
400
+ fail(`catalog is out of date (${final.length} component(s) expected at ${path.relative(repoRoot, outPath)}); regenerate it (node main.js)`);
401
+ }
402
+ console.log(`[component-uniqueness] catalog up to date (${final.length} component(s))`);
403
+ return;
404
+ }
405
+
406
+ writeCatalog(outPath, final);
407
+ const tagCount = new Set(final.map((c) => (c.rootTags || [])[0]).filter(Boolean)).size;
408
+ console.log(`[component-uniqueness] wrote ${path.relative(repoRoot, outPath)} (${final.length} component(s), ${tagCount} root tag(s), ${canonFiles.length} file(s) scanned)`);
409
+
410
+ if (args.report) {
411
+ const reportPath = path.isAbsolute(args.report) ? args.report : path.resolve(process.cwd(), args.report);
412
+ const comp = await buildComponentReport(args, repoRoot, roots, shouldSkip, config, registry, catalogComponents);
413
+ fs.mkdirSync(path.dirname(reportPath), { recursive: true });
414
+ fs.writeFileSync(reportPath, renderComponentReport(comp, args.verbose));
415
+ 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
+ }
417
+ };
418
+
419
+ if (require.main === module) {
420
+ main().catch((err) => {
421
+ fail(err && err.message ? err.message : String(err));
422
+ });
423
+ }
424
+
425
+ module.exports = {
426
+ buildCandidate,
427
+ parseComponents,
428
+ matchPairs,
429
+ applyFilters,
430
+ collectRawHtml,
431
+ findParts,
432
+ frameworkMatcher,
433
+ };
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+
3
+
4
+ const TEST_ID_WEIGHT = 0.5;
5
+
6
+ const parseToken = (token) => {
7
+ const t = String(token || "").toLowerCase();
8
+ const m = t.match(/^(role|aria-[\w-]+)(?::(.*))?$/);
9
+ if (m) return { name: m[1], value: m[2] || "" };
10
+ return null;
11
+ };
12
+
13
+ const classify = (token) => {
14
+ const t = String(token || "").toLowerCase();
15
+ if (t.startsWith("data-test") || t.startsWith("data-testid") || t.startsWith("data-test-id")) return "testid";
16
+ const p = parseToken(t);
17
+ if (p) return "a11y";
18
+ return null;
19
+ };
20
+
21
+ const tokensOf = (c, kind) => {
22
+ const s = new Set();
23
+ for (const t of c.a11y || []) {
24
+ if (classify(t) === kind) s.add(String(t).toLowerCase());
25
+ }
26
+ return s;
27
+ };
28
+
29
+ const jaccard = (a, b) => {
30
+ if (a.size === 0 || b.size === 0) return 0;
31
+ let inter = 0;
32
+ for (const t of a) if (b.has(t)) inter += 1;
33
+ const union = a.size + b.size - inter;
34
+ return union === 0 ? 0 : inter / union;
35
+ };
36
+
37
+ const matchA11y = (candidate, canon) => {
38
+ const candA = tokensOf(candidate, "a11y");
39
+ const canonA = tokensOf(canon, "a11y");
40
+ const candT = tokensOf(candidate, "testid");
41
+ const canonT = tokensOf(canon, "testid");
42
+
43
+ const a11ySim = jaccard(candA, canonA);
44
+ const testSim = jaccard(candT, canonT);
45
+
46
+ const parts = [];
47
+ if (candA.size > 0 || canonA.size > 0) parts.push({ w: 1 - TEST_ID_WEIGHT, v: a11ySim });
48
+ if (candT.size > 0 || canonT.size > 0) parts.push({ w: TEST_ID_WEIGHT, v: testSim });
49
+
50
+ const totalW = parts.reduce((s, p) => s + p.w, 0);
51
+ const score = totalW === 0 ? 0 : parts.reduce((s, p) => s + p.w * p.v, 0) / totalW;
52
+
53
+ const evidence = {
54
+ candidateA11y: [...candA].sort(),
55
+ canonicalA11y: [...canonA].sort(),
56
+ candidateTestId: [...candT].sort(),
57
+ canonicalTestId: [...canonT].sort(),
58
+ a11ySimilarity: a11ySim,
59
+ testIdSimilarity: testSim,
60
+ };
61
+
62
+ return { score, evidence };
63
+ };
64
+
65
+ module.exports = { matchA11y, tokensOf, classify, TEST_ID_WEIGHT };
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+
3
+
4
+ const jaccard = (a, b) => {
5
+ if (a.size === 0 || b.size === 0) return 0;
6
+ let inter = 0;
7
+ for (const t of a) if (b.has(t)) inter += 1;
8
+ const union = a.size + b.size - inter;
9
+ return union === 0 ? 0 : inter / union;
10
+ };
11
+
12
+ const matchBehavior = (candidate, canon) => {
13
+ const candA = new Set((candidate.framework && candidate.framework.events) || []);
14
+ const canonA = new Set((canon.framework && canon.framework.events) || []);
15
+ const shared = new Set([...candA].filter((event) => canonA.has(event)));
16
+ const score = jaccard(candA, canonA);
17
+ return {
18
+ score,
19
+ evidence: {
20
+ candidateEvents: [...candA].sort(),
21
+ canonicalEvents: [...canonA].sort(),
22
+ sharedEvents: [...shared].sort(),
23
+ },
24
+ };
25
+ };;
26
+
27
+ module.exports = { matchBehavior };