architecture-harness 0.21.2 → 0.23.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 (107) hide show
  1. package/package.json +16 -4
  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/cli.test.mjs +6 -1
  7. package/src/cli/codex-implement.mjs +79 -5
  8. package/src/cli/codex-implement.test.mjs +170 -4
  9. package/src/cli/dispatch-guard.mjs +24 -1
  10. package/src/cli/dispatch-guard.test.mjs +30 -0
  11. package/src/cli/dispatch-reminder.mjs +7 -4
  12. package/src/cli/dispatch-reminder.test.mjs +8 -4
  13. package/src/cli/dispatch-slot.mjs +12 -0
  14. package/src/cli/gate-slot.mjs +151 -0
  15. package/src/cli/gate-slot.test.mjs +90 -0
  16. package/src/cli/git-hooks.test.mjs +5 -0
  17. package/src/cli/integrate.mjs +122 -0
  18. package/src/cli/integrate.test.mjs +94 -0
  19. package/src/cli/ledger.mjs +25 -3
  20. package/src/cli/ledger.test.mjs +9 -0
  21. package/src/cli/merge-guard.mjs +13 -3
  22. package/src/cli/merge-guard.test.mjs +24 -1
  23. package/src/cli/migrations.mjs +127 -0
  24. package/src/cli/migrations.test.mjs +94 -0
  25. package/src/cli/plugin-agents.test.mjs +35 -8
  26. package/src/cli/qc.mjs +58 -1
  27. package/src/cli/report-stop.mjs +3 -0
  28. package/src/cli/report-stop.test.mjs +8 -0
  29. package/src/cli/retry-failed.mjs +80 -0
  30. package/src/cli/retry-failed.test.mjs +51 -0
  31. package/src/cli/review-gate.mjs +16 -7
  32. package/src/cli/screens-discovery.mjs +60 -0
  33. package/src/cli/screens.mjs +84 -0
  34. package/src/cli/slot-guard.mjs +43 -0
  35. package/src/cli/slot-guard.test.mjs +28 -0
  36. package/src/cli/stack.mjs +14 -0
  37. package/src/cli/task-gate-review.test.mjs +10 -0
  38. package/src/cli/task-gate.mjs +39 -7
  39. package/src/cli/task-gate.test.mjs +45 -0
  40. package/src/cli/throwaway-db.mjs +127 -0
  41. package/src/cli/throwaway-db.test.mjs +83 -0
  42. package/src/cli/ui-reuse-hint.mjs +89 -0
  43. package/src/cli/ui-reuse-hint.test.mjs +60 -0
  44. package/src/cli/ui.mjs +181 -0
  45. package/src/cli/ui.test.mjs +137 -0
  46. package/src/cli/watch.mjs +211 -0
  47. package/src/cli/watch.test.mjs +246 -0
  48. package/src/config.mjs +27 -2
  49. package/src/descriptions.mjs +3 -0
  50. package/src/gates/contract-keys.mjs +33 -0
  51. package/src/gates/contract-keys.test.mjs +38 -0
  52. package/src/gates/migration-numbers.mjs +1 -1
  53. package/src/gates/migration-numbers.test.mjs +1 -0
  54. package/src/gates/ui-catalog.mjs +45 -0
  55. package/src/gates/ui-catalog.test.mjs +48 -0
  56. package/src/gates/ui-dupes.mjs +36 -0
  57. package/src/gates/ui-dupes.test.mjs +29 -0
  58. package/src/screens/auth-context.test.mjs +41 -0
  59. package/src/screens/auth-run.test.mjs +144 -0
  60. package/src/screens/auth.mjs +223 -0
  61. package/src/screens/auth.test.mjs +76 -0
  62. package/src/screens/capture-idle.test.mjs +26 -0
  63. package/src/screens/capture.browser-test.mjs +73 -0
  64. package/src/screens/capture.mjs +175 -0
  65. package/src/screens/capture.test.mjs +28 -0
  66. package/src/screens/catalog.browser-test.mjs +32 -0
  67. package/src/screens/catalog.mjs +72 -0
  68. package/src/screens/catalog.test.mjs +36 -0
  69. package/src/screens/compare.mjs +40 -0
  70. package/src/screens/compare.test.mjs +30 -0
  71. package/src/screens/discovery.browser-test.mjs +29 -0
  72. package/src/screens/discovery.mjs +158 -0
  73. package/src/screens/discovery.test.mjs +27 -0
  74. package/src/screens/inventory.mjs +69 -0
  75. package/src/screens/inventory.test.mjs +10 -0
  76. package/src/screens/map.mjs +63 -0
  77. package/src/screens/map.test.mjs +35 -0
  78. package/src/screens/open.browser-test.mjs +50 -0
  79. package/src/screens/regions.mjs +137 -0
  80. package/src/screens/regions.test.mjs +38 -0
  81. package/src/screens/session-files.mjs +39 -0
  82. package/src/screens/session-files.test.mjs +39 -0
  83. package/src/screens/setup.browser-test.mjs +49 -0
  84. package/src/screens/setup.mjs +78 -0
  85. package/src/screens/stack-auth.browser-test.mjs +30 -0
  86. package/src/screens/stack-auth.mjs +106 -0
  87. package/src/screens/stack-auth.test.mjs +65 -0
  88. package/src/screens/write-guard.mjs +26 -0
  89. package/src/stack/stack.mjs +131 -0
  90. package/src/stack/stack.test.mjs +40 -0
  91. package/src/stack/supervisor.mjs +30 -0
  92. package/src/ui/catalog.mjs +87 -0
  93. package/src/ui/catalog.test.mjs +54 -0
  94. package/src/ui/class-sites.mjs +151 -0
  95. package/src/ui/class-sites.test.mjs +41 -0
  96. package/src/ui/codemod.mjs +138 -0
  97. package/src/ui/codemod.test.mjs +140 -0
  98. package/src/ui/components.mjs +176 -0
  99. package/src/ui/components.test.mjs +87 -0
  100. package/src/ui/dupes.mjs +141 -0
  101. package/src/ui/dupes.test.mjs +85 -0
  102. package/src/ui/find.mjs +45 -0
  103. package/src/ui/find.test.mjs +48 -0
  104. package/src/ui/options.mjs +40 -0
  105. package/src/ui/scan.mjs +78 -0
  106. package/src/ui/typescript.mjs +29 -0
  107. package/templates/github/workflows/ci.yml +54 -0
@@ -0,0 +1,83 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { randomBytes } from "node:crypto";
3
+ import { test } from "node:test";
4
+ import { dockerRunArgs, fillEnv, freePort, runThrowawayDb, throwawayDefaults } from "./throwaway-db.mjs";
5
+
6
+ test("a free port skips each port to avoid", async () => {
7
+ const ports = [5432, 55001];
8
+ assert.equal(await freePort([5432], async () => ports.shift()), 55001);
9
+ });
10
+
11
+ test("the OS hands out a real free port that is never 5432", async () => {
12
+ const port = await freePort([5432]);
13
+ assert.ok(Number.isInteger(port) && port > 0 && port !== 5432);
14
+ });
15
+
16
+ test("the env template fills the url, the port, and the rest, and keeps a literal", () => {
17
+ const env = fillEnv({ DATABASE_URL: "{url}", PGPORT: "{port}", LIVE: "1" }, { url: "postgres://u:p@127.0.0.1:55001/app", port: 55001 });
18
+ assert.deepEqual(env, { DATABASE_URL: "postgres://u:p@127.0.0.1:55001/app", PGPORT: "55001", LIVE: "1" });
19
+ });
20
+
21
+ test("the container publishes only on the loopback address", () => {
22
+ const args = dockerRunArgs(throwawayDefaults, "qc-throwaway-1", 55001, generated);
23
+ assert.ok(args.includes("127.0.0.1:55001:5432"));
24
+ assert.equal(args.at(-1), throwawayDefaults.image);
25
+ });
26
+
27
+ const generated = randomBytes(8).toString("hex");
28
+
29
+ /** A docker that answers each call, and records it. */
30
+ function fakeDocker(calls, { readyAfter = 1, runCode = 0 } = {}) {
31
+ let checks = 0;
32
+ return (args) => {
33
+ calls.push(args.slice(0, 2).join(" "));
34
+ if (args[0] === "run") return { code: runCode, err: runCode === 0 ? "" : "no daemon" };
35
+ if (args[0] === "exec") return { code: (checks += 1) > readyAfter ? 0 : 1, err: "" };
36
+ return { code: 0, err: "" };
37
+ };
38
+ }
39
+
40
+ test("the command runs on its own database on a free port, and the container is removed after it", async () => {
41
+ const calls = [];
42
+ let seen = null;
43
+ const code = await runThrowawayDb({ throwawayDb: { env: { LIVE_DB: "1" } } }, ["--", "pnpm", "vitest", "run", "a.test.ts"], {
44
+ docker: fakeDocker(calls),
45
+ open: async () => 55002,
46
+ sleep: async () => {},
47
+ run: async (command, env) => {
48
+ seen = { command, env };
49
+ return 5;
50
+ },
51
+ env: {},
52
+ say: () => {},
53
+ name: "qc-throwaway-test",
54
+ password: generated,
55
+ });
56
+ assert.equal(code, 5);
57
+ assert.equal(seen.command, "pnpm vitest run a.test.ts");
58
+ assert.equal(seen.env.DATABASE_URL, `postgres://postgres:${encodeURIComponent(generated)}@127.0.0.1:55002/app`);
59
+ assert.equal(seen.env.LIVE_DB, "1");
60
+ assert.deepEqual(calls, ["run --detach", "exec qc-throwaway-test", "exec qc-throwaway-test", "rm --force"]);
61
+ });
62
+
63
+ test("an explicit port to avoid is refused, and a docker that cannot start removes nothing", async () => {
64
+ const deps = { docker: fakeDocker([]), open: async () => 55003, sleep: async () => {}, run: async () => 0, env: {}, say: () => {} };
65
+ assert.equal(await runThrowawayDb({}, ["--port", "5432", "--", "x"], deps), 2);
66
+ const calls = [];
67
+ assert.equal(await runThrowawayDb({}, ["--", "x"], { ...deps, docker: fakeDocker(calls, { runCode: 1 }) }), 1);
68
+ assert.deepEqual(calls, ["run --detach"]);
69
+ });
70
+
71
+ test("port 5432 stays avoided when the config lists other ports to avoid", async () => {
72
+ const deps = { docker: fakeDocker([]), open: async () => 55003, sleep: async () => {}, run: async () => 0, env: {}, say: () => {} };
73
+ const config = { throwawayDb: { avoidPorts: [5433] } };
74
+ assert.equal(await runThrowawayDb(config, ["--port", "5432", "--", "x"], deps), 2);
75
+ assert.equal(await runThrowawayDb(config, ["--port", "5433", "--", "x"], deps), 2);
76
+ const opened = [5432, 5433, 55003];
77
+ let next = 0;
78
+ const ports = [];
79
+ const run = async () => 0;
80
+ const docker = (args) => { if (args[0] === "run") ports.push(args[args.indexOf("--publish") + 1]); return { code: 0, err: "" }; };
81
+ await runThrowawayDb(config, ["--", "x"], { ...deps, docker, run, open: async () => opened[next++] });
82
+ assert.deepEqual(ports, ["127.0.0.1:55003:5432"]);
83
+ });
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ // The PreToolUse trigger that names the components a new component file may duplicate. It runs on a `Write`
3
+ // of a `.tsx` file that does not exist yet and lies under the component roots, ranks the catalog by the
4
+ // words of the file name and the exported names in the content, and adds context. It never blocks.
5
+
6
+ import { existsSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { CONFIG_FILE, load } from "../config.mjs";
10
+ import { findComponents } from "../ui/find.mjs";
11
+ import { componentFileMatcher, uiOptions } from "../ui/options.mjs";
12
+ import { scanComponents } from "../ui/scan.mjs";
13
+ import { checkoutRootOf } from "./checkout-root.mjs";
14
+
15
+ const TOP = 5;
16
+ const EXPORTED = /\bexport\s+(?:default\s+)?(?:async\s+)?(?:function|const|class)\s+([A-Z]\w*)/g;
17
+ const EXPORT_LIST = /\bexport\s*\{([^}]*)\}/g;
18
+
19
+ const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } });
20
+
21
+ /** The names a new file exports: declared with `export`, or listed in an `export { }`. */
22
+ export function exportedNames(content) {
23
+ const names = [...content.matchAll(EXPORTED)].map((found) => found[1]);
24
+ for (const list of content.matchAll(EXPORT_LIST)) {
25
+ for (const item of list[1].split(",")) {
26
+ const name = item.trim().split(/\s+as\s+/).at(-1);
27
+ if (name && /^[A-Z]\w*$/.test(name)) names.push(name);
28
+ }
29
+ }
30
+ return [...new Set(names)];
31
+ }
32
+
33
+ /** The nearest folder that exists, since a new file may sit in a folder nobody has made yet. */
34
+ function existingAncestor(dir) {
35
+ let here = dir;
36
+ while (!existsSync(here) && path.dirname(here) !== here) here = path.dirname(here);
37
+ return here;
38
+ }
39
+
40
+ /** The hook output for one call, or null to let it run with no message. */
41
+ export async function decide(call) {
42
+ const input = call.tool_input ?? {};
43
+ if (call.tool_name !== "Write" || typeof input.file_path !== "string" || !input.file_path.endsWith(".tsx")) return null;
44
+ const file = path.resolve(call.cwd ?? process.cwd(), input.file_path);
45
+ if (existsSync(file)) return null;
46
+ const root = checkoutRootOf(existingAncestor(path.dirname(file)));
47
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
48
+
49
+ const rel = path.relative(root, file).split(path.sep).join("/");
50
+ let config;
51
+ try {
52
+ config = load(root);
53
+ } catch {
54
+ return null;
55
+ }
56
+ if (!componentFileMatcher(uiOptions(config))(rel)) return null;
57
+
58
+ const words = [path.basename(file, ".tsx"), ...exportedNames(String(input.content ?? ""))];
59
+ let entries;
60
+ try {
61
+ ({ entries } = await scanComponents(config));
62
+ } catch {
63
+ return null;
64
+ }
65
+ const found = findComponents(entries, words, TOP);
66
+ if (found.length === 0) return null;
67
+ const list = found.map(({ entry }) => `${entry.name} (${entry.path})`).join(", ");
68
+ return context(
69
+ `Existing components that may already do this: ${list}. Reuse or extend one; write a new one only when none fits, and say why in its JSDoc.`,
70
+ );
71
+ }
72
+
73
+ async function readStdin() {
74
+ let data = "";
75
+ for await (const chunk of process.stdin) data += chunk;
76
+ return data;
77
+ }
78
+
79
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
80
+ if (isEntryPoint) {
81
+ let call = null;
82
+ try {
83
+ call = JSON.parse(await readStdin());
84
+ } catch {
85
+ // Not hook input, so there is nothing to judge.
86
+ }
87
+ const output = call ? await decide(call).catch(() => null) : null;
88
+ if (output) process.stdout.write(JSON.stringify(output));
89
+ }
@@ -0,0 +1,60 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { decide, exportedNames } from "./ui-reuse-hint.mjs";
8
+
9
+ const UI = "frontend/src/platform/ui";
10
+
11
+ function project() {
12
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-hint-"));
13
+ execFileSync("git", ["init", "-q"], { cwd: root });
14
+ writeFileSync(path.join(root, "qc.config.json"), "{}");
15
+ mkdirSync(path.join(root, UI), { recursive: true });
16
+ writeFileSync(path.join(root, UI, "confirm-dialog.tsx"), "/** Asks the user to confirm a destructive action. */\nexport const ConfirmDialog = () => null;\n");
17
+ return root;
18
+ }
19
+
20
+ const write = (root, rel, content) => ({ tool_name: "Write", cwd: root, tool_input: { file_path: path.join(root, rel), content } });
21
+
22
+ test("a new component file under the roots gets the components that may already do the job", async () => {
23
+ const root = project();
24
+ try {
25
+ const out = await decide(write(root, `${UI}/confirm-modal.tsx`, "export const Modal = () => null;"));
26
+ const text = out.hookSpecificOutput.additionalContext;
27
+ assert.equal(out.hookSpecificOutput.hookEventName, "PreToolUse");
28
+ assert.equal(out.hookSpecificOutput.permissionDecision, undefined);
29
+ assert.match(text, /^Existing components that may already do this: ConfirmDialog \(frontend\/src\/platform\/ui\/confirm-dialog\.tsx\)\./);
30
+ assert.match(text, /Reuse or extend one; write a new one only when none fits, and say why in its JSDoc\.$/);
31
+ } finally {
32
+ rmSync(root, { recursive: true, force: true });
33
+ }
34
+ });
35
+
36
+ test("a file that exists, is outside the roots, is not tsx, or matches nothing gets no message", async () => {
37
+ const root = project();
38
+ try {
39
+ assert.equal(await decide(write(root, `${UI}/confirm-dialog.tsx`, "export const ConfirmDialog = () => null;")), null);
40
+ assert.equal(await decide(write(root, "frontend/src/pages/confirm-page.tsx", "export const ConfirmPage = () => null;")), null);
41
+ assert.equal(await decide(write(root, `${UI}/confirm-thing.ts`, "export const x = 1;")), null);
42
+ assert.equal(await decide(write(root, `${UI}/zebra.tsx`, "export const Zebra = () => null;")), null);
43
+ assert.equal(await decide({ tool_name: "Edit", cwd: root, tool_input: { file_path: path.join(root, `${UI}/new.tsx`) } }), null);
44
+ } finally {
45
+ rmSync(root, { recursive: true, force: true });
46
+ }
47
+ });
48
+
49
+ test("a repository with no config file gets no message", async () => {
50
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-hint-"));
51
+ try {
52
+ assert.equal(await decide(write(root, `${UI}/confirm.tsx`, "export const Confirm = () => null;")), null);
53
+ } finally {
54
+ rmSync(root, { recursive: true, force: true });
55
+ }
56
+ });
57
+
58
+ test("exportedNames reads declared and listed exports", () => {
59
+ assert.deepEqual(exportedNames("export const A = 1;\nexport default function B() {}\nconst c = 1; export { c, C as D };"), ["A", "B", "D"]);
60
+ });
package/src/cli/ui.mjs ADDED
@@ -0,0 +1,181 @@
1
+ // `qc ui`: find a component before writing one, and change class tokens across a frontend in one command.
2
+ // Each subcommand is a thin reader over the pure modules in ../ui.
3
+
4
+ import { readFileSync } from "node:fs";
5
+ import { readFile as readFileAsync, writeFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { baselineOfFindings, findDupes } from "../ui/dupes.mjs";
8
+ import { findComponents, formatFound } from "../ui/find.mjs";
9
+ import { arbitraryTokens, codemodSource, parseMap, suggest, themeVariables } from "../ui/codemod.mjs";
10
+ import { sameCatalog } from "../ui/catalog.mjs";
11
+ import { uiOptions } from "../ui/options.mjs";
12
+ import {
13
+ CATALOG_COMMAND,
14
+ catalogText,
15
+ clientSourceFiles,
16
+ listFiles,
17
+ readFiles,
18
+ requireTypeScript,
19
+ scanComponents,
20
+ writeCatalog,
21
+ writeCatalogBaseline,
22
+ } from "../ui/scan.mjs";
23
+
24
+ const USAGE = `qc ui — the component catalog, the duplicate finder and the class codemod
25
+
26
+ qc ui catalog [--json] [--check] [--baseline]
27
+ write the catalog; --check exits 1 when it is stale; --baseline writes ui-catalog.baseline.json
28
+ qc ui find <words...> [--json]
29
+ the eight catalog entries nearest the words, as name — path — description
30
+ qc ui dupes [--json] [--baseline]
31
+ repeated class strings, repeated component names, near-equal JSX trees
32
+ qc ui codemod --map <json|file> [--write]
33
+ rewrite whole class tokens in class sites; a dry run unless --write
34
+ qc ui codemod --suggest every arbitrary-value token with its count, and the @theme variable with its value`;
35
+
36
+ const say = (line) => console.log(line);
37
+
38
+ /** `--flag` words and the rest, split. A flag that takes a value is named in `valued`. */
39
+ function parse(args, valued = []) {
40
+ const flags = new Map();
41
+ const words = [];
42
+ for (let index = 0; index < args.length; index += 1) {
43
+ const arg = args[index];
44
+ if (!arg.startsWith("--")) words.push(arg);
45
+ else if (valued.includes(arg)) flags.set(arg, args[(index += 1)]);
46
+ else flags.set(arg, true);
47
+ }
48
+ return { flags, words };
49
+ }
50
+
51
+ async function catalog(config, args) {
52
+ const { flags } = parse(args);
53
+ const { options, entries } = await scanComponents(config);
54
+ const expected = catalogText(entries, options);
55
+ if (flags.has("--json")) {
56
+ say(JSON.stringify(entries, null, 2));
57
+ return 0;
58
+ }
59
+ if (flags.has("--check")) {
60
+ const actual = await readFileAsync(path.join(config.root, options.catalog), "utf8").catch(() => null);
61
+ if (sameCatalog(actual, expected)) return 0;
62
+ console.error(`${options.catalog} is stale; run \`${CATALOG_COMMAND}\``);
63
+ return 1;
64
+ }
65
+ if (flags.has("--baseline")) {
66
+ await writeCatalogBaseline(config, entries, options);
67
+ say(`wrote ${options.catalogBaseline}: ${entries.filter((entry) => entry.description === "").length} undocumented component(s)`);
68
+ return 0;
69
+ }
70
+ const written = await writeCatalog(config);
71
+ say(written.entries === 0 ? `no component under ${options.componentRoots.join(", ")}; no catalog` : `wrote ${written.path}: ${written.entries} component(s)`);
72
+ return 0;
73
+ }
74
+
75
+ async function find(config, args) {
76
+ const { flags, words } = parse(args);
77
+ if (words.length === 0) {
78
+ console.error("qc ui find <words...>");
79
+ return 1;
80
+ }
81
+ const { entries } = await scanComponents(config);
82
+ const found = findComponents(entries, words);
83
+ if (flags.has("--json")) say(JSON.stringify(found.map(({ entry, score }) => ({ ...entry, score })), null, 2));
84
+ else for (const one of found) say(formatFound(one));
85
+ return 0;
86
+ }
87
+
88
+ async function dupes(config, args) {
89
+ const { flags } = parse(args);
90
+ const { options, files, entries, ts } = await scanComponents(config);
91
+ const found = ts ? findDupes(ts, files, { entries, callees: options.classCallees, ...options.dupes }) : [];
92
+ if (flags.has("--baseline")) {
93
+ await writeFile(path.join(config.root, options.dupes.baseline), `${JSON.stringify(baselineOfFindings(found), null, 2)}\n`);
94
+ say(`wrote ${options.dupes.baseline}: ${found.length} finding(s)`);
95
+ return 0;
96
+ }
97
+ if (flags.has("--json")) {
98
+ say(JSON.stringify(found, null, 2));
99
+ return 0;
100
+ }
101
+ const titles = { "class-string": "Repeated class strings", "component-name": "Repeated component names", "jsx-tree": "Near-equal JSX trees" };
102
+ for (const kind of Object.keys(titles)) {
103
+ const ofKind = found.filter((one) => one.kind === kind);
104
+ say(`${titles[kind]}: ${ofKind.length}`);
105
+ for (const one of ofKind) {
106
+ const where = one.locations ? one.locations.join(" ~ ") : one.files.join(", ");
107
+ say(` ${kind === "class-string" ? `"${one.key}"` : one.key}\n ${where}`);
108
+ }
109
+ }
110
+ return 0;
111
+ }
112
+
113
+ /** The map of `--map`: inline JSON, or the path of a JSON file. */
114
+ function mapOf(value, root) {
115
+ if (typeof value !== "string") throw new Error("--map needs a JSON object, or the path of a JSON file");
116
+ const text = value.trimStart().startsWith("{") ? value : readFileSync(path.resolve(root, value), "utf8");
117
+ return parseMap(text);
118
+ }
119
+
120
+ async function stylesheets(config, listed) {
121
+ const css = await readFiles(config.root, listed.filter((rel) => rel.endsWith(".css")));
122
+ return css.filter((file) => file.contents.includes("@theme")).flatMap((file) => themeVariables(file.contents));
123
+ }
124
+
125
+ async function codemod(config, args) {
126
+ const { flags } = parse(args, ["--map"]);
127
+ const options = uiOptions(config);
128
+ const ts = requireTypeScript(config.root);
129
+ const listed = await listFiles(config);
130
+ const files = await clientSourceFiles(config, listed);
131
+
132
+ if (flags.has("--suggest")) {
133
+ const counts = new Map();
134
+ for (const file of files) {
135
+ for (const [token, count] of arbitraryTokens(ts, file.path, file.contents, options.classCallees)) counts.set(token, (counts.get(token) ?? 0) + count);
136
+ }
137
+ for (const line of suggest(counts, await stylesheets(config, listed))) {
138
+ say(`${String(line.count).padStart(5)} ${line.token}${line.variable ? ` -> ${line.variable}: ${line.value}` : ""}`);
139
+ }
140
+ say(`${counts.size} arbitrary-value token(s)`);
141
+ return 0;
142
+ }
143
+
144
+ let map;
145
+ try {
146
+ map = mapOf(flags.get("--map"), config.root);
147
+ } catch (cause) {
148
+ console.error(`qc ui codemod: ${cause.message}`);
149
+ return 1;
150
+ }
151
+ let total = 0;
152
+ let touched = 0;
153
+ for (const file of files) {
154
+ const out = codemodSource(ts, file.path, file.contents, map, options.classCallees);
155
+ if (out.count === 0) continue;
156
+ total += out.count;
157
+ touched += 1;
158
+ say(`${file.path} ${out.count}`);
159
+ if (flags.has("--write")) await writeFile(path.join(config.root, file.path), out.text);
160
+ }
161
+ say(`${total} token(s) in ${touched} file(s)${flags.has("--write") ? " rewritten" : "; a dry run, pass --write to apply"}`);
162
+ return 0;
163
+ }
164
+
165
+ const COMMANDS = { catalog, find, dupes, codemod };
166
+
167
+ /** @returns {Promise<number>} the exit code */
168
+ export async function runUi(config, args) {
169
+ const [name, ...rest] = args;
170
+ const run = COMMANDS[name];
171
+ if (!run) {
172
+ say(USAGE);
173
+ return name === undefined || name === "help" ? 0 : 1;
174
+ }
175
+ try {
176
+ return await run(config, rest);
177
+ } catch (cause) {
178
+ console.error(`qc ui ${name}: ${cause.message}`);
179
+ return 1;
180
+ }
181
+ }
@@ -0,0 +1,137 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { load } from "../config.mjs";
7
+ import { runCheck } from "./check.mjs";
8
+ import { runUi } from "./ui.mjs";
9
+
10
+ const ROOT_UI = "frontend/src/platform/ui";
11
+ // A project with no feature folder also trips the unrelated root check.
12
+ const uiProblems = async (config) => (await runCheck(config)).problems.filter((problem) => problem.rule !== "unfound-root");
13
+
14
+ function project(files, config = {}) {
15
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-ui-"));
16
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify(config));
17
+ for (const [rel, contents] of Object.entries(files)) {
18
+ mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
19
+ writeFileSync(path.join(root, rel), contents);
20
+ }
21
+ return root;
22
+ }
23
+
24
+ async function ui(root, ...args) {
25
+ const out = [];
26
+ const err = [];
27
+ const { log, error } = console;
28
+ console.log = (line) => out.push(String(line));
29
+ console.error = (line) => err.push(String(line));
30
+ try {
31
+ const code = await runUi(load(root), args);
32
+ return { code, out: out.join("\n"), err: err.join("\n") };
33
+ } finally {
34
+ console.log = log;
35
+ console.error = error;
36
+ }
37
+ }
38
+
39
+ const FILES = {
40
+ [`${ROOT_UI}/button.tsx`]: `/** A pressable control. */\nexport function Button({ label }: { label: string }) { return <button className="text-[11px] rounded-[4px]">{label}</button>; }\n`,
41
+ [`${ROOT_UI}/panel.tsx`]: `export const Panel = () => <div className={cn("text-[11px]")} />;\n`,
42
+ };
43
+
44
+ test("qc ui catalog writes the catalog, --check passes then fails once a component changes", async () => {
45
+ const root = project(FILES);
46
+ try {
47
+ assert.match((await ui(root, "catalog")).out, /wrote docs\/ui-catalog\.md: 2 component/);
48
+ const text = readFileSync(path.join(root, "docs/ui-catalog.md"), "utf8");
49
+ assert.match(text, /`Button`/);
50
+ assert.equal((await ui(root, "catalog", "--check")).code, 0);
51
+ writeFileSync(path.join(root, ROOT_UI, "card.tsx"), "export const Card = () => null;\n");
52
+ const stale = await ui(root, "catalog", "--check");
53
+ assert.equal(stale.code, 1);
54
+ assert.match(stale.err, /stale/);
55
+ assert.equal(JSON.parse((await ui(root, "catalog", "--json")).out).length, 3);
56
+ } finally {
57
+ rmSync(root, { recursive: true, force: true });
58
+ }
59
+ });
60
+
61
+ test("a repository with no component under its roots gets no catalog and no failure", async () => {
62
+ const root = project({ "src/readme.txt": "none" });
63
+ try {
64
+ assert.match((await ui(root, "catalog")).out, /no catalog/);
65
+ assert.equal(existsSync(path.join(root, "docs/ui-catalog.md")), false);
66
+ const config = { ...load(root), gates: { ...load(root).gates, "ui-catalog": true, "ui-dupes": true } };
67
+ assert.deepEqual(await uiProblems(config), []);
68
+ } finally {
69
+ rmSync(root, { recursive: true, force: true });
70
+ }
71
+ });
72
+
73
+ test("qc ui find prints name, path and description of the nearest entries", async () => {
74
+ const root = project(FILES);
75
+ try {
76
+ const { out } = await ui(root, "find", "pressable", "button");
77
+ assert.equal(out, `Button — ${ROOT_UI}/button.tsx — A pressable control.`);
78
+ } finally {
79
+ rmSync(root, { recursive: true, force: true });
80
+ }
81
+ });
82
+
83
+ test("qc ui codemod is a dry run until --write, and --suggest counts arbitrary values", async () => {
84
+ const root = project(FILES);
85
+ const map = JSON.stringify({ "text-[11px]": "text-2xs" });
86
+ try {
87
+ const dry = await ui(root, "codemod", "--map", map);
88
+ assert.match(dry.out, /button\.tsx {2}1/);
89
+ assert.match(dry.out, /2 token\(s\) in 2 file\(s\); a dry run/);
90
+ assert.match(readFileSync(path.join(root, ROOT_UI, "button.tsx"), "utf8"), /text-\[11px\]/);
91
+ await ui(root, "codemod", "--map", map, "--write");
92
+ assert.match(readFileSync(path.join(root, ROOT_UI, "button.tsx"), "utf8"), /className="text-2xs rounded-\[4px\]"/);
93
+ const suggestion = await ui(root, "codemod", "--suggest");
94
+ assert.match(suggestion.out, /1 {2}rounded-\[4px\]/);
95
+ assert.equal((await ui(root, "codemod")).code, 1);
96
+ } finally {
97
+ rmSync(root, { recursive: true, force: true });
98
+ }
99
+ });
100
+
101
+ test("the ui-catalog gate fails an undocumented component and a stale catalog, and a baseline excuses and then must shrink", async () => {
102
+ const root = project(FILES);
103
+ const gated = () => ({ ...load(root), gates: { ...load(root).gates, "ui-catalog": true } });
104
+ try {
105
+ await ui(root, "catalog");
106
+ const first = (await uiProblems(gated())).filter((problem) => problem.rule.endsWith("component") || problem.rule.includes("catalog") || problem.rule.includes("baseline"));
107
+ assert.deepEqual(first.map((problem) => [problem.rule, problem.path]), [["undocumented-component", `${ROOT_UI}/panel.tsx:1`]]);
108
+
109
+ await ui(root, "catalog", "--baseline");
110
+ assert.deepEqual((await uiProblems(gated())), []);
111
+
112
+ writeFileSync(path.join(root, ROOT_UI, "panel.tsx"), `/** A panel. */\nexport const Panel = () => <div />;\n`);
113
+ await ui(root, "catalog");
114
+ const shrunk = (await uiProblems(gated()));
115
+ assert.deepEqual(shrunk.map((problem) => problem.rule), ["stale-baseline"]);
116
+ } finally {
117
+ rmSync(root, { recursive: true, force: true });
118
+ }
119
+ });
120
+
121
+ test("the ui-dupes gate fails a finding outside the baseline and the baseline only shrinks", async () => {
122
+ const files = {
123
+ [`${ROOT_UI}/a/card.tsx`]: "/** A card. */\nexport const Card = () => null;\n",
124
+ [`${ROOT_UI}/b/card.tsx`]: "/** Another card. */\nexport const Card = () => null;\n",
125
+ };
126
+ const root = project(files);
127
+ const gated = () => ({ ...load(root), gates: { ...load(root).gates, "ui-dupes": true } });
128
+ try {
129
+ assert.deepEqual((await uiProblems(gated())).map((problem) => problem.rule), ["duplicate-component-name"]);
130
+ await ui(root, "dupes", "--baseline");
131
+ assert.deepEqual((await uiProblems(gated())), []);
132
+ rmSync(path.join(root, ROOT_UI, "b"), { recursive: true });
133
+ assert.deepEqual((await uiProblems(gated())).map((problem) => problem.rule), ["stale-baseline"]);
134
+ } finally {
135
+ rmSync(root, { recursive: true, force: true });
136
+ }
137
+ });