architecture-harness 0.21.2 → 0.22.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.
Files changed (68) hide show
  1. package/package.json +8 -3
  2. package/src/cli/check.mjs +61 -0
  3. package/src/cli/child-run.mjs +39 -0
  4. package/src/cli/child-run.test.mjs +16 -0
  5. package/src/cli/ci-template.test.mjs +28 -0
  6. package/src/cli/codex-implement.mjs +72 -3
  7. package/src/cli/codex-implement.test.mjs +141 -4
  8. package/src/cli/dispatch-guard.mjs +24 -1
  9. package/src/cli/dispatch-guard.test.mjs +30 -0
  10. package/src/cli/dispatch-reminder.mjs +4 -4
  11. package/src/cli/dispatch-reminder.test.mjs +3 -3
  12. package/src/cli/dispatch-slot.mjs +12 -0
  13. package/src/cli/gate-slot.mjs +151 -0
  14. package/src/cli/gate-slot.test.mjs +90 -0
  15. package/src/cli/integrate.mjs +122 -0
  16. package/src/cli/integrate.test.mjs +94 -0
  17. package/src/cli/ledger.mjs +25 -3
  18. package/src/cli/ledger.test.mjs +9 -0
  19. package/src/cli/merge-guard.mjs +13 -3
  20. package/src/cli/merge-guard.test.mjs +24 -1
  21. package/src/cli/migrations.mjs +127 -0
  22. package/src/cli/migrations.test.mjs +94 -0
  23. package/src/cli/plugin-agents.test.mjs +35 -8
  24. package/src/cli/qc.mjs +44 -0
  25. package/src/cli/report-stop.mjs +3 -0
  26. package/src/cli/report-stop.test.mjs +8 -0
  27. package/src/cli/retry-failed.mjs +80 -0
  28. package/src/cli/retry-failed.test.mjs +51 -0
  29. package/src/cli/review-gate.mjs +16 -7
  30. package/src/cli/slot-guard.mjs +43 -0
  31. package/src/cli/slot-guard.test.mjs +28 -0
  32. package/src/cli/task-gate-review.test.mjs +10 -0
  33. package/src/cli/task-gate.mjs +39 -7
  34. package/src/cli/task-gate.test.mjs +45 -0
  35. package/src/cli/throwaway-db.mjs +127 -0
  36. package/src/cli/throwaway-db.test.mjs +83 -0
  37. package/src/cli/ui-reuse-hint.mjs +89 -0
  38. package/src/cli/ui-reuse-hint.test.mjs +60 -0
  39. package/src/cli/ui.mjs +181 -0
  40. package/src/cli/ui.test.mjs +137 -0
  41. package/src/cli/watch.mjs +211 -0
  42. package/src/cli/watch.test.mjs +246 -0
  43. package/src/config.mjs +27 -2
  44. package/src/descriptions.mjs +3 -0
  45. package/src/gates/contract-keys.mjs +33 -0
  46. package/src/gates/contract-keys.test.mjs +38 -0
  47. package/src/gates/migration-numbers.mjs +1 -1
  48. package/src/gates/migration-numbers.test.mjs +1 -0
  49. package/src/gates/ui-catalog.mjs +45 -0
  50. package/src/gates/ui-catalog.test.mjs +48 -0
  51. package/src/gates/ui-dupes.mjs +36 -0
  52. package/src/gates/ui-dupes.test.mjs +29 -0
  53. package/src/ui/catalog.mjs +87 -0
  54. package/src/ui/catalog.test.mjs +54 -0
  55. package/src/ui/class-sites.mjs +151 -0
  56. package/src/ui/class-sites.test.mjs +41 -0
  57. package/src/ui/codemod.mjs +138 -0
  58. package/src/ui/codemod.test.mjs +140 -0
  59. package/src/ui/components.mjs +176 -0
  60. package/src/ui/components.test.mjs +87 -0
  61. package/src/ui/dupes.mjs +141 -0
  62. package/src/ui/dupes.test.mjs +85 -0
  63. package/src/ui/find.mjs +45 -0
  64. package/src/ui/find.test.mjs +48 -0
  65. package/src/ui/options.mjs +40 -0
  66. package/src/ui/scan.mjs +78 -0
  67. package/src/ui/typescript.mjs +29 -0
  68. package/templates/github/workflows/ci.yml +54 -0
@@ -0,0 +1,176 @@
1
+ // The exported React components of one source file: name, line, layer, props and the first JSDoc sentence.
2
+ // A component is a capitalized function, or a capitalized `const` bound to an arrow, a function expression,
3
+ // `forwardRef` or `memo`. The syntax tree comes from the compiler API the repository already holds.
4
+
5
+ const PASCAL = /^[A-Z][A-Za-z0-9]*$/;
6
+ const WRAPPERS = new Set(["forwardRef", "memo"]);
7
+ const FUNCTION_COMPONENT_TYPES = new Set(["FC", "FunctionComponent", "VFC", "ForwardRefExoticComponent"]);
8
+
9
+ const isComponentName = (name) => PASCAL.test(name) && /[a-z]/.test(name);
10
+
11
+ /** The first sentence of a doc comment: to the first full stop that ends a word, or the paragraph, or the end. */
12
+ export function firstSentence(comment) {
13
+ const paragraph = String(comment ?? "").trim().split(/\n\s*\n/)[0] ?? "";
14
+ const flat = paragraph.replace(/\s+/g, " ").trim();
15
+ const stop = /[.!?](?=\s|$)/.exec(flat);
16
+ return stop ? flat.slice(0, stop.index + 1) : flat;
17
+ }
18
+
19
+ /** The layer of a file: the longest `layers` prefix that holds it, else `feature:<name>`, else `platform`. */
20
+ export function layerOf(rel, options, featureDir = "features") {
21
+ let best = null;
22
+ for (const [layer, prefix] of Object.entries(options.layers ?? {})) {
23
+ const folder = `${prefix.replace(/\/+$/, "")}/`;
24
+ if (rel.startsWith(folder) && (best === null || folder.length > best.length)) best = { layer, length: folder.length };
25
+ }
26
+ if (best) return best.layer;
27
+ const parts = rel.split("/");
28
+ const at = parts.indexOf(featureDir);
29
+ if (at !== -1 && parts.length > at + 2) return `feature:${parts[at + 1]}`;
30
+ return "platform";
31
+ }
32
+
33
+ const modifiersOf = (ts, node) => (ts.canHaveModifiers?.(node) ? (ts.getModifiers(node) ?? []) : (node.modifiers ?? []));
34
+ const hasModifier = (ts, node, kind) => modifiersOf(ts, node).some((modifier) => modifier.kind === kind);
35
+
36
+ function calleeName(ts, expression) {
37
+ if (ts.isIdentifier(expression)) return expression.text;
38
+ if (ts.isPropertyAccessExpression(expression)) return expression.name.text;
39
+ return null;
40
+ }
41
+
42
+ /** The function, or the `forwardRef` / `memo` call, a component is bound to. Null for anything else. */
43
+ function componentValue(ts, init) {
44
+ let node = init;
45
+ while (node && (ts.isParenthesizedExpression(node) || ts.isAsExpression(node))) node = node.expression;
46
+ if (!node) return null;
47
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) return { fn: node, call: null, reference: null };
48
+ if (ts.isCallExpression(node) && WRAPPERS.has(calleeName(ts, node.expression))) {
49
+ const inner = node.arguments[0];
50
+ const nested = inner ? componentValue(ts, inner) : null;
51
+ return { fn: nested?.fn ?? null, call: node, reference: inner && ts.isIdentifier(inner) ? inner.text : null };
52
+ }
53
+ return null;
54
+ }
55
+
56
+ function memberNames(ts, members) {
57
+ const names = [];
58
+ for (const member of members) {
59
+ if (!(ts.isPropertySignature(member) || ts.isMethodSignature(member))) continue;
60
+ if (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) names.push(member.name.text);
61
+ }
62
+ return names;
63
+ }
64
+
65
+ /** The prop names of a type reference to a local interface or alias, with what an interface extends. */
66
+ function propsOfReference(ts, name, types, seen) {
67
+ const declared = types.get(name);
68
+ if (!declared || seen.has(name)) return [];
69
+ seen.add(name);
70
+ if (ts.isTypeAliasDeclaration(declared)) return propsOfType(ts, declared.type, types, seen);
71
+ const inherited = (declared.heritageClauses ?? []).flatMap((clause) =>
72
+ clause.types.flatMap((one) => (ts.isIdentifier(one.expression) ? propsOfReference(ts, one.expression.text, types, seen) : [])),
73
+ );
74
+ return [...memberNames(ts, declared.members), ...inherited];
75
+ }
76
+
77
+ /** The prop names a type declares, following local interfaces, aliases, unions and intersections. */
78
+ function propsOfType(ts, node, types, seen = new Set()) {
79
+ if (!node) return [];
80
+ if (ts.isParenthesizedTypeNode(node)) return propsOfType(ts, node.type, types, seen);
81
+ if (ts.isTypeLiteralNode(node)) return memberNames(ts, node.members);
82
+ if (ts.isIntersectionTypeNode(node) || ts.isUnionTypeNode(node)) return node.types.flatMap((one) => propsOfType(ts, one, types, seen));
83
+ if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) return propsOfReference(ts, node.typeName.text, types, seen);
84
+ return [];
85
+ }
86
+
87
+ function bindingNames(ts, pattern) {
88
+ if (!pattern || !ts.isObjectBindingPattern(pattern)) return [];
89
+ return pattern.elements
90
+ .filter((element) => !element.dotDotDotToken)
91
+ .map((element) => element.propertyName ?? element.name)
92
+ .filter((name) => ts.isIdentifier(name) || ts.isStringLiteral(name))
93
+ .map((name) => name.text);
94
+ }
95
+
96
+ function typeNameOf(ts, reference) {
97
+ if (ts.isIdentifier(reference.typeName)) return reference.typeName.text;
98
+ return reference.typeName.right.text;
99
+ }
100
+
101
+ function propsOf(ts, info, types, declared) {
102
+ const { fn, call, annotation, reference } = info;
103
+ const typeArguments = [];
104
+ if (annotation && ts.isTypeReferenceNode(annotation) && FUNCTION_COMPONENT_TYPES.has(typeNameOf(ts, annotation))) {
105
+ typeArguments.push(annotation.typeArguments?.[0]);
106
+ }
107
+ if (call?.typeArguments) typeArguments.push(calleeName(ts, call.expression) === "forwardRef" ? call.typeArguments[1] : call.typeArguments[0]);
108
+ const target = fn ?? (reference ? declared.get(reference)?.fn : null);
109
+ const first = target?.parameters?.[0];
110
+ const typed = [...typeArguments, first?.type].flatMap((type) => propsOfType(ts, type, types));
111
+ return [...new Set(typed.length > 0 ? typed : bindingNames(ts, first?.name))];
112
+ }
113
+
114
+ function describe(ts, statement) {
115
+ const doc = ts.getJSDocCommentsAndTags(statement).filter((one) => ts.isJSDoc(one)).at(-1);
116
+ return doc ? firstSentence(ts.getTextOfJSDocComment(doc.comment) ?? "") : "";
117
+ }
118
+
119
+ /** Every component a file declares, by local name, whether or not it is exported. */
120
+ function declaredComponents(ts, file) {
121
+ const types = new Map();
122
+ const declared = new Map();
123
+ for (const statement of file.statements) {
124
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {
125
+ types.set(statement.name.text, statement);
126
+ } else if (ts.isFunctionDeclaration(statement) && statement.name && isComponentName(statement.name.text)) {
127
+ declared.set(statement.name.text, { statement, nameNode: statement.name, fn: statement, call: null, reference: null });
128
+ } else if (ts.isVariableStatement(statement)) {
129
+ for (const declaration of statement.declarationList.declarations) {
130
+ if (!ts.isIdentifier(declaration.name) || !isComponentName(declaration.name.text) || !declaration.initializer) continue;
131
+ const value = componentValue(ts, declaration.initializer);
132
+ if (value) declared.set(declaration.name.text, { statement, nameNode: declaration.name, annotation: declaration.type, ...value });
133
+ }
134
+ }
135
+ }
136
+ return { types, declared };
137
+ }
138
+
139
+ /** The exported name of each exported component, mapped to its local name. */
140
+ function exportedNames(ts, file, declared) {
141
+ const exported = new Map();
142
+ for (const statement of file.statements) {
143
+ if ((ts.isFunctionDeclaration(statement) || ts.isVariableStatement(statement)) && hasModifier(ts, statement, ts.SyntaxKind.ExportKeyword)) {
144
+ const names = ts.isFunctionDeclaration(statement)
145
+ ? [statement.name?.text]
146
+ : statement.declarationList.declarations.map((one) => (ts.isIdentifier(one.name) ? one.name.text : null));
147
+ for (const name of names) if (name && declared.has(name)) exported.set(name, name);
148
+ } else if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
149
+ for (const element of statement.exportClause.elements) {
150
+ const local = (element.propertyName ?? element.name).text;
151
+ if (declared.has(local)) exported.set(element.name.text === "default" ? local : element.name.text, local);
152
+ }
153
+ } else if (ts.isExportAssignment(statement) && !statement.isExportEquals && ts.isIdentifier(statement.expression) && declared.has(statement.expression.text)) {
154
+ exported.set(statement.expression.text, statement.expression.text);
155
+ }
156
+ }
157
+ return exported;
158
+ }
159
+
160
+ /**
161
+ * @param ts the TypeScript module
162
+ * @param {string} rel the repository-relative path
163
+ * @param {string} text the source
164
+ * @returns {{name: string, path: string, line: number, props: string[], description: string}[]} sorted by name
165
+ */
166
+ export function extractComponents(ts, rel, text) {
167
+ const file = ts.createSourceFile(rel, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
168
+ const { types, declared } = declaredComponents(ts, file);
169
+ const found = [];
170
+ for (const [name, local] of exportedNames(ts, file, declared)) {
171
+ const info = declared.get(local);
172
+ const line = file.getLineAndCharacterOfPosition(info.nameNode.getStart(file)).line + 1;
173
+ found.push({ name, path: rel, line, props: propsOf(ts, info, types, declared), description: describe(ts, info.statement) });
174
+ }
175
+ return found.sort((a, b) => a.name.localeCompare(b.name));
176
+ }
@@ -0,0 +1,87 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { extractComponents, firstSentence, layerOf } from "./components.mjs";
4
+ import { loadTypeScript } from "./typescript.mjs";
5
+
6
+ const ts = loadTypeScript();
7
+ const extract = (text, rel = "frontend/src/platform/ui/primitives/button.tsx") => extractComponents(ts, rel, text);
8
+
9
+ test("a function component records its name, line, props and first JSDoc sentence", () => {
10
+ const [button] = extract(`import React from "react";
11
+ interface ButtonProps { label: string; onPress?: () => void }
12
+ /** A pressable control. It shows a spinner while loading. */
13
+ export function Button({ label, onPress }: ButtonProps) { return <button onClick={onPress}>{label}</button>; }
14
+ `);
15
+ assert.deepEqual(
16
+ { name: button.name, line: button.line, props: button.props, description: button.description },
17
+ { name: "Button", line: 4, props: ["label", "onPress"], description: "A pressable control." },
18
+ );
19
+ });
20
+
21
+ test("a const bound to an arrow, forwardRef and memo is a component", () => {
22
+ const found = extract(`
23
+ type Props = { a: string } & { b?: number };
24
+ /** Arrow. */
25
+ export const Arrow = ({ a }: Props) => <i>{a}</i>;
26
+ /** Forwarded. */
27
+ export const Forwarded = React.forwardRef<HTMLDivElement, { tone: string }>((props, ref) => <div ref={ref} />);
28
+ /** Memoised. */
29
+ export const Memoised = memo(function Memoised(props: Props) { return null; });
30
+ `);
31
+ assert.deepEqual(
32
+ found.map((c) => [c.name, c.props]),
33
+ [["Arrow", ["a", "b"]], ["Forwarded", ["tone"]], ["Memoised", ["a", "b"]]],
34
+ );
35
+ });
36
+
37
+ test("a lowercase function, a constant and a function that is not exported are skipped", () => {
38
+ const found = extract(`
39
+ export function helper() { return 1; }
40
+ export const MAX_ITEMS = 5;
41
+ function Hidden() { return <i />; }
42
+ export const Config = { a: 1 };
43
+ `);
44
+ assert.deepEqual(found, []);
45
+ });
46
+
47
+ test("a component exported by a list or as the default is found, with the JSDoc of its declaration", () => {
48
+ const found = extract(`
49
+ /** Listed. */
50
+ function Listed() { return <i />; }
51
+ /** Default one. */
52
+ function Fallback() { return <i />; }
53
+ export { Listed as Renamed };
54
+ export default Fallback;
55
+ `);
56
+ assert.deepEqual(found.map((c) => [c.name, c.description]), [["Fallback", "Default one."], ["Renamed", "Listed."]]);
57
+ });
58
+
59
+ test("a component with no JSDoc has an empty description", () => {
60
+ const [one] = extract("export const Bare = () => <i />;\n");
61
+ assert.equal(one.description, "");
62
+ });
63
+
64
+ test("props come from an extended local interface and fall back to the destructured names", () => {
65
+ const found = extract(`
66
+ interface Base { id: string }
67
+ interface Card extends Base { title: string }
68
+ export function CardView(props: Card) { return null; }
69
+ export const Loose = ({ x, y: z, ...rest }) => null;
70
+ `);
71
+ assert.deepEqual(found.map((c) => c.props), [["title", "id"], ["x", "y"]]);
72
+ });
73
+
74
+ test("firstSentence stops at the first full stop, a paragraph break, or the end", () => {
75
+ assert.equal(firstSentence("One thing. Another."), "One thing.");
76
+ assert.equal(firstSentence("Spans\nlines without a stop\n\nNext paragraph."), "Spans lines without a stop");
77
+ assert.equal(firstSentence("Version 1.2 is fine. Yes."), "Version 1.2 is fine.");
78
+ assert.equal(firstSentence(""), "");
79
+ });
80
+
81
+ test("the layer is the longest configured prefix, then feature:<name>, then platform", () => {
82
+ const options = { layers: { primitive: "frontend/src/platform/ui/primitives", pattern: "frontend/src/platform/ui" } };
83
+ assert.equal(layerOf("frontend/src/platform/ui/primitives/button.tsx", options, "features"), "primitive");
84
+ assert.equal(layerOf("frontend/src/platform/ui/card.tsx", options, "features"), "pattern");
85
+ assert.equal(layerOf("frontend/src/features/photos/components/grid.tsx", options, "features"), "feature:photos");
86
+ assert.equal(layerOf("frontend/src/platform/shell/frame.tsx", options, "features"), "platform");
87
+ });
@@ -0,0 +1,141 @@
1
+ // Duplicate UI the catalog cannot prevent: the same class string repeated, two components with one name,
2
+ // and two JSX trees that differ by a class or two. Each finding has an id, so a baseline can hold the
3
+ // ones that predate the gate.
4
+
5
+ import { createHash } from "node:crypto";
6
+ import { classSpans, tokensOfSpan } from "./class-sites.mjs";
7
+ import { parseSource } from "./typescript.mjs";
8
+
9
+ const MIN_TREE_ELEMENTS = 4;
10
+ const MIN_OVERLAP = 0.8;
11
+
12
+ export const findingId = (finding) => `${finding.kind}:${finding.key}`;
13
+
14
+ const shortHash = (text) => createHash("sha1").update(text).digest("hex").slice(0, 8);
15
+
16
+ /** The class strings of a file, each as its sorted tokens joined by one space. A string cut by a substitution is left out. */
17
+ function classStrings(ts, source, callees) {
18
+ const strings = [];
19
+ for (const span of classSpans(ts, source, callees)) {
20
+ if (span.leftOpen || span.rightOpen) continue;
21
+ const tokens = tokensOfSpan(source.text, span).map((token) => token.text);
22
+ if (tokens.length > 0) strings.push({ normalized: [...new Set(tokens)].sort().join(" "), start: span.start });
23
+ }
24
+ return strings;
25
+ }
26
+
27
+ function classStringFindings(perFile, { minClassLength, minFiles }) {
28
+ const byString = new Map();
29
+ for (const { path, strings } of perFile) {
30
+ for (const { normalized } of strings) {
31
+ if (normalized.length < minClassLength) continue;
32
+ byString.set(normalized, new Set([...(byString.get(normalized) ?? []), path]));
33
+ }
34
+ }
35
+ return [...byString]
36
+ .filter(([, paths]) => paths.size >= minFiles)
37
+ .map(([key, paths]) => ({ kind: "class-string", key, files: [...paths].sort() }));
38
+ }
39
+
40
+ function componentNameFindings(entries) {
41
+ const byName = new Map();
42
+ for (const entry of entries) byName.set(entry.name, new Set([...(byName.get(entry.name) ?? []), entry.path]));
43
+ return [...byName]
44
+ .filter(([, paths]) => paths.size > 1)
45
+ .map(([key, paths]) => ({ kind: "component-name", key, files: [...paths].sort() }));
46
+ }
47
+
48
+ /** The JSX nodes directly below `node`: its children, and the first ones inside an expression child. */
49
+ function jsxChildren(ts, node) {
50
+ const found = [];
51
+ const isJsx = (one) => ts.isJsxElement(one) || ts.isJsxSelfClosingElement(one) || ts.isJsxFragment(one);
52
+ const descend = (one) => (isJsx(one) ? found.push(one) : ts.forEachChild(one, descend));
53
+ if (ts.isJsxElement(node) || ts.isJsxFragment(node)) node.children.forEach(descend);
54
+ return found;
55
+ }
56
+
57
+ /** Every JSX tree of four elements or more in a file, with its skeleton and the class tokens it holds. */
58
+ function jsxTrees(ts, source, strings, path) {
59
+ const trees = [];
60
+ const tagOf = (node) => {
61
+ if (ts.isJsxFragment(node)) return "";
62
+ return (ts.isJsxElement(node) ? node.openingElement : node).tagName.getText(source);
63
+ };
64
+ function walk(node) {
65
+ const children = jsxChildren(ts, node).map(walk);
66
+ const counted = (ts.isJsxFragment(node) ? 0 : 1) + children.reduce((sum, child) => sum + child.count, 0);
67
+ const skeleton = `${tagOf(node)}(${children.map((child) => child.skeleton).join(",")})`;
68
+ const start = node.getStart(source);
69
+ const end = node.getEnd();
70
+ const tokens = new Set();
71
+ for (const one of strings) if (one.start >= start && one.start < end) one.normalized.split(" ").forEach((token) => tokens.add(token));
72
+ const here = { path, skeleton, count: counted, start, end, tokens, line: source.getLineAndCharacterOfPosition(start).line + 1 };
73
+ if (counted >= MIN_TREE_ELEMENTS) trees.push(here);
74
+ return here;
75
+ }
76
+ const visit = (node) => {
77
+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node)) walk(node);
78
+ else ts.forEachChild(node, visit);
79
+ };
80
+ visit(source);
81
+ return trees;
82
+ }
83
+
84
+ function jaccard(a, b) {
85
+ let shared = 0;
86
+ for (const token of a) if (b.has(token)) shared += 1;
87
+ const union = a.size + b.size - shared;
88
+ return union === 0 ? 0 : shared / union;
89
+ }
90
+
91
+ const contains = (outer, inner) => outer.start <= inner.start && inner.end <= outer.end;
92
+
93
+ function treeFindings(trees) {
94
+ const bySkeleton = Map.groupBy(trees, (tree) => tree.skeleton);
95
+ const pairs = [];
96
+ for (const group of bySkeleton.values()) {
97
+ for (let i = 0; i < group.length; i += 1) {
98
+ for (let j = i + 1; j < group.length; j += 1) {
99
+ const [a, b] = group[i].path <= group[j].path ? [group[i], group[j]] : [group[j], group[i]];
100
+ if (a.path !== b.path && jaccard(a.tokens, b.tokens) >= MIN_OVERLAP) pairs.push({ a, b });
101
+ }
102
+ }
103
+ }
104
+ // A subtree of a duplicated pair is duplicated too; only the outermost pair is a finding.
105
+ const maximal = pairs.filter(
106
+ (p) => !pairs.some((q) => q !== p && q.a.path === p.a.path && q.b.path === p.b.path && contains(q.a, p.a) && contains(q.b, p.b)),
107
+ );
108
+ const byKey = new Map();
109
+ for (const { a, b } of maximal) {
110
+ const key = `${a.path}~${b.path}#${shortHash(a.skeleton)}`;
111
+ const found = byKey.get(key) ?? { kind: "jsx-tree", key, files: [a.path, b.path], elements: a.count, locations: [] };
112
+ found.locations.push(`${a.path}:${a.line}`, `${b.path}:${b.line}`);
113
+ byKey.set(key, found);
114
+ }
115
+ return [...byKey.values()];
116
+ }
117
+
118
+ /**
119
+ * @param ts the TypeScript module
120
+ * @param {{path: string, contents: string}[]} files the component files
121
+ * @param {{entries: object[], callees: string[], minClassLength: number, minFiles: number}} options `entries` are the catalog's
122
+ * @returns {{kind: string, key: string, files: string[]}[]} sorted by kind, then key
123
+ */
124
+ export function findDupes(ts, files, { entries, callees, minClassLength, minFiles }) {
125
+ const perFile = [];
126
+ const trees = [];
127
+ for (const file of files) {
128
+ const source = parseSource(ts, file.path, file.contents);
129
+ const strings = classStrings(ts, source, callees);
130
+ perFile.push({ path: file.path, strings });
131
+ trees.push(...jsxTrees(ts, source, strings, file.path));
132
+ }
133
+ return [
134
+ ...classStringFindings(perFile, { minClassLength, minFiles }),
135
+ ...componentNameFindings(entries),
136
+ ...treeFindings(trees),
137
+ ].sort((a, b) => a.kind.localeCompare(b.kind) || a.key.localeCompare(b.key));
138
+ }
139
+
140
+ /** The baseline file's content: the id of each finding today. */
141
+ export const baselineOfFindings = (findings) => ({ findings: findings.map(findingId).sort() });
@@ -0,0 +1,85 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { catalogEntries } from "./catalog.mjs";
4
+ import { findDupes, findingId } from "./dupes.mjs";
5
+ import { loadTypeScript } from "./typescript.mjs";
6
+
7
+ const ts = loadTypeScript();
8
+ const options = { componentRoots: ["ui"], layers: {} };
9
+ const settings = { callees: ["cn", "clsx", "cva", "twMerge"], minClassLength: 20, minFiles: 3 };
10
+ const find = (files, over = {}) =>
11
+ findDupes(ts, files, { ...settings, ...over, entries: catalogEntries(ts, options, files) });
12
+ const kinds = (found, kind) => found.filter((one) => one.kind === kind);
13
+
14
+ const LONG = "flex items-center gap-2 rounded-md border px-3 py-2";
15
+
16
+ test("a long class string in three files is reported once, whatever the token order", () => {
17
+ const reordered = "px-3 py-2 gap-2 flex items-center rounded-md border";
18
+ const files = [
19
+ { path: "ui/a.tsx", contents: `export const A = () => <div className="${LONG}" />;` },
20
+ { path: "ui/b.tsx", contents: `export const B = () => <div className={cn("${reordered}")} />;` },
21
+ { path: "ui/c.tsx", contents: `export const C = () => <div className="${LONG}" />;` },
22
+ ];
23
+ const [one, ...rest] = kinds(find(files), "class-string");
24
+ assert.equal(rest.length, 0);
25
+ assert.deepEqual(one.files, ["ui/a.tsx", "ui/b.tsx", "ui/c.tsx"]);
26
+ assert.equal(one.key, [...LONG.split(" ")].sort().join(" "));
27
+ });
28
+
29
+ test("a class string below the length, or in fewer files than the minimum, or twice in one file, is not reported", () => {
30
+ const files = [
31
+ { path: "ui/a.tsx", contents: `export const A = () => <div className="${LONG}" />;` },
32
+ { path: "ui/b.tsx", contents: `export const B = () => <><i className="${LONG}" /><i className="${LONG}" /></>;` },
33
+ { path: "ui/c.tsx", contents: `export const C = () => <div className="flex p-2" />;` },
34
+ { path: "ui/d.tsx", contents: `export const D = () => <div className="flex p-2" />;` },
35
+ { path: "ui/e.tsx", contents: `export const E = () => <div className="flex p-2" />;` },
36
+ ];
37
+ assert.deepEqual(kinds(find(files), "class-string"), []);
38
+ });
39
+
40
+ test("two exported components with one name in different files are reported", () => {
41
+ const files = [
42
+ { path: "ui/a/card.tsx", contents: "export const Card = () => null;" },
43
+ { path: "ui/b/card.tsx", contents: "export function Card() { return null; }" },
44
+ { path: "ui/c.tsx", contents: "export const Other = () => null;" },
45
+ ];
46
+ const [one] = kinds(find(files), "component-name");
47
+ assert.deepEqual([one.key, one.files], ["Card", ["ui/a/card.tsx", "ui/b/card.tsx"]]);
48
+ });
49
+
50
+ const tree = (classes) =>
51
+ `export const T = () => (<section className="${classes[0]}"><header className="${classes[1]}"><h2 className="${classes[2]}">t</h2></header><p className="${classes[3]}">x</p></section>);`;
52
+
53
+ test("a tree of four elements with one skeleton and a class overlap of 0.8 or more is reported across files", () => {
54
+ const same = ["card p-4", "flex gap-2", "font-bold text-lg", "text-sm text-muted"];
55
+ const near = ["card p-4", "flex gap-2", "font-bold text-lg", "text-sm text-muted extra"];
56
+ const files = [
57
+ { path: "ui/a.tsx", contents: tree(same) },
58
+ { path: "ui/b.tsx", contents: tree(near) },
59
+ ];
60
+ const [one, ...rest] = kinds(find(files), "jsx-tree");
61
+ assert.equal(rest.length, 0);
62
+ assert.deepEqual(one.files, ["ui/a.tsx", "ui/b.tsx"]);
63
+ assert.equal(one.elements, 4);
64
+ });
65
+
66
+ test("a tree below the overlap, with another skeleton, or in one file is not reported", () => {
67
+ const same = ["card p-4", "flex gap-2", "font-bold text-lg", "text-sm text-muted"];
68
+ const apart = ["a-1", "b-1", "c-1", "d-1"];
69
+ const other = tree(same).replace("<p ", "<div ").replace("</p>", "</div>");
70
+ assert.deepEqual(kinds(find([{ path: "ui/a.tsx", contents: tree(same) }, { path: "ui/b.tsx", contents: tree(apart) }]), "jsx-tree"), []);
71
+ assert.deepEqual(kinds(find([{ path: "ui/a.tsx", contents: tree(same) }, { path: "ui/b.tsx", contents: other }]), "jsx-tree"), []);
72
+ assert.deepEqual(kinds(find([{ path: "ui/a.tsx", contents: tree(same) + "\n" + tree(same).replace("T =", "U =") }]), "jsx-tree"), []);
73
+ });
74
+
75
+ test("an outer tree reports once, not again for each subtree it holds", () => {
76
+ const big = (extra) =>
77
+ `export const T = () => (<main className="m"><section className="a b"><header className="c d"><h2 className="e f">t</h2></header><p className="g h">x</p></section><footer className="${extra}">z</footer></main>);`;
78
+ const found = kinds(find([{ path: "ui/a.tsx", contents: big("x y") }, { path: "ui/b.tsx", contents: big("x y") }]), "jsx-tree");
79
+ assert.equal(found.length, 1);
80
+ assert.equal(found[0].elements, 6);
81
+ });
82
+
83
+ test("findingId names the kind and the key, so a baseline can hold it", () => {
84
+ assert.equal(findingId({ kind: "component-name", key: "Card" }), "component-name:Card");
85
+ });
@@ -0,0 +1,45 @@
1
+ // Finding a component before writing one: rank the catalog entries by the tokens they share with the
2
+ // words asked. The camel-case parts of a name weigh most, then its description and its prop names.
3
+
4
+ const FILLER = new Set(["a", "an", "the", "of", "to", "in", "on", "for", "and", "or", "with", "is", "it", "this", "that"]);
5
+ const NAME_WEIGHT = 3;
6
+
7
+ const singular = (token) => (token.length > 3 && token.endsWith("s") && !token.endsWith("ss") ? token.slice(0, -1) : token);
8
+
9
+ /** Lowercase tokens: camel-case parts, digit runs and words, with filler dropped and a trailing plural s removed. */
10
+ export function tokensOf(text) {
11
+ const parts = String(text ?? "")
12
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
13
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
14
+ .replace(/([A-Za-z])(\d)/g, "$1 $2")
15
+ .toLowerCase()
16
+ .split(/[^a-z0-9]+/)
17
+ .filter(Boolean);
18
+ return parts.filter((token) => !FILLER.has(token)).map(singular);
19
+ }
20
+
21
+ /**
22
+ * @param {{name: string, path: string, props: string[], description: string}[]} entries
23
+ * @param {string[]} words what the caller wants, in any case
24
+ * @param {number} [limit]
25
+ * @returns {{entry: object, score: number}[]} the best first; an entry that shares no token is left out
26
+ */
27
+ export function findComponents(entries, words, limit = 8) {
28
+ const wanted = new Set(words.flatMap(tokensOf));
29
+ if (wanted.size === 0) return [];
30
+ const count = (tokens) => [...new Set(tokens)].filter((token) => wanted.has(token)).length;
31
+ const scored = entries.map((entry) => ({
32
+ entry,
33
+ score:
34
+ NAME_WEIGHT * count(tokensOf(entry.name)) + count(tokensOf(entry.description)) + count(entry.props.flatMap(tokensOf)),
35
+ }));
36
+ return scored
37
+ .filter((one) => one.score > 0)
38
+ .sort((a, b) => b.score - a.score || a.entry.name.localeCompare(b.entry.name) || a.entry.path.localeCompare(b.entry.path))
39
+ .slice(0, limit);
40
+ }
41
+
42
+ /** One line per entry: `name — path — description`. */
43
+ export function formatFound({ entry }) {
44
+ return `${entry.name} — ${entry.path} — ${entry.description}`;
45
+ }
@@ -0,0 +1,48 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { findComponents, formatFound, tokensOf } from "./find.mjs";
4
+
5
+ const entries = [
6
+ { name: "ConfirmDialog", path: "ui/confirm-dialog.tsx", props: ["title", "onConfirm"], description: "Asks the user to confirm a destructive action." },
7
+ { name: "PhotoGrid", path: "features/photos/photo-grid.tsx", props: ["photos", "onSelect"], description: "A responsive grid of photo thumbnails." },
8
+ { name: "Button", path: "ui/button.tsx", props: ["label", "loading"], description: "A pressable control." },
9
+ { name: "EmptyState", path: "ui/empty-state.tsx", props: ["message"], description: "Says a list has no rows." },
10
+ ];
11
+
12
+ test("tokensOf splits camel case, digits and separators, drops filler words and a plural s", () => {
13
+ assert.deepEqual(tokensOf("PhotoGridView"), ["photo", "grid", "view"]);
14
+ assert.deepEqual(tokensOf("the photos of a user-list"), ["photo", "user", "list"]);
15
+ assert.deepEqual(tokensOf("HTMLParser2"), ["html", "parser", "2"]);
16
+ });
17
+
18
+ test("a name match outranks a description or prop match", () => {
19
+ const found = findComponents(entries, ["grid"]);
20
+ assert.equal(found[0].entry.name, "PhotoGrid");
21
+ });
22
+
23
+ test("the description and the prop names count", () => {
24
+ assert.equal(findComponents(entries, ["confirm", "destructive"])[0].entry.name, "ConfirmDialog");
25
+ assert.equal(findComponents(entries, ["loading"])[0].entry.name, "Button");
26
+ });
27
+
28
+ test("an entry that shares no token is not returned, and the list is capped at eight", () => {
29
+ assert.deepEqual(findComponents(entries, ["zebra"]), []);
30
+ const many = Array.from({ length: 20 }, (_, index) => ({ name: `Card${index}`, path: `c${index}.tsx`, props: [], description: "" }));
31
+ assert.equal(findComponents(many, ["card"]).length, 8);
32
+ });
33
+
34
+ test("equal scores keep a stable order by name", () => {
35
+ const found = findComponents(
36
+ [
37
+ { name: "BCard", path: "b.tsx", props: [], description: "card" },
38
+ { name: "ACard", path: "a.tsx", props: [], description: "card" },
39
+ ],
40
+ ["card"],
41
+ );
42
+ assert.deepEqual(found.map((one) => one.entry.name), ["ACard", "BCard"]);
43
+ });
44
+
45
+ test("formatFound prints name, path and description", () => {
46
+ const [one] = findComponents(entries, ["button"]);
47
+ assert.equal(formatFound(one), "Button — ui/button.tsx — A pressable control.");
48
+ });
@@ -0,0 +1,40 @@
1
+ // A fragment: the `ui` block of the configuration, read once. Every path and threshold the UI tools
2
+ // use comes from here, so a repository names its own layout and the tools name none.
3
+
4
+ import { globMatcher } from "../glob.mjs";
5
+
6
+ /** @returns the `ui` block with its defaults filled in. */
7
+ export function uiOptions(config) {
8
+ const ui = config.ui ?? {};
9
+ return {
10
+ componentRoots: ui.componentRoots ?? [],
11
+ layers: ui.layers ?? {},
12
+ catalog: ui.catalog ?? "docs/ui-catalog.md",
13
+ catalogBaseline: ui.catalogBaseline ?? "ui-catalog.baseline.json",
14
+ classCallees: ui.classCallees ?? ["cn", "clsx", "cva", "twMerge"],
15
+ dupes: {
16
+ minClassLength: ui.dupes?.minClassLength ?? 60,
17
+ minFiles: ui.dupes?.minFiles ?? 3,
18
+ baseline: ui.dupes?.baseline ?? "ui-dupes.baseline.json",
19
+ },
20
+ };
21
+ }
22
+
23
+ const TEST_OR_STORY = /\.(?:test|spec|stories|story)\.[cm]?[jt]sx?$|(?:^|\/)__tests__\//;
24
+ const TSX = /\.tsx$/;
25
+
26
+ /** True for a test or a story, which hold no component the catalog lists. */
27
+ export const isTestOrStory = (rel) => TEST_OR_STORY.test(rel);
28
+
29
+ /** A matcher for the `.tsx` files under the component roots, tests and stories excluded. */
30
+ export function componentFileMatcher(options) {
31
+ const under = globMatcher(options.componentRoots.map((root) => `${root.replace(/\/+$/, "")}/**`));
32
+ return (rel) => TSX.test(rel) && !isTestOrStory(rel) && under(rel);
33
+ }
34
+
35
+ /** `a/{b,c}/d` as `a/b/d` and `a/c/d`. One level of braces is all a client glob uses. */
36
+ export function expandBraces(glob) {
37
+ const found = /\{([^{}]*)\}/.exec(glob);
38
+ if (!found) return [glob];
39
+ return found[1].split(",").flatMap((choice) => expandBraces(glob.slice(0, found.index) + choice + glob.slice(found.index + found[0].length)));
40
+ }