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.
- package/package.json +8 -3
- package/src/cli/check.mjs +61 -0
- package/src/cli/child-run.mjs +39 -0
- package/src/cli/child-run.test.mjs +16 -0
- package/src/cli/ci-template.test.mjs +28 -0
- package/src/cli/codex-implement.mjs +72 -3
- package/src/cli/codex-implement.test.mjs +141 -4
- package/src/cli/dispatch-guard.mjs +24 -1
- package/src/cli/dispatch-guard.test.mjs +30 -0
- package/src/cli/dispatch-reminder.mjs +4 -4
- package/src/cli/dispatch-reminder.test.mjs +3 -3
- package/src/cli/dispatch-slot.mjs +12 -0
- package/src/cli/gate-slot.mjs +151 -0
- package/src/cli/gate-slot.test.mjs +90 -0
- package/src/cli/integrate.mjs +122 -0
- package/src/cli/integrate.test.mjs +94 -0
- package/src/cli/ledger.mjs +25 -3
- package/src/cli/ledger.test.mjs +9 -0
- package/src/cli/merge-guard.mjs +13 -3
- package/src/cli/merge-guard.test.mjs +24 -1
- package/src/cli/migrations.mjs +127 -0
- package/src/cli/migrations.test.mjs +94 -0
- package/src/cli/plugin-agents.test.mjs +35 -8
- package/src/cli/qc.mjs +44 -0
- package/src/cli/report-stop.mjs +3 -0
- package/src/cli/report-stop.test.mjs +8 -0
- package/src/cli/retry-failed.mjs +80 -0
- package/src/cli/retry-failed.test.mjs +51 -0
- package/src/cli/review-gate.mjs +16 -7
- package/src/cli/slot-guard.mjs +43 -0
- package/src/cli/slot-guard.test.mjs +28 -0
- package/src/cli/task-gate-review.test.mjs +10 -0
- package/src/cli/task-gate.mjs +39 -7
- package/src/cli/task-gate.test.mjs +45 -0
- package/src/cli/throwaway-db.mjs +127 -0
- package/src/cli/throwaway-db.test.mjs +83 -0
- package/src/cli/ui-reuse-hint.mjs +89 -0
- package/src/cli/ui-reuse-hint.test.mjs +60 -0
- package/src/cli/ui.mjs +181 -0
- package/src/cli/ui.test.mjs +137 -0
- package/src/cli/watch.mjs +211 -0
- package/src/cli/watch.test.mjs +246 -0
- package/src/config.mjs +27 -2
- package/src/descriptions.mjs +3 -0
- package/src/gates/contract-keys.mjs +33 -0
- package/src/gates/contract-keys.test.mjs +38 -0
- package/src/gates/migration-numbers.mjs +1 -1
- package/src/gates/migration-numbers.test.mjs +1 -0
- package/src/gates/ui-catalog.mjs +45 -0
- package/src/gates/ui-catalog.test.mjs +48 -0
- package/src/gates/ui-dupes.mjs +36 -0
- package/src/gates/ui-dupes.test.mjs +29 -0
- package/src/ui/catalog.mjs +87 -0
- package/src/ui/catalog.test.mjs +54 -0
- package/src/ui/class-sites.mjs +151 -0
- package/src/ui/class-sites.test.mjs +41 -0
- package/src/ui/codemod.mjs +138 -0
- package/src/ui/codemod.test.mjs +140 -0
- package/src/ui/components.mjs +176 -0
- package/src/ui/components.test.mjs +87 -0
- package/src/ui/dupes.mjs +141 -0
- package/src/ui/dupes.test.mjs +85 -0
- package/src/ui/find.mjs +45 -0
- package/src/ui/find.test.mjs +48 -0
- package/src/ui/options.mjs +40 -0
- package/src/ui/scan.mjs +78 -0
- package/src/ui/typescript.mjs +29 -0
- package/templates/github/workflows/ci.yml +54 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// The component catalog: every exported component under the configured roots, one markdown table per
|
|
2
|
+
// layer. It is generated and never edited by hand, so an agent reads it to find a component before it
|
|
3
|
+
// writes a new one.
|
|
4
|
+
|
|
5
|
+
import { extractComponents, layerOf } from "./components.mjs";
|
|
6
|
+
import { componentFileMatcher } from "./options.mjs";
|
|
7
|
+
|
|
8
|
+
const lf = (text) => text.replace(/\r\n/g, "\n");
|
|
9
|
+
const cell = (text) => text.replace(/\|/g, "\\|");
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param ts the TypeScript module
|
|
13
|
+
* @param options the resolved `ui` block
|
|
14
|
+
* @param {{path: string, contents: string}[]} files the listed source files, any of them
|
|
15
|
+
* @param {string} [featureDir] the path segment that marks a feature
|
|
16
|
+
* @returns {{name: string, path: string, line: number, props: string[], description: string, layer: string}[]}
|
|
17
|
+
*/
|
|
18
|
+
export function catalogEntries(ts, options, files, featureDir = "features") {
|
|
19
|
+
const inRoots = componentFileMatcher(options);
|
|
20
|
+
const entries = [];
|
|
21
|
+
for (const file of files) {
|
|
22
|
+
if (!inRoots(file.path) || !/\bexport\b/.test(file.contents)) continue;
|
|
23
|
+
for (const component of extractComponents(ts, file.path, file.contents)) {
|
|
24
|
+
entries.push({ ...component, layer: layerOf(file.path, options, featureDir) });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return entries.sort((a, b) => a.name.localeCompare(b.name) || a.path.localeCompare(b.path));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The layers in reading order: those configured, then `platform`, then each feature, then any other. */
|
|
31
|
+
function orderedLayers(layers, configured) {
|
|
32
|
+
const rank = (layer) => {
|
|
33
|
+
const named = configured.indexOf(layer);
|
|
34
|
+
if (named !== -1) return [0, named, layer];
|
|
35
|
+
if (layer === "platform") return [1, 0, layer];
|
|
36
|
+
return [layer.startsWith("feature:") ? 2 : 3, 0, layer];
|
|
37
|
+
};
|
|
38
|
+
return [...layers].sort((a, b) => {
|
|
39
|
+
const [ka, na, la] = rank(a);
|
|
40
|
+
const [kb, nb, lb] = rank(b);
|
|
41
|
+
return ka - kb || na - nb || la.localeCompare(lb);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {object[]} entries from `catalogEntries`
|
|
47
|
+
* @param {{layers: Record<string, string>, command: string}} options `command` is what writes the file
|
|
48
|
+
* @returns {string | null} null when there is no component, so no file is owed
|
|
49
|
+
*/
|
|
50
|
+
export function renderCatalog(entries, { layers, command }) {
|
|
51
|
+
if (entries.length === 0) return null;
|
|
52
|
+
const byLayer = Map.groupBy(entries, (entry) => entry.layer);
|
|
53
|
+
const sections = orderedLayers(byLayer.keys(), Object.keys(layers)).map((layer) => {
|
|
54
|
+
const rows = byLayer.get(layer).map((entry) => {
|
|
55
|
+
const props = entry.props.map((prop) => `\`${prop}\``).join(", ");
|
|
56
|
+
return `| \`${entry.name}\` | \`${entry.path}\` | ${props} | ${cell(entry.description) || "none"} |`;
|
|
57
|
+
});
|
|
58
|
+
return `## ${layer}\n\n| Component | Path | Props | Description |\n|---|---|---|---|\n${rows.join("\n")}`;
|
|
59
|
+
});
|
|
60
|
+
return [
|
|
61
|
+
`<!-- generated: ui-catalog. Run \`${command}\` to write this file; never edit it by hand. -->`,
|
|
62
|
+
"",
|
|
63
|
+
"# UI component catalog",
|
|
64
|
+
"",
|
|
65
|
+
"Find a component here before you write one. `qc ui find <words>` ranks these entries.",
|
|
66
|
+
"",
|
|
67
|
+
sections.join("\n\n"),
|
|
68
|
+
"",
|
|
69
|
+
"<!-- /generated -->",
|
|
70
|
+
"",
|
|
71
|
+
].join("\n");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** True when the file on disk is the text the scan produced. Both null is a repository with nothing to list. */
|
|
75
|
+
export function sameCatalog(actual, expected) {
|
|
76
|
+
if (actual === null || expected === null) return actual === expected;
|
|
77
|
+
return lf(actual) === lf(expected);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The baseline file's content: the components that have no sentence today, so the list only shrinks. */
|
|
81
|
+
export function baselineOf(entries) {
|
|
82
|
+
const undocumented = entries
|
|
83
|
+
.filter((entry) => entry.description === "")
|
|
84
|
+
.map((entry) => `${entry.path}#${entry.name}`)
|
|
85
|
+
.sort();
|
|
86
|
+
return { undocumented };
|
|
87
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { baselineOf, catalogEntries, renderCatalog, sameCatalog } from "./catalog.mjs";
|
|
4
|
+
import { loadTypeScript } from "./typescript.mjs";
|
|
5
|
+
|
|
6
|
+
const ts = loadTypeScript();
|
|
7
|
+
const options = {
|
|
8
|
+
componentRoots: ["frontend/src/platform/ui", "frontend/src/features/*/components"],
|
|
9
|
+
layers: { primitive: "frontend/src/platform/ui/primitives", pattern: "frontend/src/platform/ui/patterns" },
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const files = [
|
|
13
|
+
{ path: "frontend/src/platform/ui/primitives/button.tsx", contents: "/** A pressable control. */\nexport function Button({ label }: { label: string }) { return null; }\n" },
|
|
14
|
+
{ path: "frontend/src/platform/ui/patterns/empty-state.tsx", contents: "/** Says a list is empty | and why. */\nexport const EmptyState = () => null;\n" },
|
|
15
|
+
{ path: "frontend/src/features/photos/components/grid.tsx", contents: "export const Grid = () => null;\n" },
|
|
16
|
+
{ path: "frontend/src/features/photos/components/grid.test.tsx", contents: "export const NotListed = () => null;\n" },
|
|
17
|
+
{ path: "frontend/src/features/photos/components/grid.stories.tsx", contents: "export const AlsoNot = () => null;\n" },
|
|
18
|
+
{ path: "frontend/src/features/photos/api.tsx", contents: "export const OutsideRoots = () => null;\n" },
|
|
19
|
+
{ path: "frontend/src/platform/ui/shell.tsx", contents: "/** The app frame. */\nexport function Shell() { return null; }\n" },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
test("only exported components under the roots are listed, tests and stories skipped, each with its layer", () => {
|
|
23
|
+
const entries = catalogEntries(ts, options, files);
|
|
24
|
+
assert.deepEqual(
|
|
25
|
+
entries.map((entry) => [entry.name, entry.layer]),
|
|
26
|
+
[["Button", "primitive"], ["EmptyState", "pattern"], ["Grid", "feature:photos"], ["Shell", "platform"]],
|
|
27
|
+
);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test("the catalog is one table per layer, sorted by name, inside a generated region", () => {
|
|
31
|
+
const text = renderCatalog(catalogEntries(ts, options, files), { layers: options.layers, command: "pnpm codegen" });
|
|
32
|
+
assert.match(text, /^<!-- generated: ui-catalog\. .*pnpm codegen.* -->/);
|
|
33
|
+
assert.ok(text.trimEnd().endsWith("<!-- /generated -->"));
|
|
34
|
+
const order = [...text.matchAll(/^## (.+)$/gm)].map((found) => found[1]);
|
|
35
|
+
assert.deepEqual(order, ["primitive", "pattern", "platform", "feature:photos"]);
|
|
36
|
+
assert.match(text, /\| `Button` \| `frontend\/src\/platform\/ui\/primitives\/button\.tsx` \| `label` \| A pressable control\. \|/);
|
|
37
|
+
assert.match(text, /Says a list is empty \\\| and why\./);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("no component means no catalog text", () => {
|
|
41
|
+
assert.equal(renderCatalog([], { layers: {}, command: "pnpm codegen" }), null);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test("sameCatalog ignores line endings and a missing file differs", () => {
|
|
45
|
+
assert.equal(sameCatalog("a\r\nb\n", "a\nb\n"), true);
|
|
46
|
+
assert.equal(sameCatalog("a\n", "b\n"), false);
|
|
47
|
+
assert.equal(sameCatalog(null, "b\n"), false);
|
|
48
|
+
assert.equal(sameCatalog(null, null), true);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("the baseline lists each undocumented component as a sorted path and name", () => {
|
|
52
|
+
const entries = catalogEntries(ts, options, files);
|
|
53
|
+
assert.deepEqual(baselineOf(entries), { undocumented: ["frontend/src/features/photos/components/grid.tsx#Grid"] });
|
|
54
|
+
});
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Where a class token can sit in a source file, and nowhere else: string literals in a `className` or
|
|
2
|
+
// `class` attribute, in a call to a class callee, and in a `cva` variant object, plus the static parts of
|
|
3
|
+
// a template literal in those places. The codemod and the duplicate finder read the same sites, so they
|
|
4
|
+
// agree on what a class string is.
|
|
5
|
+
|
|
6
|
+
const CLASS_ATTRIBUTES = new Set(["className", "class"]);
|
|
7
|
+
|
|
8
|
+
function calleeName(ts, expression) {
|
|
9
|
+
if (ts.isIdentifier(expression)) return expression.text;
|
|
10
|
+
if (ts.isPropertyAccessExpression(expression)) return expression.name.text;
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The text spans of a string-like node, as source ranges inside its quotes or between its substitutions. */
|
|
15
|
+
function spansOf(ts, file, node) {
|
|
16
|
+
const start = node.getStart(file);
|
|
17
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
|
|
18
|
+
return [{ start: start + 1, end: node.getEnd() - 1, leftOpen: false, rightOpen: false }];
|
|
19
|
+
}
|
|
20
|
+
if (ts.isTemplateExpression(node)) {
|
|
21
|
+
const spans = [{ node: node.head, leftOpen: false, rightOpen: true, close: 2 }];
|
|
22
|
+
node.templateSpans.forEach((span, index) => {
|
|
23
|
+
const last = index === node.templateSpans.length - 1;
|
|
24
|
+
spans.push({ node: span.literal, leftOpen: true, rightOpen: !last, close: last ? 1 : 2 });
|
|
25
|
+
});
|
|
26
|
+
return spans.map(({ node: part, leftOpen, rightOpen, close }) => ({
|
|
27
|
+
start: part.getStart(file) + 1,
|
|
28
|
+
end: part.getEnd() - close,
|
|
29
|
+
leftOpen,
|
|
30
|
+
rightOpen,
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Every span of class text in a file.
|
|
38
|
+
* @returns {{start: number, end: number, leftOpen: boolean, rightOpen: boolean}[]} in source order, none twice
|
|
39
|
+
*/
|
|
40
|
+
export function classSpans(ts, file, callees) {
|
|
41
|
+
const callable = new Set(callees);
|
|
42
|
+
const found = new Map();
|
|
43
|
+
|
|
44
|
+
function take(node) {
|
|
45
|
+
for (const span of spansOf(ts, file, node)) found.set(span.start, span);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function propertyName(property) {
|
|
49
|
+
if (!ts.isPropertyAssignment(property)) return null;
|
|
50
|
+
const { name } = property;
|
|
51
|
+
return ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function propertyValue(object, wanted) {
|
|
55
|
+
if (!ts.isObjectLiteralExpression(object)) return [];
|
|
56
|
+
return object.properties.filter((p) => wanted.has(propertyName(p))).map((p) => p.initializer);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A node whose value is class text: a string, or an expression that yields one. A condition, a comparison
|
|
61
|
+
* operand and the argument of a call outside `classCallees` are not class text, so the walk stops there.
|
|
62
|
+
* `objectKeys` reads the keys of an object, as `clsx({ "p-2": on })` does.
|
|
63
|
+
*/
|
|
64
|
+
function collectValue(node, objectKeys) {
|
|
65
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
|
|
66
|
+
take(node);
|
|
67
|
+
} else if (ts.isTemplateExpression(node)) {
|
|
68
|
+
take(node);
|
|
69
|
+
for (const span of node.templateSpans) collectValue(span.expression, objectKeys);
|
|
70
|
+
} else if (
|
|
71
|
+
ts.isParenthesizedExpression(node) ||
|
|
72
|
+
ts.isAsExpression(node) ||
|
|
73
|
+
ts.isSatisfiesExpression(node) ||
|
|
74
|
+
ts.isNonNullExpression(node) ||
|
|
75
|
+
ts.isJsxExpression(node)
|
|
76
|
+
) {
|
|
77
|
+
if (node.expression) collectValue(node.expression, objectKeys);
|
|
78
|
+
} else if (ts.isConditionalExpression(node)) {
|
|
79
|
+
collectValue(node.whenTrue, objectKeys);
|
|
80
|
+
collectValue(node.whenFalse, objectKeys);
|
|
81
|
+
} else if (ts.isBinaryExpression(node)) {
|
|
82
|
+
const kind = node.operatorToken.kind;
|
|
83
|
+
const logical =
|
|
84
|
+
kind === ts.SyntaxKind.AmpersandAmpersandToken ||
|
|
85
|
+
kind === ts.SyntaxKind.BarBarToken ||
|
|
86
|
+
kind === ts.SyntaxKind.QuestionQuestionToken;
|
|
87
|
+
if (logical) collectValue(node.right, objectKeys);
|
|
88
|
+
} else if (ts.isArrayLiteralExpression(node)) {
|
|
89
|
+
for (const element of node.elements) collectValue(element, objectKeys);
|
|
90
|
+
} else if (ts.isObjectLiteralExpression(node) && objectKeys) {
|
|
91
|
+
for (const property of node.properties) {
|
|
92
|
+
if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) take(property.name);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The class text of a `cva` call: the base, the variant values, and the class of each compound variant. */
|
|
98
|
+
function collectVariants(call) {
|
|
99
|
+
const [base, config] = call.arguments;
|
|
100
|
+
if (base) collectValue(base, false);
|
|
101
|
+
if (!config) return;
|
|
102
|
+
for (const variants of propertyValue(config, new Set(["variants"]))) {
|
|
103
|
+
if (!ts.isObjectLiteralExpression(variants)) continue;
|
|
104
|
+
for (const group of variants.properties) {
|
|
105
|
+
if (!ts.isPropertyAssignment(group) || !ts.isObjectLiteralExpression(group.initializer)) continue;
|
|
106
|
+
for (const option of group.initializer.properties) {
|
|
107
|
+
if (ts.isPropertyAssignment(option)) collectValue(option.initializer, false);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
for (const compound of propertyValue(config, new Set(["compoundVariants"]))) {
|
|
112
|
+
if (!ts.isArrayLiteralExpression(compound)) continue;
|
|
113
|
+
for (const entry of compound.elements) {
|
|
114
|
+
for (const value of propertyValue(entry, CLASS_ATTRIBUTES)) collectValue(value, false);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function visit(node) {
|
|
120
|
+
if (ts.isJsxAttribute(node) && CLASS_ATTRIBUTES.has(node.name.getText(file)) && node.initializer) {
|
|
121
|
+
collectValue(node.initializer, false);
|
|
122
|
+
} else if (ts.isCallExpression(node)) {
|
|
123
|
+
const name = calleeName(ts, node.expression);
|
|
124
|
+
if (name === "cva" && callable.has(name)) collectVariants(node);
|
|
125
|
+
else if (name !== null && callable.has(name)) {
|
|
126
|
+
for (const argument of node.arguments) collectValue(argument, true);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
ts.forEachChild(node, visit);
|
|
130
|
+
}
|
|
131
|
+
visit(file);
|
|
132
|
+
return [...found.values()].sort((a, b) => a.start - b.start);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The whitespace-separated tokens of one span, each with its source range. A token cut by a substitution is left out. */
|
|
136
|
+
export function tokensOfSpan(text, span) {
|
|
137
|
+
const raw = text.slice(span.start, span.end);
|
|
138
|
+
const out = [];
|
|
139
|
+
for (const found of raw.matchAll(/\S+/g)) {
|
|
140
|
+
const touchesLeft = span.leftOpen && found.index === 0;
|
|
141
|
+
const touchesRight = span.rightOpen && found.index + found[0].length === raw.length;
|
|
142
|
+
if (touchesLeft || touchesRight || found[0].includes("\\")) continue;
|
|
143
|
+
out.push({ text: found[0], start: span.start + found.index, end: span.start + found.index + found[0].length });
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Every class token of a file, with its range, in source order. */
|
|
149
|
+
export function classTokensOf(ts, file, callees) {
|
|
150
|
+
return classSpans(ts, file, callees).flatMap((span) => tokensOfSpan(file.text, span));
|
|
151
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { classTokensOf } from "./class-sites.mjs";
|
|
4
|
+
import { loadTypeScript, parseSource } from "./typescript.mjs";
|
|
5
|
+
|
|
6
|
+
const ts = loadTypeScript();
|
|
7
|
+
const CALLEES = ["cn", "clsx", "cva", "twMerge"];
|
|
8
|
+
const tokens = (text) => classTokensOf(ts, parseSource(ts, "a.tsx", text), CALLEES).map((one) => one.text);
|
|
9
|
+
|
|
10
|
+
test("a className string, a className expression and a class attribute are sites", () => {
|
|
11
|
+
assert.deepEqual(
|
|
12
|
+
tokens(`const a = <div className="p-2 flex" class='x' title="not-a-class" />; const b = <p className={cond ? "m-1" : "m-2"} />;`),
|
|
13
|
+
["p-2", "flex", "x", "m-1", "m-2"],
|
|
14
|
+
);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("a string in a call to a class callee is a site, a string in another call is not", () => {
|
|
18
|
+
assert.deepEqual(tokens(`const a = cn("p-2", cond && "m-1", { "b-1": on }); const b = other("p-9");`), ["p-2", "m-1", "b-1"]);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("a cva call yields its base and its variant strings but not its variant names or its default variants", () => {
|
|
22
|
+
assert.deepEqual(
|
|
23
|
+
tokens(`const v = cva("base-1", { variants: { size: { "sm": "text-xs", md: "text-sm" } }, defaultVariants: { size: "md" } });`),
|
|
24
|
+
["base-1", "text-xs", "text-sm"],
|
|
25
|
+
);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("the static parts of a template literal are sites, and a token touching a substitution is skipped", () => {
|
|
29
|
+
assert.deepEqual(tokens("const a = cn(`p-2 ${x} m-1 w-${n} flex`, `solo-1`);"), ["p-2", "m-1", "flex", "solo-1"]);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("a string outside a class position and a type literal are not sites", () => {
|
|
33
|
+
assert.deepEqual(tokens(`const label = "p-2"; type T = "m-1"; const c = <i data-x="w-1" />;`), []);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("each token carries its source range, so an edit never reprints the file", () => {
|
|
37
|
+
const text = `const a = <i className="aa bb" />;`;
|
|
38
|
+
const [first, second] = classTokensOf(ts, parseSource(ts, "a.tsx", text), CALLEES);
|
|
39
|
+
assert.equal(text.slice(first.start, first.end), "aa");
|
|
40
|
+
assert.equal(text.slice(second.start, second.end), "bb");
|
|
41
|
+
});
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// A refactor that rewrites class tokens across a frontend in one command. A token is replaced whole,
|
|
2
|
+
// keeping its variant prefixes and its `!` modifier. Only class sites change (class-sites.mjs), and the
|
|
3
|
+
// edit is by source range, so the rest of the file keeps its formatting.
|
|
4
|
+
|
|
5
|
+
import { classTokensOf } from "./class-sites.mjs";
|
|
6
|
+
import { parseSource } from "./typescript.mjs";
|
|
7
|
+
|
|
8
|
+
const BREAKS_A_STRING = /["'`\\\n\r]|\$\{/;
|
|
9
|
+
const ARBITRARY = /^-?[a-z][a-z0-9-]*-\[[^\]\s]+\](?:\/[\w.%[\]-]+)?$/i;
|
|
10
|
+
|
|
11
|
+
/** Splits `md:hover:!text-[11px]` into its variant prefix, its `!` modifier and its core. A colon in brackets is no variant. */
|
|
12
|
+
export function splitToken(token) {
|
|
13
|
+
let depth = 0;
|
|
14
|
+
let cut = -1;
|
|
15
|
+
for (let index = 0; index < token.length; index += 1) {
|
|
16
|
+
const character = token[index];
|
|
17
|
+
if (character === "[" || character === "(") depth += 1;
|
|
18
|
+
else if (character === "]" || character === ")") depth -= 1;
|
|
19
|
+
else if (character === ":" && depth === 0) cut = index;
|
|
20
|
+
}
|
|
21
|
+
const prefix = token.slice(0, cut + 1);
|
|
22
|
+
let core = token.slice(cut + 1);
|
|
23
|
+
const lead = core.startsWith("!") ? "!" : "";
|
|
24
|
+
core = core.slice(lead.length);
|
|
25
|
+
const trail = !lead && core.endsWith("!") ? "!" : "";
|
|
26
|
+
return { prefix, lead, trail, core: trail ? core.slice(0, -1) : core };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The token after the map, or the token itself when the map holds neither it nor its core. */
|
|
30
|
+
export function rewriteToken(token, map) {
|
|
31
|
+
const whole = Object.hasOwn(map, token) ? map[token] : null;
|
|
32
|
+
const { prefix, lead, trail, core } = splitToken(token);
|
|
33
|
+
const replacement = whole ?? (Object.hasOwn(map, core) ? map[core] : null);
|
|
34
|
+
if (replacement === null) return token;
|
|
35
|
+
if (whole !== null) return whole;
|
|
36
|
+
return replacement
|
|
37
|
+
.split(/\s+/)
|
|
38
|
+
.filter(Boolean)
|
|
39
|
+
.map((part) => `${prefix}${lead}${part}${trail}`)
|
|
40
|
+
.join(" ");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The map `--map` carries: class tokens to the tokens that replace them. */
|
|
44
|
+
export function parseMap(json) {
|
|
45
|
+
let map;
|
|
46
|
+
try {
|
|
47
|
+
map = JSON.parse(json);
|
|
48
|
+
} catch (cause) {
|
|
49
|
+
throw new Error(`--map is not valid JSON: ${cause.message}`);
|
|
50
|
+
}
|
|
51
|
+
if (map === null || typeof map !== "object" || Array.isArray(map)) throw new Error("--map is a JSON object of token to token");
|
|
52
|
+
for (const [from, to] of Object.entries(map)) {
|
|
53
|
+
if (typeof to !== "string") throw new Error(`--map: the replacement of ${from} is not a string`);
|
|
54
|
+
if (BREAKS_A_STRING.test(to) || BREAKS_A_STRING.test(from)) {
|
|
55
|
+
throw new Error(`--map: ${from} or its replacement holds a quote, a backtick, a backslash or a line break`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return map;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @returns {{text: string, count: number}} the source with each class token mapped, and how many changed */
|
|
62
|
+
export function codemodSource(ts, name, text, map, callees) {
|
|
63
|
+
const edits = [];
|
|
64
|
+
for (const token of classTokensOf(ts, parseSource(ts, name, text), callees)) {
|
|
65
|
+
const next = rewriteToken(token.text, map);
|
|
66
|
+
if (next !== token.text) edits.push({ ...token, next });
|
|
67
|
+
}
|
|
68
|
+
let out = text;
|
|
69
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) out = out.slice(0, edit.start) + edit.next + out.slice(edit.end);
|
|
70
|
+
return { text: out, count: edits.length };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** @returns {Map<string, number>} each arbitrary-value token of a source with its uses, in first-use order */
|
|
74
|
+
export function arbitraryTokens(ts, name, text, callees) {
|
|
75
|
+
const counts = new Map();
|
|
76
|
+
for (const token of classTokensOf(ts, parseSource(ts, name, text), callees)) {
|
|
77
|
+
const { core } = splitToken(token.text);
|
|
78
|
+
if (ARBITRARY.test(core)) counts.set(core, (counts.get(core) ?? 0) + 1);
|
|
79
|
+
}
|
|
80
|
+
return counts;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Each custom property declared inside an `@theme` block of a stylesheet. */
|
|
84
|
+
export function themeVariables(css) {
|
|
85
|
+
const variables = [];
|
|
86
|
+
for (const block of css.matchAll(/@theme\b[^{]*\{/g)) {
|
|
87
|
+
let depth = 1;
|
|
88
|
+
let index = block.index + block[0].length;
|
|
89
|
+
const start = index;
|
|
90
|
+
while (index < css.length && depth > 0) {
|
|
91
|
+
if (css[index] === "{") depth += 1;
|
|
92
|
+
else if (css[index] === "}") depth -= 1;
|
|
93
|
+
index += 1;
|
|
94
|
+
}
|
|
95
|
+
for (const found of css.slice(start, index - 1).matchAll(/(--[\w-]+)\s*:\s*([^;{}]+);/g)) {
|
|
96
|
+
variables.push({ name: found[1], value: found[2].trim() });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return variables;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A comparable value: lowercase, one space between parts, and a `rem` length as pixels. */
|
|
103
|
+
function comparable(value) {
|
|
104
|
+
const flat = value.trim().toLowerCase().replace(/\s*!important$/, "").replace(/\s+/g, " ");
|
|
105
|
+
return flat.replace(/^(-?\d*\.?\d+)rem$/, (_, number) => `${Math.round(Number(number) * 16 * 1e4) / 1e4}px`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const NAMESPACES = {
|
|
109
|
+
text: ["text", "color"],
|
|
110
|
+
rounded: ["radius"],
|
|
111
|
+
shadow: ["shadow"],
|
|
112
|
+
leading: ["leading"],
|
|
113
|
+
tracking: ["tracking"],
|
|
114
|
+
font: ["font"],
|
|
115
|
+
blur: ["blur"],
|
|
116
|
+
bg: ["color"],
|
|
117
|
+
border: ["color"],
|
|
118
|
+
ring: ["color"],
|
|
119
|
+
fill: ["color"],
|
|
120
|
+
stroke: ["color"],
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Each arbitrary token with the theme variable that holds its value, most used first.
|
|
125
|
+
* @param {Map<string, number>} counts
|
|
126
|
+
* @param {{name: string, value: string}[]} theme
|
|
127
|
+
*/
|
|
128
|
+
export function suggest(counts, theme) {
|
|
129
|
+
const ordered = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
|
|
130
|
+
return ordered.map(([token, count]) => {
|
|
131
|
+
const [, utility, inside] = /^-?([a-z][a-z0-9-]*?)-\[([^\]]+)\]/i.exec(token) ?? [];
|
|
132
|
+
const wanted = inside === undefined ? null : comparable(inside.replace(/_/g, " "));
|
|
133
|
+
const same = theme.filter((one) => wanted !== null && comparable(one.value) === wanted);
|
|
134
|
+
const spaces = NAMESPACES[utility?.split("-")[0]] ?? [];
|
|
135
|
+
const best = same.find((one) => spaces.some((space) => one.name.startsWith(`--${space}-`))) ?? same[0] ?? null;
|
|
136
|
+
return { token, count, variable: best?.name ?? null, value: best?.value ?? null };
|
|
137
|
+
});
|
|
138
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import {
|
|
4
|
+
arbitraryTokens,
|
|
5
|
+
codemodSource,
|
|
6
|
+
parseMap,
|
|
7
|
+
rewriteToken,
|
|
8
|
+
splitToken,
|
|
9
|
+
suggest,
|
|
10
|
+
themeVariables,
|
|
11
|
+
} from "./codemod.mjs";
|
|
12
|
+
import { loadTypeScript } from "./typescript.mjs";
|
|
13
|
+
|
|
14
|
+
const ts = loadTypeScript();
|
|
15
|
+
const CALLEES = ["cn", "clsx", "cva", "twMerge"];
|
|
16
|
+
const MAP = { "text-[11px]": "text-2xs", "rounded-[4px]": "rounded-sm" };
|
|
17
|
+
const run = (text, map = MAP) => codemodSource(ts, "a.tsx", text, map, CALLEES);
|
|
18
|
+
|
|
19
|
+
test("splitToken finds the variant prefix, the important modifier and the core, ignoring a colon in brackets", () => {
|
|
20
|
+
assert.deepEqual(splitToken("md:hover:!text-[11px]"), { prefix: "md:hover:", lead: "!", trail: "", core: "text-[11px]" });
|
|
21
|
+
assert.deepEqual(splitToken("dark:text-[11px]!"), { prefix: "dark:", lead: "", trail: "!", core: "text-[11px]" });
|
|
22
|
+
assert.deepEqual(splitToken("[&:hover]:p-[4px]"), { prefix: "[&:hover]:", lead: "", trail: "", core: "p-[4px]" });
|
|
23
|
+
assert.deepEqual(splitToken("data-[state=open]:bg-[url(a:b)]"), { prefix: "data-[state=open]:", lead: "", trail: "", core: "bg-[url(a:b)]" });
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("a whole token is rewritten and its variant chain and ! modifier are kept", () => {
|
|
27
|
+
assert.equal(rewriteToken("text-[11px]", MAP), "text-2xs");
|
|
28
|
+
assert.equal(rewriteToken("md:hover:dark:text-[11px]", MAP), "md:hover:dark:text-2xs");
|
|
29
|
+
assert.equal(rewriteToken("!rounded-[4px]", MAP), "!rounded-sm");
|
|
30
|
+
assert.equal(rewriteToken("sm:rounded-[4px]!", MAP), "sm:rounded-sm!");
|
|
31
|
+
assert.equal(rewriteToken("flex", MAP), "flex");
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("a token that only starts with a mapped token, or holds one, stays", () => {
|
|
35
|
+
assert.equal(rewriteToken("text-[11px]/50", MAP), "text-[11px]/50");
|
|
36
|
+
assert.equal(rewriteToken("text-[11px]-x", MAP), "text-[11px]-x");
|
|
37
|
+
assert.equal(rewriteToken("my-text-[11px]", MAP), "my-text-[11px]");
|
|
38
|
+
assert.equal(rewriteToken("text-[11px]", { "text-[11]": "x" }), "text-[11px]");
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("a replacement of several tokens keeps the prefix on each", () => {
|
|
42
|
+
assert.equal(rewriteToken("md:text-[11px]", { "text-[11px]": "text-xs leading-4" }), "md:text-xs md:leading-4");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("a className attribute string is rewritten by range and the rest of the file is untouched", () => {
|
|
46
|
+
const text = `export const A = () => (\n <div className="flex text-[11px] md:rounded-[4px]" id="x">\n text-[11px]\n </div>\n);\n`;
|
|
47
|
+
const out = run(text);
|
|
48
|
+
assert.equal(out.count, 2);
|
|
49
|
+
assert.equal(out.text, text.replace("text-[11px] md:rounded-[4px]", "text-2xs md:rounded-sm"));
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("a cn call, a cva object and a clsx key are rewritten, and a string elsewhere is not", () => {
|
|
53
|
+
const text = [
|
|
54
|
+
`const a = cn("text-[11px] p-2", cond && "!rounded-[4px]", { "rounded-[4px]": on });`,
|
|
55
|
+
`const v = cva("text-[11px]", { variants: { size: { sm: "rounded-[4px]" } } });`,
|
|
56
|
+
`const label = "text-[11px]";`,
|
|
57
|
+
`const b = other("text-[11px]");`,
|
|
58
|
+
].join("\n");
|
|
59
|
+
const out = run(text);
|
|
60
|
+
assert.equal(out.count, 5);
|
|
61
|
+
assert.equal(
|
|
62
|
+
out.text,
|
|
63
|
+
[
|
|
64
|
+
`const a = cn("text-2xs p-2", cond && "!rounded-sm", { "rounded-sm": on });`,
|
|
65
|
+
`const v = cva("text-2xs", { variants: { size: { sm: "rounded-sm" } } });`,
|
|
66
|
+
`const label = "text-[11px]";`,
|
|
67
|
+
`const b = other("text-[11px]");`,
|
|
68
|
+
].join("\n"),
|
|
69
|
+
);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("a string that is not class text stays, and a real class beside it changes", () => {
|
|
73
|
+
const map = { shadow: "shadow-sm" };
|
|
74
|
+
const text = [
|
|
75
|
+
`const v = cva("p-1", {`,
|
|
76
|
+
` variants: { elevation: { shadow: "shadow" } },`,
|
|
77
|
+
` compoundVariants: [{ elevation: "shadow", class: "p-3" }],`,
|
|
78
|
+
` defaultVariants: { elevation: "shadow" },`,
|
|
79
|
+
`});`,
|
|
80
|
+
`const a = cn(e === "shadow" && "p-2");`,
|
|
81
|
+
`const b = cn(lookup("shadow"));`,
|
|
82
|
+
`const c = cn(on ? "shadow" : "p-2", list.includes("shadow") || "shadow", ["shadow"], { "shadow": on });`,
|
|
83
|
+
].join("\n");
|
|
84
|
+
const out = run(text, map);
|
|
85
|
+
assert.equal(
|
|
86
|
+
out.text,
|
|
87
|
+
[
|
|
88
|
+
`const v = cva("p-1", {`,
|
|
89
|
+
` variants: { elevation: { shadow: "shadow-sm" } },`,
|
|
90
|
+
` compoundVariants: [{ elevation: "shadow", class: "p-3" }],`,
|
|
91
|
+
` defaultVariants: { elevation: "shadow" },`,
|
|
92
|
+
`});`,
|
|
93
|
+
`const a = cn(e === "shadow" && "p-2");`,
|
|
94
|
+
`const b = cn(lookup("shadow"));`,
|
|
95
|
+
`const c = cn(on ? "shadow-sm" : "p-2", list.includes("shadow") || "shadow-sm", ["shadow-sm"], { "shadow-sm": on });`,
|
|
96
|
+
].join("\n"),
|
|
97
|
+
);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("a compoundVariants class is rewritten and its selector is not", () => {
|
|
101
|
+
const out = run(`const v = cva("a", { compoundVariants: [{ size: "text-[11px]", className: "text-[11px]" }] });`);
|
|
102
|
+
assert.equal(out.text, `const v = cva("a", { compoundVariants: [{ size: "text-[11px]", className: "text-2xs" }] });`);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("the static parts of a template literal are rewritten and a token cut by a substitution is not", () => {
|
|
106
|
+
const out = run("const a = cn(`text-[11px] ${x} rounded-[4px] text-[11px]${y}`);");
|
|
107
|
+
assert.equal(out.text, "const a = cn(`text-2xs ${x} rounded-sm text-[11px]${y}`);");
|
|
108
|
+
assert.equal(out.count, 2);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test("a map is parsed from JSON and refuses a replacement that would break a string", () => {
|
|
112
|
+
assert.deepEqual(parseMap('{"a-[1px]":"a-px"}'), { "a-[1px]": "a-px" });
|
|
113
|
+
assert.throws(() => parseMap("[]"), /object/);
|
|
114
|
+
assert.throws(() => parseMap('{"a":1}'), /string/);
|
|
115
|
+
assert.throws(() => parseMap('{"a":"b\\"c"}'), /quote|backtick|backslash/);
|
|
116
|
+
assert.throws(() => parseMap("{"), /JSON/);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("arbitraryTokens counts each arbitrary-value core once per use, variants and ! stripped", () => {
|
|
120
|
+
const counts = arbitraryTokens(ts, "a.tsx", `const a = <i className="text-[11px] md:text-[11px] !w-[10px] flex [mask-type:alpha] bg-[#fff]/50" />;`, CALLEES);
|
|
121
|
+
assert.deepEqual([...counts], [["text-[11px]", 2], ["w-[10px]", 1], ["bg-[#fff]/50", 1]]);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("themeVariables reads each @theme block and suggest matches a value, rem against px", () => {
|
|
125
|
+
const css = `@import "tailwindcss";\n@theme inline {\n --text-2xs: 0.6875rem;\n --radius-sm: 4px;\n --color-brand: #FFF;\n --nested: { }\n}\n.x { --text-9: 9px; }\n`;
|
|
126
|
+
const theme = themeVariables(css);
|
|
127
|
+
assert.deepEqual(theme.map((v) => v.name), ["--text-2xs", "--radius-sm", "--color-brand"]);
|
|
128
|
+
const lines = suggest(new Map([["text-[11px]", 14], ["rounded-[4px]", 3], ["bg-[#fff]", 2], ["w-[10px]", 1]]), theme);
|
|
129
|
+
assert.deepEqual(lines, [
|
|
130
|
+
{ token: "text-[11px]", count: 14, variable: "--text-2xs", value: "0.6875rem" },
|
|
131
|
+
{ token: "rounded-[4px]", count: 3, variable: "--radius-sm", value: "4px" },
|
|
132
|
+
{ token: "bg-[#fff]", count: 2, variable: "--color-brand", value: "#FFF" },
|
|
133
|
+
{ token: "w-[10px]", count: 1, variable: null, value: null },
|
|
134
|
+
]);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test("without a theme the suggestion lists the tokens alone, by count then name", () => {
|
|
138
|
+
const lines = suggest(new Map([["b-[1px]", 2], ["a-[1px]", 2], ["c-[1px]", 5]]), []);
|
|
139
|
+
assert.deepEqual(lines.map((line) => line.token), ["c-[1px]", "a-[1px]", "b-[1px]"]);
|
|
140
|
+
});
|