@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/README.md +149 -0
- package/config.js +337 -0
- package/decision-maker.js +113 -0
- package/filter/drop-child-element.js +13 -0
- package/filter/drop-usages.js +10 -0
- package/index.js +178 -0
- package/main.js +433 -0
- package/matcher/a11y.js +65 -0
- package/matcher/behavior.js +27 -0
- package/matcher/framework/index.js +15 -0
- package/matcher/framework/react.js +25 -0
- package/matcher/index.js +36 -0
- package/matcher/name.js +115 -0
- package/matcher/structure.js +168 -0
- package/normalize/candidate.js +20 -0
- package/normalize/dom.js +165 -0
- package/normalize/framework.js +100 -0
- package/normalize/style.js +174 -0
- package/package.json +61 -0
- package/playgrounds/angular.js +11 -0
- package/playgrounds/framework-entrypoint.js +71 -0
- package/playgrounds/react.js +928 -0
- package/playgrounds/scss.js +7 -0
- package/playgrounds/style-entrypoint.js +78 -0
- package/playgrounds/styled-components.js +7 -0
- package/playgrounds/tailwind.js +186 -0
- package/playgrounds/vue.js +11 -0
- package/plugin.js +14 -0
- package/report.js +126 -0
- package/utils.js +92 -0
package/README.md
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# @md-code/component-uniqueness
|
|
2
|
+
|
|
3
|
+
ESLint rule + CLI scanner that finds **duplicate components** in your app code by comparing them against your canonical component library. Cross-framework: React today, the same signature model is designed to carry over to Vue and Angular.
|
|
4
|
+
|
|
5
|
+
## How it works
|
|
6
|
+
|
|
7
|
+
```mermaid
|
|
8
|
+
flowchart TD
|
|
9
|
+
A["Canonical components<br/>(walk folders, extract signatures)"] --> B[("catalog.json")]
|
|
10
|
+
A --> CD["canon-dup<br/>canonicals matched against each other (strict thresholds)<br/>duplicates dropped → unique canonical set"]
|
|
11
|
+
CD --> A
|
|
12
|
+
C["App code<br/>(every JSX element)"] --> D
|
|
13
|
+
|
|
14
|
+
subgraph match["Match (4 matchers in parallel)"]
|
|
15
|
+
D --> M1["name<br/>same or fuzzy name"]
|
|
16
|
+
D --> M2["structural<br/>shared class tokens"]
|
|
17
|
+
D --> M3["family<br/>token-profile cluster"]
|
|
18
|
+
D --> M4["jsx-block<br/>subtree contains canonical"]
|
|
19
|
+
B --> M1
|
|
20
|
+
B --> M2
|
|
21
|
+
B --> M3
|
|
22
|
+
B --> M4
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
M1 --> F1
|
|
26
|
+
M2 --> F1
|
|
27
|
+
M3 --> F1
|
|
28
|
+
M4 --> F1
|
|
29
|
+
|
|
30
|
+
subgraph filter["Filter"]
|
|
31
|
+
F1["drop-usages<br/>app already imports the canonical"]
|
|
32
|
+
F1 --> F2["drop-child-element<br/>match is on a child, not the root"]
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
F2 --> E["report.md<br/>Markdown funnel of duplicates"]
|
|
36
|
+
CD -. "own section" .-> E
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quick start
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
bun add -D @md-code/component-uniqueness
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```js
|
|
46
|
+
// eslint.config.js
|
|
47
|
+
const uniqueness = require("@md-code/component-uniqueness/plugin");
|
|
48
|
+
|
|
49
|
+
module.exports = [
|
|
50
|
+
{
|
|
51
|
+
files: ["**/*.tsx"],
|
|
52
|
+
plugins: { "md-code": uniqueness },
|
|
53
|
+
rules: {
|
|
54
|
+
"md-code/component-uniqueness": ["error", {
|
|
55
|
+
componentsFolder: [
|
|
56
|
+
{ path: "core/ui/atoms", rank: 0 },
|
|
57
|
+
{ path: "core/ui/formation", rank: 1 },
|
|
58
|
+
{ path: "core/ui/partials", rank: 2 },
|
|
59
|
+
],
|
|
60
|
+
catalogPath: "reports/component-catalog.json",
|
|
61
|
+
}],
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
];
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The catalog is generated automatically on the first lint when the file is
|
|
68
|
+
missing (from the `componentsFolder` option) — it is gitignored and never
|
|
69
|
+
committed. You can also generate it explicitly:
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
bunx md-code-component-uniqueness
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Run the linter as usual:
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
bunx eslint "src/**/*.tsx"
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## CLI
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
bunx md-code-component-uniqueness [flags]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
| Flag | Description |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| `--roots a:b` | Scan roots (overrides `componentsFolder` from config) |
|
|
90
|
+
| `--out <file>` | Catalog output path (default `reports/component-catalog.json`) |
|
|
91
|
+
| `--check` | CI gate — exit 1 if catalog is stale |
|
|
92
|
+
| `--report [file]` | Write a Markdown duplicate report |
|
|
93
|
+
| `--verbose` | Include the "Filtered out" section in the report |
|
|
94
|
+
| `--app-roots a:b` | App-code roots for the report (default: repo root) |
|
|
95
|
+
| `--repo-root <dir>` | Repo root (default: auto-discovered) |
|
|
96
|
+
|
|
97
|
+
## What it flags
|
|
98
|
+
|
|
99
|
+
| Tier | Meaning |
|
|
100
|
+
| --- | --- |
|
|
101
|
+
| `name` | App component has the same name as a canonical one |
|
|
102
|
+
| `name-fuzzy` | Name is a fuzzy match (e.g. `MyButton` vs `Button`) |
|
|
103
|
+
| `structural-exact` | ≥ 80% of the canonical's distinctive class tokens are shared |
|
|
104
|
+
| `structural-similar` | 40–80% shared |
|
|
105
|
+
| `family` | Clusters by token profile (hand-built library pieces) |
|
|
106
|
+
| `jsx-block` | A JSX subtree in app code contains the full tag-sequence of a canonical component |
|
|
107
|
+
|
|
108
|
+
## What the ESLint rule reports
|
|
109
|
+
|
|
110
|
+
| messageId | Fires when |
|
|
111
|
+
| --- | --- |
|
|
112
|
+
| `duplicateComponent` | A canonical component name is declared outside its registry directory |
|
|
113
|
+
| `rawHtml` | A raw interactive element (`button`, `input`, `select`, …) is used outside the canonical packages — the element's behavior (its `type`, `role`, `aria-*`) maps to a canonical component |
|
|
114
|
+
| `layoutPrimitive` | A hand-rolled element **behaves like** a canonical component: its behavioral signals (event handlers + behavioral `role`/`type`/`aria-*` tokens) are a subset of a canonical's. Derived entirely from the catalog — no hardcoded role/behavior lists |
|
|
115
|
+
| `styledInApp` | A `styled.*` component is created outside the canonical packages |
|
|
116
|
+
| `catalogDuplicate` | An element structurally duplicates a canonical one (shared a11y token, or ≥ 3 shared layout style keys with high similarity) — error level |
|
|
117
|
+
| `similarComponent` | Same as above but below the error threshold — warning level |
|
|
118
|
+
|
|
119
|
+
The behavioral check (`layoutPrimitive`) runs only outside the canonical
|
|
120
|
+
folders — inside them, the canonical's own body is the source of truth. It
|
|
121
|
+
keys off the **lowest-rank** canonical whose signal set contains the
|
|
122
|
+
candidate's, so the most basic canonical wins.
|
|
123
|
+
|
|
124
|
+
## Options (rule config)
|
|
125
|
+
|
|
126
|
+
| Option | Default | Notes |
|
|
127
|
+
| --- | --- | --- |
|
|
128
|
+
| `componentsFolder` | `[]` | Canonical dirs. `{ path, rank }` objects or plain strings. Rank drives the behavioral check (lowest = most basic) |
|
|
129
|
+
| `catalog` / `catalogPath` | — / `reports/component-catalog.json` | Inline catalog object, or path to load one |
|
|
130
|
+
| `registry` / `registryPath` | — / `reports/component-registry.json` | Canonical name → allowed dirs, for `duplicateComponent` |
|
|
131
|
+
| `includeDynamic` | `false` | Also load a dynamic (DOM-snapshot) catalog |
|
|
132
|
+
| `dynamicCatalog` / `dynamicCatalogPath` | — | Inline / path for the dynamic catalog |
|
|
133
|
+
| `tsconfig` | — | Fallback `tsconfig.json` (or any `.ts` file next to one) used to resolve imports when the file has no `tsconfig` of its own. Resolution is done by TypeScript; unresolved imports keep their component name |
|
|
134
|
+
| `rawHtml` | `false` | Match every HTML element that carries behavior (an event handler, `role`/`aria-*`, or an interactive tag) against the canonical catalog with the same matchers and decision-maker as components. The best canonical at or above the duplicate threshold is suggested |
|
|
135
|
+
| `exclude` | `*.stories.*`, `*.test.*`, `*.spec.*`, `*.d.ts`, `**/__tests__/**` | Globs, `^...$` regexes or `/.../ ` regexes to skip |
|
|
136
|
+
| `include` | `[]` | If set, only matching files are linted |
|
|
137
|
+
| `exts` | `.tsx`, `.ts`, `.jsx`, `.js` | File extensions to scan |
|
|
138
|
+
| `ignoreDirs` | `node_modules`, `dist`, `build` | Directory names to skip while walking |
|
|
139
|
+
| `rootMarkers` | `.git` | File names that mark the repo root (auto-discovery) |
|
|
140
|
+
| `debt` | `{}` | Known-duplicate ledger (shrink-only) |
|
|
141
|
+
|
|
142
|
+
## Notes
|
|
143
|
+
|
|
144
|
+
- The catalog is **generated on demand** by the rule when the file is missing
|
|
145
|
+
(same code path as the CLI), so it can stay gitignored and CI works out of
|
|
146
|
+
the box. The CLI is still useful for `--report` and `--check`.
|
|
147
|
+
- The catalog is read once per ESLint process and cached.
|
|
148
|
+
- A missing or stale catalog logs a warning; lint never crashes.
|
|
149
|
+
- Everything is plain Node + `fs`/`path` — works identically on Linux, macOS, Windows.
|
package/config.js
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { minimatch } = require("minimatch");
|
|
6
|
+
|
|
7
|
+
const DEFAULT_EXCLUDE = [
|
|
8
|
+
"*.stories.*",
|
|
9
|
+
"*.test.*",
|
|
10
|
+
"*.spec.*",
|
|
11
|
+
"*.d.ts",
|
|
12
|
+
"**/__tests__/**",
|
|
13
|
+
];
|
|
14
|
+
const DEFAULT_EXTS = [".tsx", ".ts", ".jsx", ".js"];
|
|
15
|
+
const DEFAULT_IGNORE_DIRS = ["node_modules", "dist", "build"];
|
|
16
|
+
const DEFAULT_ROOT_MARKERS = [".git"];
|
|
17
|
+
|
|
18
|
+
const findRepoRoot = (startDir, markers = DEFAULT_ROOT_MARKERS) => {
|
|
19
|
+
const markerSet = new Set(markers);
|
|
20
|
+
let dir = path.resolve(startDir);
|
|
21
|
+
for (;;) {
|
|
22
|
+
if (
|
|
23
|
+
fs.existsSync(path.join(dir, "package.json")) &&
|
|
24
|
+
fs.readdirSync(dir).some((name) => markerSet.has(name))
|
|
25
|
+
) {
|
|
26
|
+
return dir;
|
|
27
|
+
}
|
|
28
|
+
const parent = path.dirname(dir);
|
|
29
|
+
if (parent === dir) return null;
|
|
30
|
+
dir = parent;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const ACTION_ATTR_NAMES = new Set([
|
|
35
|
+
"onClick",
|
|
36
|
+
"onMouseDown",
|
|
37
|
+
"onMouseUp",
|
|
38
|
+
"onMouseEnter",
|
|
39
|
+
"onMouseLeave",
|
|
40
|
+
"onMouseMove",
|
|
41
|
+
"onTouchStart",
|
|
42
|
+
"onTouchEnd",
|
|
43
|
+
"onTouchMove",
|
|
44
|
+
"onFocus",
|
|
45
|
+
"onBlur",
|
|
46
|
+
"onChange",
|
|
47
|
+
"onInput",
|
|
48
|
+
"onSubmit",
|
|
49
|
+
"onKeyDown",
|
|
50
|
+
"onKeyUp",
|
|
51
|
+
"onKeyPress",
|
|
52
|
+
"onDragStart",
|
|
53
|
+
"onDragEnd",
|
|
54
|
+
"onDrop",
|
|
55
|
+
"onDragOver",
|
|
56
|
+
"onDoubleClick",
|
|
57
|
+
"onContextMenu",
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
const SUPPORTED_FRAMEWORKS = new Set(["react", "angular", "vue"]);
|
|
61
|
+
|
|
62
|
+
const resolveFramework = (f) => {
|
|
63
|
+
const s = String(f || "react").trim().toLowerCase();
|
|
64
|
+
return SUPPORTED_FRAMEWORKS.has(s) ? s : "react";
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const SUPPORTED_STYLE_SYSTEMS = new Set(["tailwind", "scss", "styled-components"]);
|
|
68
|
+
|
|
69
|
+
const resolveStyleSystem = (s) => {
|
|
70
|
+
const k = String(s || "tailwind").trim().toLowerCase();
|
|
71
|
+
return SUPPORTED_STYLE_SYSTEMS.has(k) ? k : "tailwind";
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const normalizeFolders = (folders) => {
|
|
75
|
+
return (folders || []).map((f) => {
|
|
76
|
+
const raw = f && typeof f === "object" ? f.path : f;
|
|
77
|
+
let s = String(raw).trim().split(path.sep).join("/");
|
|
78
|
+
while (s.startsWith("./")) s = s.slice(2);
|
|
79
|
+
if (!s.endsWith("/")) s += "/";
|
|
80
|
+
return s;
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const normalizeOptions = (opts) => {
|
|
85
|
+
const o = opts && typeof opts === "object" ? opts : {};
|
|
86
|
+
const rootMarkers = o.rootMarkers || DEFAULT_ROOT_MARKERS;
|
|
87
|
+
const root = o.root || findRepoRoot(process.cwd(), rootMarkers);
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
root,
|
|
91
|
+
registry: o.registry || null,
|
|
92
|
+
registryPath: o.registryPath || "reports/component-registry.json",
|
|
93
|
+
catalog: o.catalog || null,
|
|
94
|
+
catalogPath: o.catalogPath || "reports/component-catalog.json",
|
|
95
|
+
includeDynamic: o.includeDynamic === true,
|
|
96
|
+
dynamicCatalog: o.dynamicCatalog || null,
|
|
97
|
+
dynamicCatalogPath: o.dynamicCatalogPath || "reports/component-catalog-dynamic.json",
|
|
98
|
+
rawHtml: o.rawHtml === true,
|
|
99
|
+
parts: o.parts === true,
|
|
100
|
+
framework: resolveFramework(o.framework),
|
|
101
|
+
tsconfig: typeof o.tsconfig === "string" ? o.tsconfig : null,
|
|
102
|
+
styleSystem: resolveStyleSystem(o.styleSystem),
|
|
103
|
+
weights: o.weights && typeof o.weights === "object" ? o.weights : null,
|
|
104
|
+
thresholds: o.thresholds && typeof o.thresholds === "object" ? o.thresholds : null,
|
|
105
|
+
componentsFolder: normalizeFolders(o.componentsFolder || []),
|
|
106
|
+
include: o.include || [],
|
|
107
|
+
exclude: o.exclude || DEFAULT_EXCLUDE,
|
|
108
|
+
exts: o.exts || DEFAULT_EXTS,
|
|
109
|
+
ignoreDirs: o.ignoreDirs ? [...new Set([...DEFAULT_IGNORE_DIRS, ...o.ignoreDirs])] : DEFAULT_IGNORE_DIRS,
|
|
110
|
+
rootMarkers,
|
|
111
|
+
};
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const folderRank = (folders) => {
|
|
115
|
+
const map = new Map();
|
|
116
|
+
(folders || []).forEach((f, i) => {
|
|
117
|
+
const isObj = f && typeof f === "object";
|
|
118
|
+
const raw = isObj ? f.path : f;
|
|
119
|
+
let s = String(raw).trim().split(path.sep).join("/");
|
|
120
|
+
while (s.startsWith("./")) s = s.slice(2);
|
|
121
|
+
if (!s.endsWith("/")) s += "/";
|
|
122
|
+
const r = isObj && typeof f.rank === "number" ? f.rank : i;
|
|
123
|
+
if (!map.has(s)) map.set(s, r);
|
|
124
|
+
});
|
|
125
|
+
return map;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const inComponentsFolder = (relPath, componentsFolder) => {
|
|
129
|
+
return componentsFolder.some((d) => relPath.startsWith(d));
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const layerOf = (relPath, componentsFolder) => {
|
|
133
|
+
return componentsFolder.findIndex((d) => relPath.startsWith(d));
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const canSeeCanon = (appPath, canonPath, componentsFolder) => {
|
|
137
|
+
const appLayer = layerOf(appPath, componentsFolder);
|
|
138
|
+
|
|
139
|
+
return appLayer < 0 || layerOf(canonPath, componentsFolder) < appLayer;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const inCanonicalDir = (relPath, dirs) => {
|
|
143
|
+
return dirs.some((d) => relPath === d || relPath.startsWith(d + "/"));
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const compileMatcher = (pattern) => {
|
|
147
|
+
if (pattern instanceof RegExp) return (p) => pattern.test(p);
|
|
148
|
+
if (typeof pattern !== "string" || pattern.length === 0) return null;
|
|
149
|
+
if (pattern.startsWith("/") && pattern.endsWith("/") && pattern.length > 2) {
|
|
150
|
+
try {
|
|
151
|
+
const re = new RegExp(pattern.slice(1, -1));
|
|
152
|
+
return (p) => re.test(p);
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (pattern.startsWith("^") && pattern.endsWith("$")) {
|
|
158
|
+
try {
|
|
159
|
+
const re = new RegExp(pattern);
|
|
160
|
+
return (p) => re.test(p);
|
|
161
|
+
} catch {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return (p) => minimatch(p, pattern);
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const matchesPath = (m, relPath) => {
|
|
169
|
+
if (m(relPath)) return true;
|
|
170
|
+
const base = relPath.slice(relPath.lastIndexOf("/") + 1);
|
|
171
|
+
return base !== relPath && m(base);
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const isIgnored = (relPath, include, exclude) => {
|
|
175
|
+
for (const pattern of exclude || []) {
|
|
176
|
+
const m = compileMatcher(pattern);
|
|
177
|
+
if (m && matchesPath(m, relPath)) return true;
|
|
178
|
+
}
|
|
179
|
+
if (include && include.length > 0) {
|
|
180
|
+
return !include.some((pattern) => {
|
|
181
|
+
const m = compileMatcher(pattern);
|
|
182
|
+
return m ? matchesPath(m, relPath) : false;
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return false;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const RULE_NAME = "md-code/duplicate-component";
|
|
189
|
+
const RULE_SHORT = "md-code";
|
|
190
|
+
|
|
191
|
+
const FLAT_CANDIDATES = ["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", "eslint.config.ts"];
|
|
192
|
+
const LEGACY_CANDIDATES = [".eslintrc.js", ".eslintrc.cjs", ".eslintrc.json", ".eslintrc.yaml", ".eslintrc.yml"];
|
|
193
|
+
|
|
194
|
+
const loadModule = (file) => {
|
|
195
|
+
const src = fs.readFileSync(file, "utf8");
|
|
196
|
+
if (file.endsWith(".json")) return Promise.resolve(JSON.parse(src));
|
|
197
|
+
if (/^\s*(exports?\s+(default|const|let|var)|import\s)/m.test(src)) {
|
|
198
|
+
const { pathToFileURL } = require("node:url");
|
|
199
|
+
return import(pathToFileURL(file).href).catch((esmErr) => {
|
|
200
|
+
try {
|
|
201
|
+
return require(file);
|
|
202
|
+
} catch {
|
|
203
|
+
throw esmErr;
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return Promise.resolve().then(() => require(file));
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
const pickOptions = (v) => {
|
|
211
|
+
if (v === undefined || v === null) return null;
|
|
212
|
+
if (Array.isArray(v)) return v[1] && typeof v[1] === "object" ? v[1] : {};
|
|
213
|
+
if (typeof v === "object") return v;
|
|
214
|
+
return {};
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const loadFlatOptions = async (file) => {
|
|
218
|
+
const mod = await loadModule(file);
|
|
219
|
+
const list = mod && mod.default !== undefined ? mod.default : mod;
|
|
220
|
+
if (!Array.isArray(list)) return null;
|
|
221
|
+
for (const entry of list) {
|
|
222
|
+
if (!entry || typeof entry !== "object" || !entry.rules) continue;
|
|
223
|
+
const v = entry.rules[RULE_NAME] ?? entry.rules[RULE_SHORT];
|
|
224
|
+
if (v === undefined || v === null) continue;
|
|
225
|
+
return pickOptions(v);
|
|
226
|
+
}
|
|
227
|
+
return null;
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const loadLegacyOptions = async (file) => {
|
|
231
|
+
const mod = await loadModule(file);
|
|
232
|
+
const rules = (mod && mod.rules) || {};
|
|
233
|
+
return pickOptions(rules[RULE_NAME] ?? rules[RULE_SHORT]);
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const loadRuleOptions = async (dir) => {
|
|
237
|
+
let d = dir;
|
|
238
|
+
for (;;) {
|
|
239
|
+
const standalone = path.join(d, "md-code-component-uniqueness.config.js");
|
|
240
|
+
if (fs.existsSync(standalone)) {
|
|
241
|
+
const mod = await loadModule(standalone);
|
|
242
|
+
const options = mod && mod.default !== undefined ? mod.default : mod;
|
|
243
|
+
if (options && typeof options === "object") return { options, source: standalone };
|
|
244
|
+
}
|
|
245
|
+
for (const name of FLAT_CANDIDATES) {
|
|
246
|
+
const file = path.join(d, name);
|
|
247
|
+
if (!fs.existsSync(file)) continue;
|
|
248
|
+
try {
|
|
249
|
+
const options = await loadFlatOptions(file);
|
|
250
|
+
if (options) return { options, source: file };
|
|
251
|
+
} catch {}
|
|
252
|
+
}
|
|
253
|
+
for (const name of LEGACY_CANDIDATES) {
|
|
254
|
+
const file = path.join(d, name);
|
|
255
|
+
if (!fs.existsSync(file)) continue;
|
|
256
|
+
try {
|
|
257
|
+
const options = await loadLegacyOptions(file);
|
|
258
|
+
if (options) return { options, source: file };
|
|
259
|
+
} catch {}
|
|
260
|
+
}
|
|
261
|
+
const parent = path.dirname(d);
|
|
262
|
+
if (parent === d) break;
|
|
263
|
+
d = parent;
|
|
264
|
+
}
|
|
265
|
+
return null;
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const jsonCache = new Map();
|
|
269
|
+
|
|
270
|
+
const loadJson = (absPath, label) => {
|
|
271
|
+
if (jsonCache.has(absPath)) return jsonCache.get(absPath).value;
|
|
272
|
+
|
|
273
|
+
let entry = { loaded: false, value: null, warned: false };
|
|
274
|
+
try {
|
|
275
|
+
const raw = fs.readFileSync(absPath, "utf8");
|
|
276
|
+
const parsed = JSON.parse(raw);
|
|
277
|
+
entry.value = parsed && typeof parsed === "object" ? parsed : null;
|
|
278
|
+
entry.loaded = true;
|
|
279
|
+
} catch (err) {
|
|
280
|
+
entry.value = null;
|
|
281
|
+
entry.loaded = false;
|
|
282
|
+
const reason = err && err.code === "ENOENT" ? "file not found" : `could not be read/parsed (${err && err.message ? err.message : err})`;
|
|
283
|
+
if (!entry.warned) {
|
|
284
|
+
entry.warned = true;
|
|
285
|
+
const rel = path.isAbsolute(absPath) ? absPath : path.resolve(absPath);
|
|
286
|
+
console.warn(
|
|
287
|
+
`[component-uniqueness] ${label} ${reason} at ${rel}. ` +
|
|
288
|
+
`The ${label} is disabled for this run. ` +
|
|
289
|
+
`Generate it first (see the package README) or pass it via the rule options.`
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
jsonCache.set(absPath, entry);
|
|
295
|
+
return entry.value;
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
const resolveAgainst = (p, root) => (path.isAbsolute(p) ? p : path.join(root, p));
|
|
299
|
+
|
|
300
|
+
const loadRegistry = (config) => {
|
|
301
|
+
if (config.registry) return config.registry;
|
|
302
|
+
return loadJson(resolveAgainst(config.registryPath, config.root), "component registry");
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
const loadCatalog = (config) => {
|
|
306
|
+
if (config.catalog) return config.catalog;
|
|
307
|
+
return loadJson(resolveAgainst(config.catalogPath, config.root), "component catalog");
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
const loadDynamicCatalog = (config) => {
|
|
311
|
+
if (config.dynamicCatalog) return config.dynamicCatalog;
|
|
312
|
+
return loadJson(resolveAgainst(config.dynamicCatalogPath, config.root), "dynamic component catalog");
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
module.exports = {
|
|
316
|
+
DEFAULT_EXCLUDE,
|
|
317
|
+
DEFAULT_EXTS,
|
|
318
|
+
DEFAULT_IGNORE_DIRS,
|
|
319
|
+
DEFAULT_ROOT_MARKERS,
|
|
320
|
+
ACTION_ATTR_NAMES,
|
|
321
|
+
findRepoRoot,
|
|
322
|
+
normalizeOptions,
|
|
323
|
+
normalizeFolders,
|
|
324
|
+
inComponentsFolder,
|
|
325
|
+
canSeeCanon,
|
|
326
|
+
inCanonicalDir,
|
|
327
|
+
isIgnored,
|
|
328
|
+
folderRank,
|
|
329
|
+
loadRuleOptions,
|
|
330
|
+
RULE_NAME,
|
|
331
|
+
RULE_SHORT,
|
|
332
|
+
loadJson,
|
|
333
|
+
resolveAgainst,
|
|
334
|
+
loadRegistry,
|
|
335
|
+
loadCatalog,
|
|
336
|
+
loadDynamicCatalog,
|
|
337
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { tokensOf } = require("./matcher/a11y");
|
|
4
|
+
const { NON_SEMANTIC_TAGS } = require("./normalize/dom.js");
|
|
5
|
+
|
|
6
|
+
const DEFAULT_WEIGHTS = {
|
|
7
|
+
name: 0.10,
|
|
8
|
+
structure: 0.5,
|
|
9
|
+
behavior: 0.2,
|
|
10
|
+
a11y: 0.1,
|
|
11
|
+
framework: 0.15,
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const DEFAULT_THRESHOLDS = {
|
|
15
|
+
duplicate: 0.6,
|
|
16
|
+
similar: 0.4,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const clamp01 = (x) => Math.max(0, Math.min(1, x));
|
|
20
|
+
|
|
21
|
+
const resolveWeights = (opts) => {
|
|
22
|
+
const w = (opts && opts.weights) || {};
|
|
23
|
+
return {
|
|
24
|
+
name: w.name ?? DEFAULT_WEIGHTS.name,
|
|
25
|
+
structure: w.structure ?? DEFAULT_WEIGHTS.structure,
|
|
26
|
+
behavior: w.behavior ?? DEFAULT_WEIGHTS.behavior,
|
|
27
|
+
a11y: w.a11y ?? DEFAULT_WEIGHTS.a11y,
|
|
28
|
+
framework: w.framework ?? DEFAULT_WEIGHTS.framework,
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const resolveThresholds = (opts) => {
|
|
33
|
+
const t = (opts && opts.thresholds) || {};
|
|
34
|
+
return {
|
|
35
|
+
duplicate: t.duplicate ?? DEFAULT_THRESHOLDS.duplicate,
|
|
36
|
+
similar: t.similar ?? DEFAULT_THRESHOLDS.similar,
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const applicableOf = (candidate) => ({
|
|
41
|
+
name: false,
|
|
42
|
+
behavior: candidate.framework.events.length > 0,
|
|
43
|
+
a11y: tokensOf(candidate, "a11y").size > 0,
|
|
44
|
+
structure: !!candidate.dom.tree && (Object.keys(candidate.dom.tree.css).length > 0 || !NON_SEMANTIC_TAGS.has(candidate.dom.tree.tag)),
|
|
45
|
+
framework: candidate.framework.props.length > 0 || candidate.framework.events.length > 0,
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const applicableWeights = (weights, applicable) => Object.fromEntries(Object.entries(weights).map(([key, w]) => [key, applicable[key] === false ? 0 : w]));
|
|
49
|
+
|
|
50
|
+
const decide = (candidate, canon, ctx) => {
|
|
51
|
+
const o = ctx || {};
|
|
52
|
+
const flagged = Object.fromEntries(Object.entries(o.signals || {}).filter(([, s]) => s && s.applicable === false).map(([key]) => [key, false]));
|
|
53
|
+
const weights = applicableWeights(resolveWeights(o), { ...(candidate.partial ? applicableOf(candidate) : {}), ...flagged });
|
|
54
|
+
const thresholds = resolveThresholds(o);
|
|
55
|
+
|
|
56
|
+
const signals = {};
|
|
57
|
+
for (const key of ["name", "structure", "behavior", "a11y", "framework"]) {
|
|
58
|
+
const s = o.signals && o.signals[key];
|
|
59
|
+
signals[key] = { score: s ? clamp01(s.score) : 0, evidence: s && s.evidence ? s.evidence : {} };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const totalW = weights.name + weights.structure + weights.behavior + weights.a11y + weights.framework;
|
|
63
|
+
const weighted =
|
|
64
|
+
weights.name * signals.name.score +
|
|
65
|
+
weights.structure * signals.structure.score +
|
|
66
|
+
weights.behavior * signals.behavior.score +
|
|
67
|
+
weights.a11y * signals.a11y.score +
|
|
68
|
+
weights.framework * signals.framework.score;
|
|
69
|
+
const confidence = totalW === 0 ? 0 : clamp01(weighted / totalW);
|
|
70
|
+
|
|
71
|
+
let isDuplicate = false;
|
|
72
|
+
let tier = null;
|
|
73
|
+
if (confidence >= thresholds.duplicate) {
|
|
74
|
+
isDuplicate = true;
|
|
75
|
+
tier = "duplicate";
|
|
76
|
+
} else if (confidence >= thresholds.similar) {
|
|
77
|
+
tier = "similar";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const contributions = Object.fromEntries(Object.entries(signals).map(([k, s]) => [k, weights[k] * s.score]));
|
|
81
|
+
const parts = [];
|
|
82
|
+
for (const key of ["name", "structure", "behavior", "a11y", "framework"]) {
|
|
83
|
+
if (signals[key].score > 0) parts.push(`${key} ${signals[key].score.toFixed(2)}`);
|
|
84
|
+
}
|
|
85
|
+
const reason = parts.length > 0 ? `confidence ${confidence.toFixed(2)} (${parts.join(", ")})` : `confidence ${confidence.toFixed(2)}`;
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
isDuplicate,
|
|
89
|
+
confidence,
|
|
90
|
+
tier,
|
|
91
|
+
reason,
|
|
92
|
+
signals,
|
|
93
|
+
thresholds,
|
|
94
|
+
weights,
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const nodeCount = (node) => (node ? 1 + (node.children || []).reduce((sum, child) => sum + nodeCount(child), 0) : 0);
|
|
99
|
+
|
|
100
|
+
const tagCount = (match) => nodeCount(match.canon.dom && match.canon.dom.tree);
|
|
101
|
+
|
|
102
|
+
const bestOf = (matches) =>
|
|
103
|
+
[...matches].sort((a, b) => b.decision.confidence - a.decision.confidence || tagCount(a) - tagCount(b) || a.canon.name.localeCompare(b.canon.name))[0] || null;
|
|
104
|
+
|
|
105
|
+
module.exports = {
|
|
106
|
+
decide,
|
|
107
|
+
bestOf,
|
|
108
|
+
resolveWeights,
|
|
109
|
+
resolveThresholds,
|
|
110
|
+
clamp01,
|
|
111
|
+
DEFAULT_WEIGHTS,
|
|
112
|
+
DEFAULT_THRESHOLDS,
|
|
113
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const test = (match) => {
|
|
4
|
+
if (match.tier === "name" || match.tier === "name-fuzzy" || match.tier === "jsx-block") return null;
|
|
5
|
+
const appEls = (match.app.elementProps || []).length;
|
|
6
|
+
const canonEls = (match.canon.elementProps || []).length;
|
|
7
|
+
if (canonEls > 0 && appEls > 3 * canonEls) {
|
|
8
|
+
return `app has ${appEls} elements vs canonical's ${canonEls} — match is on a child element, not the component itself`;
|
|
9
|
+
}
|
|
10
|
+
return null;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
module.exports = { name: "drop-child-element", test };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const test = (match) => {
|
|
4
|
+
if ((match.app.usesCanonical || []).includes(match.canon.name)) {
|
|
5
|
+
return `renders canonical ${match.canon.name} (usage, not a duplicate)`;
|
|
6
|
+
}
|
|
7
|
+
return null;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
module.exports = { name: "drop-usages", test };
|