astralis-cli 0.4.0 → 0.5.1
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/CHANGELOG.md +179 -0
- package/LICENSE +21 -0
- package/README.md +179 -29
- package/package.json +29 -10
- package/src/commands/add.mjs +48 -71
- package/src/commands/connect-mcp.mjs +66 -29
- package/src/commands/create.mjs +73 -100
- package/src/commands/init.mjs +59 -22
- package/src/commands/report.mjs +257 -0
- package/src/commands/theme.mjs +77 -104
- package/src/commands/validate.mjs +101 -0
- package/src/index.mjs +26 -48
- package/src/lib/args.mjs +135 -0
- package/src/lib/aria.mjs +40 -0
- package/src/lib/children-rule.mjs +23 -0
- package/src/lib/ci-setup.mjs +78 -0
- package/src/lib/ci.mjs +155 -0
- package/src/lib/commands.mjs +214 -0
- package/src/lib/css-value.mjs +141 -0
- package/src/lib/devtools-setup.mjs +142 -0
- package/src/lib/edits.mjs +206 -26
- package/src/lib/github-annotations.mjs +26 -0
- package/src/lib/github.d.mts +72 -0
- package/src/lib/github.mjs +339 -0
- package/src/lib/library.mjs +40 -0
- package/src/lib/menu.mjs +59 -0
- package/src/lib/prompt-child.mjs +85 -39
- package/src/lib/registry.mjs +37 -4
- package/src/lib/report-tree.mjs +134 -0
- package/src/lib/run.mjs +39 -0
- package/src/lib/snapshot.d.mts +65 -0
- package/src/lib/snapshot.mjs +371 -0
- package/src/lib/source-files.mjs +29 -0
- package/src/lib/spec-load.mjs +32 -0
- package/src/lib/spec-resolve.mjs +20 -0
- package/src/lib/starter.mjs +11 -19
- package/src/lib/suggest.mjs +32 -0
- package/src/lib/ui.mjs +78 -36
- package/src/lib/validate-core.d.mts +48 -0
- package/src/lib/validate-core.mjs +655 -0
- package/src/lib/validate.d.mts +33 -0
- package/src/lib/validate.mjs +8 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/* ==========================================================================
|
|
2
|
+
astralis report: an issue snapshot from source files.
|
|
3
|
+
--------------------------------------------------------------------------
|
|
4
|
+
The same astralis-snapshot/1 the DevTools build from a page, built here
|
|
5
|
+
from the JSX of the files that show the problem: the astralis-ui
|
|
6
|
+
components with their literal props, the validator's findings for those
|
|
7
|
+
files, and the versions installed. It prints the exact JSON and opens it
|
|
8
|
+
as a GitHub issue, from the reporter's own account, only when they
|
|
9
|
+
confirm. The first time, they sign in with a code on github.com.
|
|
10
|
+
========================================================================== */
|
|
11
|
+
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { readFileSync, statSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
15
|
+
import { bold, cyan, dim, fail, info, ok, warn, ask, isAssumeYes, confirm, select, posix } from "../lib/ui.mjs";
|
|
16
|
+
import { parseCommandArgs } from "../lib/args.mjs";
|
|
17
|
+
import { commandNamed } from "../lib/commands.mjs";
|
|
18
|
+
import { loadSpec } from "../lib/spec-load.mjs";
|
|
19
|
+
import { detectFramework, readPackageJson } from "../lib/detect.mjs";
|
|
20
|
+
import { prepareSpec, validateSource } from "../lib/validate-core.mjs";
|
|
21
|
+
import { treeFromSource } from "../lib/report-tree.mjs";
|
|
22
|
+
import { SNAPSHOT_FORMAT, LIMITS, checkSnapshot } from "../lib/snapshot.mjs";
|
|
23
|
+
import {
|
|
24
|
+
commentFromSnapshot,
|
|
25
|
+
commentOnIssue,
|
|
26
|
+
createIssue,
|
|
27
|
+
findSimilar,
|
|
28
|
+
finishSignIn,
|
|
29
|
+
issueFromSnapshot,
|
|
30
|
+
issuesRepo,
|
|
31
|
+
newIssueUrl,
|
|
32
|
+
startSignIn,
|
|
33
|
+
tokenStore,
|
|
34
|
+
} from "../lib/github.mjs";
|
|
35
|
+
|
|
36
|
+
/** The nearest node_modules/<name>/package.json above `root`: its version, or null. */
|
|
37
|
+
function installedVersion(root, name) {
|
|
38
|
+
for (let dir = resolve(root); ; dir = dirname(dir)) {
|
|
39
|
+
const file = join(dir, "node_modules", name, "package.json");
|
|
40
|
+
if (statSync(file, { throwIfNoEntry: false })) {
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(readFileSync(file, "utf8")).version ?? null;
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (dirname(dir) === dir) return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function environmentOf(cwd) {
|
|
52
|
+
const framework = detectFramework(readPackageJson(cwd));
|
|
53
|
+
return {
|
|
54
|
+
framework: { name: framework, version: framework ? installedVersion(cwd, framework) : null },
|
|
55
|
+
react: installedVersion(cwd, "react"),
|
|
56
|
+
browser: null,
|
|
57
|
+
viewport: null,
|
|
58
|
+
colorMode: null,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The reporter's words: flags first, then prompts, with --yes taking what the flags gave. */
|
|
63
|
+
function describe(values) {
|
|
64
|
+
const answer = (flag, question) => {
|
|
65
|
+
if (values[flag] !== undefined) return values[flag];
|
|
66
|
+
if (isAssumeYes()) return undefined;
|
|
67
|
+
return ask(question) || undefined;
|
|
68
|
+
};
|
|
69
|
+
const title = answer("title", `${bold("Title")} ${dim("(one line)")}: `);
|
|
70
|
+
if (!title?.trim()) {
|
|
71
|
+
fail(`A report needs a title — pass ${cyan('--title "…"')}${isAssumeYes() ? " with --yes" : ""}.`);
|
|
72
|
+
}
|
|
73
|
+
const description = { title: title.trim().slice(0, LIMITS.title) };
|
|
74
|
+
const happened = answer("happened", `${bold("What happened?")} ${dim("(Enter to skip)")} `);
|
|
75
|
+
const expected = answer("expected", `${bold("What did you expect?")} ${dim("(Enter to skip)")} `);
|
|
76
|
+
if (happened?.trim()) description.happened = happened.trim().slice(0, LIMITS.body);
|
|
77
|
+
if (expected?.trim()) description.expected = expected.trim().slice(0, LIMITS.body);
|
|
78
|
+
return description;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Sign in with GitHub's device flow, in the terminal, and save the sign-in. */
|
|
82
|
+
async function signIn(store) {
|
|
83
|
+
let flow;
|
|
84
|
+
try {
|
|
85
|
+
flow = await startSignIn();
|
|
86
|
+
} catch (error) {
|
|
87
|
+
fail(`${error.message} Nothing was sent. ${cyan("--out snapshot.json")} saves the snapshot to attach by hand.`);
|
|
88
|
+
}
|
|
89
|
+
console.log("");
|
|
90
|
+
console.log(` Sign in to GitHub: open ${cyan(flow.verificationUri)} and enter ${bold(flow.userCode)}`);
|
|
91
|
+
console.log(dim(` The Astralis DevTools app can only read and write issues on ${issuesRepo()}.`));
|
|
92
|
+
console.log("");
|
|
93
|
+
try {
|
|
94
|
+
const signedIn = await finishSignIn(flow);
|
|
95
|
+
store.write(signedIn);
|
|
96
|
+
ok(`signed in as ${bold(signedIn.login)}`);
|
|
97
|
+
return signedIn;
|
|
98
|
+
} catch (error) {
|
|
99
|
+
fail(`${error.message} Nothing was sent.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function run(argv) {
|
|
104
|
+
const args = parseCommandArgs(commandNamed("report"), argv);
|
|
105
|
+
if (!args) return;
|
|
106
|
+
const { values, positionals } = args;
|
|
107
|
+
const cwd = process.cwd();
|
|
108
|
+
if (values["sign-out"]) {
|
|
109
|
+
const store = tokenStore();
|
|
110
|
+
const saved = store.read();
|
|
111
|
+
store.clear();
|
|
112
|
+
if (saved) ok(`signed out of GitHub (${saved.login}). The app's access ends when you revoke it at github.com/settings/applications.`);
|
|
113
|
+
else info("not signed in to GitHub.");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (positionals.length === 0) {
|
|
117
|
+
fail(`Name the files that show the problem: ${cyan("astralis report app/page.tsx")}.`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const { spec, text: specText } = loadSpec(values.spec, cwd);
|
|
121
|
+
const prepared = prepareSpec(spec);
|
|
122
|
+
const tree = [];
|
|
123
|
+
const findings = [];
|
|
124
|
+
for (const given of positionals) {
|
|
125
|
+
const file = resolve(given);
|
|
126
|
+
if (!/\.(tsx|jsx)$/.test(file) || !statSync(file, { throwIfNoEntry: false })?.isFile()) {
|
|
127
|
+
fail(`${given} is not a .tsx or .jsx file.`);
|
|
128
|
+
}
|
|
129
|
+
const rel = posix(relative(cwd, file));
|
|
130
|
+
if (rel.startsWith("..")) fail(`${given} is outside this project; run the command from the project root.`);
|
|
131
|
+
const source = readFileSync(file, "utf8");
|
|
132
|
+
try {
|
|
133
|
+
tree.push(...treeFromSource(source, spec, { includeText: values["include-text"] }));
|
|
134
|
+
} catch (error) {
|
|
135
|
+
fail(`${rel} does not parse: ${error.message}`);
|
|
136
|
+
}
|
|
137
|
+
const { errors, warnings } = validateSource(source, prepared, rel);
|
|
138
|
+
findings.push(...errors, ...warnings);
|
|
139
|
+
}
|
|
140
|
+
if (tree.length === 0) fail("None of those files renders an astralis-ui component, so there is nothing to report.");
|
|
141
|
+
|
|
142
|
+
const snapshot = {
|
|
143
|
+
format: SNAPSHOT_FORMAT,
|
|
144
|
+
source: "cli",
|
|
145
|
+
library: {
|
|
146
|
+
name: "astralis-ui",
|
|
147
|
+
version: spec.version,
|
|
148
|
+
specVersion: spec.specVersion,
|
|
149
|
+
specSha256: createHash("sha256").update(specText).digest("hex"),
|
|
150
|
+
},
|
|
151
|
+
environment: environmentOf(cwd),
|
|
152
|
+
route: null,
|
|
153
|
+
tree,
|
|
154
|
+
...(values["no-findings"] ? {} : { findings: findings.slice(0, LIMITS.findings) }),
|
|
155
|
+
description: describe(values),
|
|
156
|
+
};
|
|
157
|
+
const problems = checkSnapshot(snapshot);
|
|
158
|
+
if (problems.length) fail(`The snapshot is not valid: ${problems.join("; ")}`);
|
|
159
|
+
|
|
160
|
+
// The exact content, before anything leaves the machine.
|
|
161
|
+
const json = JSON.stringify(snapshot, null, 2);
|
|
162
|
+
console.log(json);
|
|
163
|
+
|
|
164
|
+
if (values.out) {
|
|
165
|
+
writeFileSync(resolve(values.out), `${json}\n`);
|
|
166
|
+
ok(`snapshot written to ${values.out} ${dim("(nothing was sent)")}`);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (values["dry-run"]) {
|
|
170
|
+
info("dry run: nothing was sent.");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (values.link) {
|
|
174
|
+
// No sign-in: GitHub's own form, pre-filled, submitted in the browser.
|
|
175
|
+
ok("open this link to check the report on GitHub and submit it yourself:");
|
|
176
|
+
console.log(` ${cyan(newIssueUrl(snapshot))}`);
|
|
177
|
+
console.log(dim(" Nothing is sent until you press Create on GitHub."));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const send = await confirm(`Open this as an issue on github.com/${issuesRepo()}?`, {
|
|
181
|
+
hint: `Pass --yes to send, or ${cyan("--out snapshot.json")} to save it instead.`,
|
|
182
|
+
});
|
|
183
|
+
if (!send) {
|
|
184
|
+
info("nothing was sent.");
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const store = tokenStore();
|
|
188
|
+
let signedIn = store.read() ?? (await signIn(store));
|
|
189
|
+
const keep = `Nothing was sent. ${cyan("--out snapshot.json")} saves the snapshot to attach by hand.`;
|
|
190
|
+
/** Run `work` signed in; a sign-in GitHub revoked is replaced, once. */
|
|
191
|
+
const asUser = async (work) => {
|
|
192
|
+
try {
|
|
193
|
+
return await work(signedIn.token);
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error.code !== "signed-out") throw error;
|
|
196
|
+
store.clear();
|
|
197
|
+
signedIn = await signIn(store);
|
|
198
|
+
return work(signedIn.token);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const target = await chooseTarget(values, () => asUser((token) => findSimilar(token, snapshot)));
|
|
203
|
+
try {
|
|
204
|
+
if (target) {
|
|
205
|
+
const added = await asUser((token) => commentOnIssue(token, target, commentFromSnapshot(snapshot)));
|
|
206
|
+
ok(`report added to issue #${added.number} as ${signedIn.login}: ${cyan(added.url)}`);
|
|
207
|
+
} else {
|
|
208
|
+
const created = await asUser((token) => createIssue(token, issueFromSnapshot(snapshot)));
|
|
209
|
+
ok(`issue #${created.number} opened as ${signedIn.login}: ${cyan(created.url)}`);
|
|
210
|
+
}
|
|
211
|
+
} catch (error) {
|
|
212
|
+
fail(`${error.message} ${keep}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const line = (issue) => `#${issue.number} ${issue.title} ${dim(`(${issue.state})`)}`;
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Where the report goes: an existing issue's number, or null for a new issue.
|
|
220
|
+
* --add-to and --new decide without searching. Otherwise the issues that may
|
|
221
|
+
* already report it are shown, and the reporter chooses; with --yes, a new
|
|
222
|
+
* issue is opened and the possible duplicates are listed for them to check.
|
|
223
|
+
*/
|
|
224
|
+
async function chooseTarget(values, searchSimilar) {
|
|
225
|
+
if (values["add-to"] !== undefined) {
|
|
226
|
+
const number = Number(String(values["add-to"]).replace(/^#/, ""));
|
|
227
|
+
if (!Number.isInteger(number) || number < 1) fail(`--add-to takes an issue number, like ${cyan("--add-to 12")}.`);
|
|
228
|
+
return number;
|
|
229
|
+
}
|
|
230
|
+
if (values.new) return null;
|
|
231
|
+
let similar;
|
|
232
|
+
try {
|
|
233
|
+
similar = await searchSimilar();
|
|
234
|
+
} catch (error) {
|
|
235
|
+
warn(`could not check for an existing issue (${error.message}); opening a new one.`);
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
const { duplicates, related } = similar;
|
|
239
|
+
if (related.length) {
|
|
240
|
+
info(`open issues about the same component:`);
|
|
241
|
+
for (const issue of related) console.log(` ${line(issue)} ${dim(issue.url)}`);
|
|
242
|
+
}
|
|
243
|
+
if (!duplicates.length) return null;
|
|
244
|
+
console.log("");
|
|
245
|
+
console.log(bold("This may already be reported:"));
|
|
246
|
+
for (const issue of duplicates) console.log(` ${line(issue)} ${dim(issue.url)}`);
|
|
247
|
+
if (isAssumeYes()) {
|
|
248
|
+
info(`opening a new issue; pass ${cyan(`--add-to ${duplicates[0].number}`)} to add your report to an existing one instead.`);
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
const choice = await select("Add your report to one of them, or open a new issue?", [
|
|
252
|
+
...duplicates.slice(0, 3).map((issue) => ({ value: issue.number, label: `Add it to #${issue.number} ${issue.title}` })),
|
|
253
|
+
{ value: 0, label: "Open a new issue" },
|
|
254
|
+
]);
|
|
255
|
+
if (choice === null) fail("Choose one of the listed numbers. Nothing was sent.");
|
|
256
|
+
return choice || null;
|
|
257
|
+
}
|
package/src/commands/theme.mjs
CHANGED
|
@@ -1,18 +1,16 @@
|
|
|
1
|
-
import { parseArgs } from "node:util";
|
|
2
1
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { dirname, join, relative } from "node:path";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
2
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
3
|
+
import { ok, warn, fail, cyan, dim, posix } from "../lib/ui.mjs";
|
|
4
|
+
import { parseCommandArgs } from "../lib/args.mjs";
|
|
5
|
+
import { commandNamed } from "../lib/commands.mjs";
|
|
6
6
|
import { readPackageJson, detectFramework, findEntryFile } from "../lib/detect.mjs";
|
|
7
|
-
import { addImports } from "../lib/edits.mjs";
|
|
7
|
+
import { addImports, parses } from "../lib/edits.mjs";
|
|
8
|
+
import { loadThemeLibrary } from "../lib/library.mjs";
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
|
-
* Renders a theme seed as a stylesheet
|
|
11
|
-
* <AstralisProvider tokens={seed}
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* Both the colour maths and the serialization come from the library and are
|
|
15
|
-
* never duplicated here, so `astralis theme` and the provider cannot drift.
|
|
11
|
+
* Renders a theme seed as a stylesheet: the static equivalent of
|
|
12
|
+
* <AstralisProvider tokens={seed}>. The colour maths and serialization come
|
|
13
|
+
* from the library, never duplicated here, so the two cannot drift.
|
|
16
14
|
*/
|
|
17
15
|
|
|
18
16
|
/** Flag -> seed field. */
|
|
@@ -35,67 +33,7 @@ const NUMBER_FLAGS = {
|
|
|
35
33
|
motion: "motionScale",
|
|
36
34
|
};
|
|
37
35
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
Colours
|
|
41
|
-
--brand <hex> brand hue, e.g. "#8b5cf6"
|
|
42
|
-
--gray <hex> neutral hue — drives every surface, label and border,
|
|
43
|
-
and tints white/black so the page follows the neutral
|
|
44
|
-
|
|
45
|
-
Status (each seeds its own palette; the red/orange/green/blue hues and
|
|
46
|
-
their colorScheme values are never altered)
|
|
47
|
-
--error <hex> defaults to red
|
|
48
|
-
--warning <hex> defaults to orange
|
|
49
|
-
--success <hex> defaults to green
|
|
50
|
-
--info <hex> defaults to blue
|
|
51
|
-
|
|
52
|
-
Typefaces
|
|
53
|
-
--font-heading <stack>
|
|
54
|
-
--font-body <stack>
|
|
55
|
-
--font-mono <stack>
|
|
56
|
-
|
|
57
|
-
Scales (1 = library default; 0 is allowed)
|
|
58
|
-
--radius <n> border-radius multiplier
|
|
59
|
-
--spacing <n> spacing multiplier — the density dial
|
|
60
|
-
--font-scale <n> font-size multiplier
|
|
61
|
-
--motion <n> duration multiplier (0 disables transitions)
|
|
62
|
-
|
|
63
|
-
Output
|
|
64
|
-
--out <file> default: src/astralis-theme.css, or
|
|
65
|
-
astralis-theme.css in a project with no src/
|
|
66
|
-
--force overwrite an existing file
|
|
67
|
-
--no-import write the file but don't touch the entry point
|
|
68
|
-
|
|
69
|
-
A bare hex is shorthand for --brand: astralis theme "#8b5cf6"`;
|
|
70
|
-
|
|
71
|
-
export async function run(argv) {
|
|
72
|
-
let parsed;
|
|
73
|
-
try {
|
|
74
|
-
parsed = parseArgs({
|
|
75
|
-
args: argv,
|
|
76
|
-
options: {
|
|
77
|
-
...Object.fromEntries(
|
|
78
|
-
[...Object.keys(STRING_FLAGS), ...Object.keys(NUMBER_FLAGS)].map((f) => [f, { type: "string" }]),
|
|
79
|
-
),
|
|
80
|
-
// No default: the destination depends on whether the project has a
|
|
81
|
-
// src/, resolved below so `--out` can still override it.
|
|
82
|
-
out: { type: "string" },
|
|
83
|
-
"no-import": { type: "boolean", default: false },
|
|
84
|
-
force: { type: "boolean", default: false },
|
|
85
|
-
help: { type: "boolean", default: false },
|
|
86
|
-
},
|
|
87
|
-
allowPositionals: true,
|
|
88
|
-
});
|
|
89
|
-
} catch (error) {
|
|
90
|
-
fail(`${error.message}\n\n${USAGE}`);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const { values, positionals } = parsed;
|
|
94
|
-
if (values.help) {
|
|
95
|
-
console.log(USAGE);
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
98
|
-
|
|
36
|
+
function seedFrom(values, positionals) {
|
|
99
37
|
const seed = {};
|
|
100
38
|
for (const [flag, field] of Object.entries(STRING_FLAGS)) {
|
|
101
39
|
if (values[flag] !== undefined) seed[field] = values[flag];
|
|
@@ -103,60 +41,95 @@ export async function run(argv) {
|
|
|
103
41
|
for (const [flag, field] of Object.entries(NUMBER_FLAGS)) {
|
|
104
42
|
if (values[flag] === undefined) continue;
|
|
105
43
|
const n = Number(values[flag]);
|
|
106
|
-
if (!Number.isFinite(n)) fail(`--${flag} expects a number, got "${values[flag]}".`);
|
|
44
|
+
if (values[flag].trim() === "" || !Number.isFinite(n)) fail(`--${flag} expects a number, got "${values[flag]}".`);
|
|
107
45
|
seed[field] = n;
|
|
108
46
|
}
|
|
109
|
-
|
|
110
|
-
// Back-compat: `astralis theme "#8b5cf6"` still means --brand.
|
|
47
|
+
// `astralis theme "#8b5cf6"` means --brand.
|
|
111
48
|
if (positionals[0]) {
|
|
112
|
-
if (seed.brandColor) fail("Pass the brand colour as
|
|
49
|
+
if (seed.brandColor) fail("Pass the brand colour as an argument or as --brand, not both.");
|
|
113
50
|
seed.brandColor = positionals[0].toLowerCase();
|
|
114
51
|
}
|
|
52
|
+
return seed;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The same WCAG contracts the library's build gate enforces, run against the
|
|
57
|
+
* palette this seed generates. Returns { results } or { skipped: reason }.
|
|
58
|
+
*/
|
|
59
|
+
function checkContrast(library, seed) {
|
|
60
|
+
try {
|
|
61
|
+
const palette = library.contrast.parsePaletteFromCss(readFileSync(library.stylesPath, "utf8"));
|
|
62
|
+
return { results: library.contrast.verifySeedContrast(seed, palette) };
|
|
63
|
+
} catch (error) {
|
|
64
|
+
return { skipped: error.message };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function run(argv) {
|
|
69
|
+
const args = parseCommandArgs(commandNamed("theme"), argv);
|
|
70
|
+
if (!args) return;
|
|
71
|
+
const { values, positionals } = args;
|
|
115
72
|
|
|
116
|
-
|
|
73
|
+
const seed = seedFrom(values, positionals);
|
|
74
|
+
const cwd = process.cwd();
|
|
75
|
+
const library = await loadThemeLibrary(cwd);
|
|
76
|
+
const { themeCss, validateSeed, isEmptySeed } = library.serialize;
|
|
117
77
|
|
|
78
|
+
if (isEmptySeed(seed)) fail(`Nothing to generate: no theme options given. Run ${cyan("astralis theme --help")}.`);
|
|
118
79
|
const issues = validateSeed(seed);
|
|
119
80
|
if (issues.length) {
|
|
120
81
|
fail(`Invalid theme options:\n${issues.map((i) => ` ${i.field}: ${i.message}`).join("\n")}`);
|
|
121
82
|
}
|
|
122
83
|
|
|
123
|
-
|
|
124
|
-
const posix = (p) => p.split("\\").join("/");
|
|
125
|
-
|
|
126
|
-
/*
|
|
127
|
-
* Default next to the code that imports it, not at the project root — the
|
|
128
|
-
* same rule `astralis add` follows for blocks. A stylesheet dropped beside
|
|
129
|
-
* package.json is not where anyone looks for one.
|
|
130
|
-
*/
|
|
84
|
+
// Next to the code that imports it, as `astralis add` does for blocks.
|
|
131
85
|
const out = values.out ?? (existsSync(join(cwd, "src")) ? join("src", "astralis-theme.css") : "astralis-theme.css");
|
|
132
|
-
|
|
133
|
-
if (existsSync(
|
|
134
|
-
|
|
86
|
+
const outPath = resolve(cwd, out);
|
|
87
|
+
if (existsSync(outPath) && !values.force) fail(`${posix(out)} already exists — pass --force to overwrite.`);
|
|
88
|
+
|
|
89
|
+
const strict = values["strict-contrast"];
|
|
90
|
+
const contrast = checkContrast(library, seed);
|
|
91
|
+
if (contrast.skipped) {
|
|
92
|
+
if (strict) fail(`Couldn't verify contrast (${contrast.skipped}), so nothing was written under --strict-contrast.`);
|
|
93
|
+
warn(`contrast check skipped: ${contrast.skipped}`);
|
|
94
|
+
} else {
|
|
95
|
+
const failures = contrast.results.filter((r) => !r.pass);
|
|
96
|
+
for (const r of failures) {
|
|
97
|
+
warn(
|
|
98
|
+
`contrast: [${r.mode}] ${r.rule} — ${r.fgHex ?? "?"} on ${r.bgHex ?? "?"} is ` +
|
|
99
|
+
`${r.ratio ? r.ratio.toFixed(2) : "unresolvable"}:1, needs ${r.min}:1`,
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
if (failures.length === 0) {
|
|
103
|
+
ok(`contrast: all ${contrast.results.length} promised pairings clear WCAG AA (light + dark)`);
|
|
104
|
+
} else if (strict) {
|
|
105
|
+
fail(`${failures.length} of ${contrast.results.length} pairings fall below WCAG AA — nothing written under --strict-contrast.`);
|
|
106
|
+
} else {
|
|
107
|
+
warn(`${failures.length} of ${contrast.results.length} pairings fall below WCAG AA — a darker or lighter seed usually fixes it.`);
|
|
108
|
+
}
|
|
135
109
|
}
|
|
136
110
|
|
|
137
|
-
writeFileSync(
|
|
138
|
-
|
|
111
|
+
writeFileSync(outPath, themeCss(seed));
|
|
112
|
+
const from = library.source === "project" ? "your project's" : "the CLI's bundled";
|
|
113
|
+
ok(`wrote ${cyan(posix(out))} ${dim(`(astralis-ui ${library.version}, ${from} copy)`)}`);
|
|
114
|
+
if (library.outdated) {
|
|
115
|
+
warn(`Your astralis-ui ${library.outdated} predates static themes; upgrade it so the file matches the library you ship.`);
|
|
116
|
+
}
|
|
139
117
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
* the failure is invisible: the file exists, the command reported success,
|
|
143
|
-
* and the brand colour is simply never applied.
|
|
144
|
-
*
|
|
145
|
-
* It goes after the last existing import, which puts it after
|
|
146
|
-
* `astralis-ui/styles.css` — the order the override depends on.
|
|
147
|
-
*/
|
|
148
|
-
const usesFont = seed.fontHeading || seed.fontBody || seed.fontMono;
|
|
118
|
+
// A generated stylesheet nobody imports changes nothing, silently. After the
|
|
119
|
+
// last import is after astralis-ui/styles.css: the order the override needs.
|
|
149
120
|
const pkg = readPackageJson(cwd);
|
|
150
121
|
const entry = pkg ? findEntryFile(cwd, detectFramework(pkg)) : null;
|
|
122
|
+
const specifier = entry ? posix(relative(dirname(entry.path), outPath)) : null;
|
|
123
|
+
const line = specifier ? `import "${specifier.startsWith(".") ? specifier : `./${specifier}`}";` : null;
|
|
151
124
|
|
|
152
125
|
if (!values["no-import"] && entry) {
|
|
153
|
-
const specifier = posix(relative(dirname(entry.path), join(cwd, out)));
|
|
154
|
-
const line = `import "${specifier.startsWith(".") ? specifier : `./${specifier}`}";`;
|
|
155
126
|
const result = addImports(readFileSync(entry.path, "utf8"), [line]);
|
|
156
|
-
|
|
157
|
-
if (result.changed) {
|
|
127
|
+
if (result.changed && parses(result.source)) {
|
|
158
128
|
writeFileSync(entry.path, result.source);
|
|
159
129
|
ok(`imported in ${cyan(entry.relative)} ${dim("(after the library stylesheet)")}`);
|
|
130
|
+
} else if (result.changed || result.note) {
|
|
131
|
+
warn(`${entry.relative} ${result.note ?? "couldn't be edited safely"} — add this after the library stylesheet:`);
|
|
132
|
+
console.log(` ${cyan(line)}`);
|
|
160
133
|
} else {
|
|
161
134
|
ok(`already imported in ${cyan(entry.relative)}`);
|
|
162
135
|
}
|
|
@@ -168,7 +141,7 @@ export async function run(argv) {
|
|
|
168
141
|
);
|
|
169
142
|
}
|
|
170
143
|
|
|
171
|
-
if (
|
|
144
|
+
if (seed.fontHeading || seed.fontBody || seed.fontMono) {
|
|
172
145
|
console.log(dim("\nCustom fonts must be loaded by your app (next/font or a <link>)."));
|
|
173
146
|
}
|
|
174
147
|
console.log(dim("Runtime alternative: <AstralisProvider tokens={…}> — same math."));
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/* ==========================================================================
|
|
2
|
+
astralis validate — check TSX against the installed design system.
|
|
3
|
+
--------------------------------------------------------------------------
|
|
4
|
+
Loads dist/system-spec.json from the installed astralis-ui (or --spec) and
|
|
5
|
+
runs the validator core over every .tsx/.jsx under the given paths. Exits
|
|
6
|
+
1 when anything that typechecks-but-fails is found.
|
|
7
|
+
========================================================================== */
|
|
8
|
+
|
|
9
|
+
import { readFileSync } from "node:fs";
|
|
10
|
+
import { relative, resolve } from "node:path";
|
|
11
|
+
import { bold, dim, red, yellow, green, ok, fail } from "../lib/ui.mjs";
|
|
12
|
+
import { parseCommandArgs } from "../lib/args.mjs";
|
|
13
|
+
import { commandNamed } from "../lib/commands.mjs";
|
|
14
|
+
import { prepareSpec, validateSource } from "../lib/validate-core.mjs";
|
|
15
|
+
import { loadSpec } from "../lib/spec-load.mjs";
|
|
16
|
+
import { collectSourceFiles } from "../lib/source-files.mjs";
|
|
17
|
+
import { annotation } from "../lib/github-annotations.mjs";
|
|
18
|
+
|
|
19
|
+
const FORMATS = ["text", "json", "github"];
|
|
20
|
+
|
|
21
|
+
/** --format wins; --json means json; inside GitHub Actions the default is annotations. */
|
|
22
|
+
function chooseFormat(values, env = process.env) {
|
|
23
|
+
if (values.format !== undefined && !FORMATS.includes(values.format)) {
|
|
24
|
+
fail(`--format must be one of ${FORMATS.join(", ")} (got "${values.format}").`);
|
|
25
|
+
}
|
|
26
|
+
if (values.json && values.format !== undefined && values.format !== "json") {
|
|
27
|
+
fail(`--json and --format ${values.format} disagree; pass one of them.`);
|
|
28
|
+
}
|
|
29
|
+
if (values.json) return "json";
|
|
30
|
+
return values.format ?? (env.GITHUB_ACTIONS === "true" ? "github" : "text");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function collectFiles(path, into) {
|
|
34
|
+
if (!collectSourceFiles(path, into)) fail(`No such path: ${path}`);
|
|
35
|
+
return into;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function run(argv) {
|
|
39
|
+
const args = parseCommandArgs(commandNamed("validate"), argv);
|
|
40
|
+
if (!args) return;
|
|
41
|
+
const paths = args.positionals.length > 0 ? args.positionals : ["."];
|
|
42
|
+
const strictTokens = args.values["strict-tokens"];
|
|
43
|
+
const format = chooseFormat(args.values);
|
|
44
|
+
|
|
45
|
+
const { spec } = loadSpec(args.values.spec);
|
|
46
|
+
const prepared = prepareSpec(spec);
|
|
47
|
+
const files = paths.reduce((acc, p) => collectFiles(resolve(p), acc), []);
|
|
48
|
+
if (files.length === 0) fail("No .tsx/.jsx files found under the given paths.");
|
|
49
|
+
|
|
50
|
+
const results = [];
|
|
51
|
+
let errorCount = 0;
|
|
52
|
+
let warningCount = 0;
|
|
53
|
+
|
|
54
|
+
for (const file of files) {
|
|
55
|
+
const rel = relative(process.cwd(), file) || file;
|
|
56
|
+
const { errors, warnings } = validateSource(readFileSync(file, "utf8"), prepared, rel, { strictTokens });
|
|
57
|
+
errorCount += errors.length;
|
|
58
|
+
warningCount += warnings.length;
|
|
59
|
+
if (errors.length || warnings.length) results.push({ file: rel, errors, warnings });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (format === "json") {
|
|
63
|
+
console.log(JSON.stringify({
|
|
64
|
+
spec: { name: spec.name, version: spec.version, specVersion: spec.specVersion },
|
|
65
|
+
files: files.length,
|
|
66
|
+
errors: errorCount,
|
|
67
|
+
warnings: warningCount,
|
|
68
|
+
results,
|
|
69
|
+
}, null, 2));
|
|
70
|
+
if (errorCount) process.exitCode = 1;
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (format === "github") {
|
|
75
|
+
for (const r of results) {
|
|
76
|
+
for (const e of r.errors) console.log(annotation("error", e));
|
|
77
|
+
for (const w of r.warnings) console.log(annotation("warning", w));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
for (const r of format === "text" ? results : []) {
|
|
82
|
+
console.log(`\n${bold(r.file)}`);
|
|
83
|
+
const all = [...r.errors.map((e) => ({ ...e, kind: "error" })), ...r.warnings.map((w) => ({ ...w, kind: "warn" }))]
|
|
84
|
+
.sort((a, b) => a.line - b.line || a.column - b.column);
|
|
85
|
+
for (const issue of all) {
|
|
86
|
+
const mark = issue.kind === "error" ? red("✗") : yellow("!");
|
|
87
|
+
console.log(` ${dim(`${issue.line}:${issue.column}`)} ${mark} ${issue.message} ${dim(issue.code)}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const summary = `${files.length} file(s) against ${spec.name}@${spec.version}` +
|
|
92
|
+
` — ${errorCount ? red(`${errorCount} error(s)`) : green("0 errors")}, ` +
|
|
93
|
+
(warningCount ? yellow(`${warningCount} warning(s)`) : "0 warnings");
|
|
94
|
+
console.log("");
|
|
95
|
+
if (errorCount) {
|
|
96
|
+
console.error(`${red("✗")} ${summary}`);
|
|
97
|
+
process.exitCode = 1;
|
|
98
|
+
} else {
|
|
99
|
+
ok(summary);
|
|
100
|
+
}
|
|
101
|
+
}
|