@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.
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+
3
+ const resolveClasses = (classes) => {
4
+ return { css: {}, unresolved: [...(classes || [])] };
5
+ };
6
+
7
+ module.exports = { resolveClasses, available: () => false };
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ const { normalizeOptions } = require("../config.js");
4
+ const { cssTextToStyles, styleObjectToText, mergeProfiles } = require("../normalize/style.js");
5
+
6
+ const PLAYGROUNDS = {
7
+ tailwind: () => require("./tailwind.js"),
8
+ scss: () => require("./scss.js"),
9
+ "styled-components": () => require("./styled-components.js"),
10
+ styled: () => require("./styled-components.js"),
11
+ };
12
+
13
+ const cache = new Map();
14
+
15
+ const getPlayground = (styleSystem) => {
16
+ const key = String(styleSystem || "tailwind").toLowerCase();
17
+ if (!cache.has(key)) {
18
+ const loader = PLAYGROUNDS[key] || PLAYGROUNDS.tailwind;
19
+ cache.set(key, loader());
20
+ }
21
+ return cache.get(key);
22
+ };
23
+
24
+ const getStyleSystem = (opts) => normalizeOptions(opts).styleSystem;
25
+
26
+ const normalizeStyles = async (className, styleObj, opts, label) => {
27
+ const pg = getPlayground(getStyleSystem(opts));
28
+ const parts = [];
29
+ if (typeof className === "string" && className.trim()) {
30
+ const tw = await pg.resolveClasses(className.trim().split(/\s+/));
31
+ parts.push(tw);
32
+ }
33
+ if (styleObj && typeof styleObj === "object") {
34
+ parts.push(cssTextToStyles(styleObjectToText(styleObj)));
35
+ }
36
+ if (parts.length === 0) return { css: {}, unresolved: [] };
37
+ const merged = parts.reduce(mergeProfiles, { css: {}, unresolved: [] });
38
+ return { css: merged.css, unresolved: merged.unresolved };
39
+ };
40
+
41
+ const normalizeStylesSync = (className, styleObj, opts, label) => {
42
+ const pg = getPlayground(getStyleSystem(opts));
43
+ const parts = [];
44
+ if (typeof className === "string" && className.trim()) {
45
+ const tw = pg.resolveClassesSync(className.trim().split(/\s+/));
46
+ parts.push(tw);
47
+ }
48
+ if (styleObj && typeof styleObj === "object") {
49
+ parts.push(cssTextToStyles(styleObjectToText(styleObj)));
50
+ }
51
+ if (parts.length === 0) return { css: {}, unresolved: [] };
52
+ const merged = parts.reduce(mergeProfiles, { css: {}, unresolved: [] });
53
+ return { css: merged.css, unresolved: merged.unresolved };
54
+ };
55
+
56
+ const escapeClass = (cls) => cls.replace(/[^a-zA-Z0-9_-]/g, (c) => `\\${c}`);
57
+
58
+ const buildStylesheet = (classes, opts) => {
59
+ const pg = getPlayground(getStyleSystem(opts));
60
+ if (!pg.classStyles) return "";
61
+ const { byClass } = pg.classStyles(classes);
62
+ const rules = [];
63
+ for (const [cls, decls] of Object.entries(byClass)) {
64
+ if (cls.includes(":")) continue;
65
+ const body = Object.entries(decls)
66
+ .map(([prop, values]) => `${prop}:${values[values.length - 1]}`)
67
+ .join(";");
68
+ rules.push(`.${escapeClass(cls)}{${body}}`);
69
+ }
70
+ return rules.join("\n");
71
+ };
72
+
73
+ const whenReady = async (opts) => {
74
+ const pg = getPlayground(getStyleSystem(opts));
75
+ if (pg.ready) await pg.ready;
76
+ };
77
+
78
+ module.exports = { normalizeStyles, normalizeStylesSync, getStyleSystem, getPlayground, buildStylesheet, whenReady };
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+
3
+ const resolveClasses = (classes) => {
4
+ return { css: {}, unresolved: [...(classes || [])] };
5
+ };
6
+
7
+ module.exports = { resolveClasses, available: () => false };
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+
6
+ let compiled = null;
7
+ let failed = false;
8
+ let designSystem = null;
9
+ const ready = Promise.resolve()
10
+ .then(() => require("tailwindcss").__unstable__loadDesignSystem("@import \"tailwindcss\";", {
11
+ from: path.join(__dirname, "probe.css"),
12
+ loadStylesheet: (id, base) => {
13
+ if (id === "tailwindcss") {
14
+ const cssPath = require.resolve("tailwindcss/index.css");
15
+ return { path: cssPath, base: path.dirname(cssPath), content: fs.readFileSync(cssPath, "utf8") };
16
+ }
17
+ return { path: id, base: base || "", content: "" };
18
+ },
19
+ }))
20
+ .then((ds) => {
21
+ designSystem = ds;
22
+ })
23
+ .catch(() => {});
24
+
25
+ const compileOnce = async () => {
26
+ if (compiled) return compiled;
27
+ if (failed) return null;
28
+ try {
29
+ const { compile } = require("tailwindcss");
30
+ const cssPath = require.resolve("tailwindcss/index.css");
31
+ compiled = await compile("@import \"tailwindcss\";", {
32
+ from: path.join(__dirname, "probe.css"),
33
+ loadStylesheet: async (id, base) => {
34
+ if (id === "tailwindcss") {
35
+ return { path: cssPath, base: path.dirname(cssPath), content: fs.readFileSync(cssPath, "utf8") };
36
+ }
37
+ return { path: id, base: base || "", content: "" };
38
+ },
39
+ });
40
+ return compiled;
41
+ } catch {
42
+ failed = true;
43
+ return null;
44
+ }
45
+ };
46
+
47
+ const extractClass = (sel) => {
48
+ if (sel.startsWith(".")) sel = sel.slice(1);
49
+ let name = "";
50
+ for (let i = 0; i < sel.length; i++) {
51
+ const ch = sel[i];
52
+ if (ch === "\\") {
53
+ name += sel[i + 1] ?? "";
54
+ i++;
55
+ continue;
56
+ }
57
+ if (ch === ":" || ch === " " || ch === "," || ch === "[" || ch === "{" || ch === ".") break;
58
+ name += ch;
59
+ }
60
+ return name;
61
+ };
62
+
63
+ const parseCss = (css) => {
64
+ const vars = new Map();
65
+ for (const m of css.matchAll(/--([a-z0-9-]+)\s*:\s*([^;{}]+);/g)) vars.set(m[1], m[2].trim());
66
+ const map = {};
67
+ const layerIdx = css.indexOf("@layer utilities");
68
+ const layer = layerIdx >= 0 ? css.slice(layerIdx) : css;
69
+ const ruleRe = /([.#][^{]+)\{([^{}]*)\}/g;
70
+ let m;
71
+ while ((m = ruleRe.exec(layer))) {
72
+ const sel = m[1].trim();
73
+ if (!sel.startsWith(".")) continue;
74
+ const cls = extractClass(sel);
75
+ if (!cls) continue;
76
+ const styles = {};
77
+ for (const d of m[2].split(";")) {
78
+ const idx = d.indexOf(":");
79
+ if (idx < 0) continue;
80
+ const prop = d.slice(0, idx).trim().toLowerCase();
81
+ let value = d.slice(idx + 1).trim();
82
+ if (!prop || !value) continue;
83
+ if (value.startsWith("var(")) {
84
+ const vm = value.match(/^var\(\s*--([a-z0-9-]+)/);
85
+ if (vm && vars.has(vm[1])) value = vars.get(vm[1]);
86
+ }
87
+ if (!Object.prototype.hasOwnProperty.call(styles, prop)) styles[prop] = [];
88
+ if (!styles[prop].includes(value)) styles[prop].push(value);
89
+ }
90
+ const pairs = Object.entries(styles).map(([prop, values]) => [prop, values.join(" ")]);
91
+ if (pairs.length > 0) map[cls] = pairs;
92
+ }
93
+ return map;
94
+ };
95
+
96
+ const resolveClasses = async (classes) => {
97
+ const list = [...new Set(classes || [])];
98
+ const out = await compileOnce();
99
+ if (!out) return { css: {}, unresolved: list };
100
+ const cssText = await out.build(list);
101
+ const map = parseCss(cssText);
102
+ const css = {};
103
+ const unresolved = [];
104
+ for (const cls of list) {
105
+ const pairs = map[cls];
106
+ if (pairs && pairs.length > 0) {
107
+ for (const [prop, value] of pairs) {
108
+ css[prop] = css[prop] || [];
109
+ if (!css[prop].includes(value)) css[prop].push(value);
110
+ }
111
+ } else {
112
+ unresolved.push(cls);
113
+ }
114
+ }
115
+ return { css, unresolved };
116
+ };
117
+
118
+ const parseBlock = (block, vars, styles) => {
119
+ const ruleRe = /([.#][^{]+)\{([^{}]*)\}/g;
120
+ let m;
121
+ while ((m = ruleRe.exec(block))) {
122
+ const sel = m[1].trim();
123
+ if (!sel.startsWith(".")) continue;
124
+ const cls = extractClass(sel);
125
+ if (!cls) continue;
126
+ for (const d of m[2].split(";")) {
127
+ const idx = d.indexOf(":");
128
+ if (idx < 0) continue;
129
+ const prop = d.slice(0, idx).trim().toLowerCase();
130
+ let value = d.slice(idx + 1).trim();
131
+ if (!prop || !value) continue;
132
+ if (value.startsWith("var(")) {
133
+ const vm = value.match(/^var\(\s*--([a-z0-9-]+)/);
134
+ if (vm && vars.has(vm[1])) value = vars.get(vm[1]);
135
+ }
136
+ if (!Object.prototype.hasOwnProperty.call(styles, cls)) styles[cls] = {};
137
+ if (!Object.prototype.hasOwnProperty.call(styles[cls], prop)) styles[cls][prop] = [];
138
+ if (!styles[cls][prop].includes(value)) styles[cls][prop].push(value);
139
+ }
140
+ const inner = m[2];
141
+ if (inner.includes("{")) parseBlock(inner, vars, styles);
142
+ }
143
+ };
144
+
145
+ const substituteVars = (value, depth = 0) =>
146
+ value.replace(/var\(--([a-z0-9-]+)\)/g, (match, name) => {
147
+ if (depth >= 4) return match;
148
+ const resolved = designSystem.theme.resolve(null, [`--${name}`]);
149
+ return resolved && String(resolved) !== match ? substituteVars(String(resolved), depth + 1) : match;
150
+ });
151
+
152
+ const classStyles = (classes) => {
153
+ const list = [...new Set(classes || [])];
154
+ if (!designSystem) return { byClass: {}, unresolved: list };
155
+ const out = designSystem.candidatesToCss(list);
156
+ const vars = new Map();
157
+ for (const m of String(out).matchAll(/--([a-z0-9-]+)\s*:\s*([^;{}]+);/g)) vars.set(m[1], m[2].trim());
158
+ const styles = {};
159
+ for (const b of out) if (typeof b === "string") parseBlock(b, vars, styles);
160
+ const byClass = {};
161
+ const unresolved = [];
162
+ for (const cls of list) {
163
+ const decls = styles[cls];
164
+ if (decls && Object.keys(decls).length > 0) {
165
+ byClass[cls] = Object.fromEntries(Object.entries(decls).map(([prop, values]) => [prop, values.map((value) => substituteVars(value))]));
166
+ } else {
167
+ unresolved.push(cls);
168
+ }
169
+ }
170
+ return { byClass, unresolved };
171
+ };
172
+
173
+ const resolveClassesSync = (classes) => {
174
+ const { byClass, unresolved } = classStyles(classes);
175
+ const css = {};
176
+ for (const decls of Object.values(byClass)) {
177
+ for (const [prop, values] of Object.entries(decls)) {
178
+ css[prop] = css[prop] || [];
179
+ const joined = values.join(" ");
180
+ if (!css[prop].includes(joined)) css[prop].push(joined);
181
+ }
182
+ }
183
+ return { css, unresolved };
184
+ };
185
+
186
+ module.exports = { resolveClasses, resolveClassesSync, classStyles, ready, available: () => true };
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ const parseComponents = () => [];
4
+
5
+ const resolveCss = () => ({ css: "", unresolved: [] });
6
+
7
+ module.exports = {
8
+ parseComponents,
9
+ resolveCss,
10
+ available: () => false,
11
+ };
package/plugin.js ADDED
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+
3
+ const rule = require("./index");
4
+ const pkg = require("./package.json");
5
+
6
+ module.exports = {
7
+ meta: {
8
+ name: pkg.name,
9
+ version: pkg.version,
10
+ },
11
+ rules: {
12
+ "duplicate-component": rule,
13
+ },
14
+ };
package/report.js ADDED
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+
3
+ const TIERS = ["duplicate", "similar"];
4
+
5
+ const TIER_LABEL = {
6
+ duplicate: "Duplicate (confidence ≥ threshold)",
7
+ similar: "Similar (below duplicate threshold)",
8
+ };
9
+
10
+ const duplicateText = (match) => {
11
+ const d = match.decision;
12
+ return `Component \`${match.app.name}\` duplicates canonical \`${match.canon.name}\` (${match.canon.path}) — ${d.reason}. Use the canonical component instead.`;
13
+ };
14
+
15
+ const rawHtmlText = (tag, suggestion) => {
16
+ return `Raw <${tag}> outside the canonical packages → replace with \`${suggestion.component}\` from ${suggestion.path}.`;
17
+ };
18
+
19
+ const renderHeader = (comp) => {
20
+ const lines = [];
21
+ lines.push("# Component duplicates (component-level funnel)");
22
+ lines.push("");
23
+ lines.push(`Scanned ${comp.files} app file(s), ${comp.appCount} app component(s) against ${comp.canonCount} canonical component(s).`);
24
+ lines.push(`Found ${comp.matches.length} duplicate component(s)${comp.dropped && comp.dropped.length > 0 ? ` (after filtering out ${comp.dropped.length} match(es))` : ""}.`);
25
+ lines.push("");
26
+ return lines;
27
+ };
28
+
29
+ const renderTierSection = (tier, rows, title = TIER_LABEL[tier]) => {
30
+ const lines = [];
31
+ lines.push(`## ${title} (${rows.length})`);
32
+ lines.push("");
33
+ lines.push("| Local component | Location | Duplicates canonical | Canonical location | Confidence | Why |");
34
+ lines.push("| --- | --- | --- | --- | --- | --- |");
35
+ const sorted = [...rows].sort((a, b) => b.decision.confidence - a.decision.confidence || a.canon.name.localeCompare(b.canon.name));
36
+ for (const m of sorted) {
37
+ lines.push(`| ${m.app.name} | \`${m.app.path}:${m.app.line}\` | ${m.canon.name} | \`${m.canon.path}\` | ${m.decision.confidence.toFixed(2)} | ${m.decision.reason} |`);
38
+ }
39
+ lines.push("");
40
+ return lines;
41
+ };
42
+
43
+ const renderRawHtmlSection = (rows) => {
44
+ if (rows.length === 0) return [];
45
+ const lines = [];
46
+ lines.push(`## Raw HTML outside canonical packages (${rows.length})`);
47
+ lines.push("");
48
+ lines.push("| Element | Location | Replace with | From | Why |");
49
+ lines.push("| --- | --- | --- | --- | --- |");
50
+ const sorted = [...rows].sort((a, b) => a.path.localeCompare(b.path));
51
+ for (const r of sorted) {
52
+ lines.push(`| <${r.tag}> | \`${r.path}:${r.line}\` | \`${r.suggestion.component}\` | ${r.suggestion.path} | ${r.reason} |`);
53
+ }
54
+ lines.push("");
55
+ return lines;
56
+ };
57
+
58
+ const renderPartsSection = (rows, title = "Parts of components that duplicate a canonical") => {
59
+ if (rows.length === 0) return [];
60
+ const lines = [];
61
+ lines.push(`## ${title} (${rows.length})`);
62
+ lines.push("");
63
+ lines.push("| Part | Location | Replace with | From | Why |");
64
+ lines.push("| --- | --- | --- | --- | --- |");
65
+ const sorted = [...rows].sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
66
+ for (const r of sorted) {
67
+ lines.push(`| ${r.owner} \u203a <${r.tag}> | \`${r.path}:${r.line}-${r.endLine}\` | \`${r.suggestion.component}\` | ${r.suggestion.path} | ${r.reason} |`);
68
+ }
69
+ lines.push("");
70
+ return lines;
71
+ };
72
+
73
+ const renderFilteredSection = (dropped) => {
74
+ const lines = [];
75
+ const byFilter = new Map();
76
+ for (const d of dropped) {
77
+ if (!byFilter.has(d.filter)) byFilter.set(d.filter, []);
78
+ byFilter.get(d.filter).push(d);
79
+ }
80
+ for (const [filter, rows] of byFilter) {
81
+ lines.push(`## Filtered out by \`${filter}\` (${rows.length})`);
82
+ lines.push("");
83
+ lines.push("| Local component | Location | Canonical | Why dropped |");
84
+ lines.push("| --- | --- | --- | --- |");
85
+ const sorted = [...rows].sort((a, b) => a.match.canon.name.localeCompare(b.match.canon.name));
86
+ for (const d of sorted) {
87
+ lines.push(`| ${d.match.app.name} | \`${d.match.app.path}:${d.match.app.line}\` | ${d.match.canon.name} | ${d.reason} |`);
88
+ }
89
+ lines.push("");
90
+ }
91
+ return lines;
92
+ };
93
+
94
+ const renderComponentReport = (comp, verbose) => {
95
+ const lines = [];
96
+ const folders = comp.layerFolders || [];
97
+ const inLayer = (p) => folders.some((d) => p.startsWith(d));
98
+ const appMatches = comp.matches.filter((m) => !inLayer(m.app.path));
99
+ const layerMatches = comp.matches.filter((m) => inLayer(m.app.path));
100
+ const appParts = (comp.parts || []).filter((r) => !inLayer(r.path));
101
+ const layerParts = (comp.parts || []).filter((r) => inLayer(r.path));
102
+ lines.push(...renderHeader(comp));
103
+ for (const tier of TIERS) {
104
+ const rows = appMatches.filter((m) => m.decision.tier === tier);
105
+ if (rows.length === 0) continue;
106
+ lines.push(...renderTierSection(tier, rows));
107
+ }
108
+ if (comp.rawHtml && comp.rawHtml.length > 0) lines.push(...renderRawHtmlSection(comp.rawHtml));
109
+ lines.push(...renderPartsSection(appParts));
110
+ for (const tier of TIERS) {
111
+ const rows = layerMatches.filter((m) => m.decision.tier === tier);
112
+ if (rows.length === 0) continue;
113
+ lines.push(...renderTierSection(tier, rows, `Inside canonical layers: ${TIER_LABEL[tier]}`));
114
+ }
115
+ lines.push(...renderPartsSection(layerParts, "Inside canonical layers: parts that duplicate a lower layer"));
116
+ if (verbose && comp.dropped && comp.dropped.length > 0) lines.push(...renderFilteredSection(comp.dropped));
117
+ return lines.join("\n");
118
+ };
119
+
120
+ module.exports = {
121
+ renderComponentReport,
122
+ duplicateText,
123
+ rawHtmlText,
124
+ TIERS,
125
+ TIER_LABEL,
126
+ };
package/utils.js ADDED
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { DEFAULT_EXTS, DEFAULT_IGNORE_DIRS } = require("./config");
6
+
7
+ const walk = (dir, exts = DEFAULT_EXTS, ignoreDirs = DEFAULT_IGNORE_DIRS) => {
8
+ const extSet = new Set(exts);
9
+ const ignoreSet = new Set(ignoreDirs);
10
+ const out = [];
11
+ const visit = (d) => {
12
+ let list;
13
+ try {
14
+ list = fs.readdirSync(d, { withFileTypes: true });
15
+ } catch {
16
+ return;
17
+ }
18
+ for (const entry of list) {
19
+ if (entry.name.startsWith(".") || ignoreSet.has(entry.name)) continue;
20
+ const full = path.join(d, entry.name);
21
+ if (entry.isDirectory()) {
22
+ visit(full);
23
+ } else if ([...extSet].some((e) => entry.name.endsWith(e))) {
24
+ out.push(full);
25
+ }
26
+ }
27
+ };
28
+ visit(dir);
29
+ return out;
30
+ };
31
+
32
+ const dedupeAndSort = (components) => {
33
+ const seen = new Set();
34
+ const out = [];
35
+ for (const c of components) {
36
+ const key = JSON.stringify({ n: c.name, ...c });
37
+ if (seen.has(key)) continue;
38
+ seen.add(key);
39
+ out.push(c);
40
+ }
41
+ out.sort((a, b) => (a.name + a.tag + a.path).localeCompare(b.name + b.tag + b.path));
42
+ return out;
43
+ };
44
+
45
+ const writeCatalog = (outPath, components) => {
46
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
47
+ fs.writeFileSync(outPath, JSON.stringify({ generatedAt: new Date().toISOString(), components }, null, 2) + "\n", "utf8");
48
+ };
49
+
50
+ const buildDirNameMap = (repoRoot, registryPath) => {
51
+ const map = new Map();
52
+ const regPath = registryPath || path.join(repoRoot, "reports", "component-registry.json");
53
+ if (!fs.existsSync(regPath)) return map;
54
+ try {
55
+ const reg = JSON.parse(fs.readFileSync(regPath, "utf8"));
56
+ for (const [name, dirs] of Object.entries((reg && reg.names) || {})) {
57
+ for (const d of dirs) {
58
+ if (!map.has(d)) map.set(d, name);
59
+ }
60
+ }
61
+ } catch {}
62
+ return map;
63
+ };
64
+
65
+ const componentNameFor = (fileAbs, repoRoot, dirNameMap) => {
66
+ const dir = path.dirname(fileAbs);
67
+ let name = path.basename(fileAbs).replace(/\.[^.]+$/, "");
68
+ const isFileScoped = /^(index|styles|types|constants|utils|hooks|test|stories)$/i.test(name);
69
+ let up = dir;
70
+ if (/^[A-Z][A-Za-z0-9]*$/.test(path.basename(dir)) && isFileScoped) {
71
+ name = path.basename(dir);
72
+ } else {
73
+ for (let i = 0; i < 4; i += 1) {
74
+ const parent = path.dirname(up);
75
+ if (parent === up) break;
76
+ const bn = path.basename(parent);
77
+ if (/^[A-Z][A-Za-z0-9]*$/.test(bn)) {
78
+ up = parent;
79
+ if (isFileScoped) name = bn;
80
+ break;
81
+ }
82
+ up = parent;
83
+ }
84
+ }
85
+ const relDir = path.relative(repoRoot, dir).split(path.sep).join("/");
86
+ const relUp = path.relative(repoRoot, up).split(path.sep).join("/");
87
+ const regName = dirNameMap.get(relDir) || dirNameMap.get(relUp);
88
+ if (regName) name = regName;
89
+ return name;
90
+ };
91
+
92
+ module.exports = { walk, dedupeAndSort, writeCatalog, buildDirNameMap, componentNameFor };