astralis-cli 0.3.0 → 0.5.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 (42) hide show
  1. package/CHANGELOG.md +167 -0
  2. package/LICENSE +21 -0
  3. package/README.md +179 -29
  4. package/package.json +29 -10
  5. package/src/commands/add.mjs +48 -71
  6. package/src/commands/connect-mcp.mjs +66 -27
  7. package/src/commands/create.mjs +133 -39
  8. package/src/commands/init.mjs +125 -28
  9. package/src/commands/report.mjs +257 -0
  10. package/src/commands/theme.mjs +100 -82
  11. package/src/commands/validate.mjs +101 -0
  12. package/src/index.mjs +26 -47
  13. package/src/lib/args.mjs +135 -0
  14. package/src/lib/aria.mjs +40 -0
  15. package/src/lib/children-rule.mjs +23 -0
  16. package/src/lib/ci-setup.mjs +78 -0
  17. package/src/lib/ci.mjs +155 -0
  18. package/src/lib/commands.mjs +214 -0
  19. package/src/lib/css-value.mjs +141 -0
  20. package/src/lib/devtools-setup.mjs +142 -0
  21. package/src/lib/edits.mjs +206 -26
  22. package/src/lib/github-annotations.mjs +26 -0
  23. package/src/lib/github.d.mts +72 -0
  24. package/src/lib/github.mjs +339 -0
  25. package/src/lib/library.mjs +40 -0
  26. package/src/lib/menu.mjs +59 -0
  27. package/src/lib/prompt-child.mjs +97 -0
  28. package/src/lib/registry.mjs +37 -4
  29. package/src/lib/report-tree.mjs +134 -0
  30. package/src/lib/run.mjs +39 -0
  31. package/src/lib/snapshot.d.mts +65 -0
  32. package/src/lib/snapshot.mjs +371 -0
  33. package/src/lib/source-files.mjs +29 -0
  34. package/src/lib/spec-load.mjs +32 -0
  35. package/src/lib/spec-resolve.mjs +20 -0
  36. package/src/lib/starter.mjs +219 -0
  37. package/src/lib/suggest.mjs +32 -0
  38. package/src/lib/ui.mjs +85 -51
  39. package/src/lib/validate-core.d.mts +48 -0
  40. package/src/lib/validate-core.mjs +652 -0
  41. package/src/lib/validate.d.mts +33 -0
  42. package/src/lib/validate.mjs +8 -0
@@ -0,0 +1,20 @@
1
+ import { statSync } from "node:fs";
2
+ import { join, dirname, resolve } from "node:path";
3
+
4
+ /**
5
+ * Walk upward for node_modules/astralis-ui/<file>: the CONSUMER's copy, the
6
+ * version their code must conform to, not this tool's own dependency.
7
+ * (require.resolve can't be used: the library's exports carry no "require"
8
+ * condition.) Returns the file's path, or null.
9
+ */
10
+ export function findInstalledLibrary(startDir, file = "package.json") {
11
+ for (let dir = resolve(startDir); ; dir = dirname(dir)) {
12
+ const candidate = join(dir, "node_modules", "astralis-ui", file);
13
+ if (statSync(candidate, { throwIfNoEntry: false })) return candidate;
14
+ if (dirname(dir) === dir) return null;
15
+ }
16
+ }
17
+
18
+ export function findInstalledSpec(startDir) {
19
+ return findInstalledLibrary(startDir, join("dist", "system-spec.json"));
20
+ }
@@ -0,0 +1,219 @@
1
+ import { join, dirname } from "node:path";
2
+
3
+ /**
4
+ * The welcome screen `astralis create` leaves behind.
5
+ *
6
+ * Scope is deliberately one file. The scaffolder owns the project — router,
7
+ * config, folder layout, tooling — and we replace only what it put on screen.
8
+ * The moment this starts making structural decisions, Astralis owns a template,
9
+ * and templates rot behind the framework they wrap. That is the cost the
10
+ * wrap-the-official-scaffolder design exists to avoid.
11
+ *
12
+ * It earns its place by being an assertion rather than decoration: if the
13
+ * provider, the stylesheet and the token pipeline are all wired correctly you
14
+ * see this render. If `init` half-worked, it is visible immediately instead of
15
+ * hiding until the first component is used.
16
+ *
17
+ * No hooks, so it stays a Server Component under Next without a "use client"
18
+ * banner — ThemeToggle carries its own.
19
+ */
20
+
21
+ /**
22
+ * Every astralis-ui export the starter uses. The gate in test/ asserts these
23
+ * are real exports, and that this list matches what the source actually imports.
24
+ *
25
+ * Flat parts (Card, CardBody) rather than Card.Body: under Next this file
26
+ * is `app/page.tsx`, a Server Component, and namespace access on a
27
+ * client-reference stub is undefined across the RSC boundary. Same rule the
28
+ * block authoring gate enforces, for the same reason.
29
+ */
30
+ export const STARTER_IMPORTS = [
31
+ "Badge",
32
+ "Button",
33
+ "Card",
34
+ "CardBody",
35
+ "Code",
36
+ "Container",
37
+ "Flex",
38
+ "Heading",
39
+ "Stack",
40
+ "Text",
41
+ "ThemeToggle",
42
+ ];
43
+
44
+ function starterSource() {
45
+ return `import {
46
+ ${STARTER_IMPORTS.join(",\n ")},
47
+ } from "astralis-ui";
48
+
49
+ /**
50
+ * Astralis is wired up — this screen is rendering through the provider, the
51
+ * precompiled stylesheet and the token scales.
52
+ *
53
+ * It is an ordinary file in your project. Edit it, or delete it and start over.
54
+ */
55
+ /**
56
+ * The Astralis mark — four blocks, the last still being placed. Painted with
57
+ * the brand token rather than fixed hex, so it re-colours with the theme.
58
+ */
59
+ function AstralisMark() {
60
+ return (
61
+ <svg viewBox="0 0 32 32" width="28" height="28" aria-hidden="true" style={{ overflow: "visible" }}>
62
+ <g fill="var(--astralis-color-brand-500)">
63
+ <rect x="3" y="17" width="12" height="12" rx="3" />
64
+ <rect x="17" y="17" width="12" height="12" rx="3" />
65
+ <rect x="3" y="3" width="12" height="12" rx="3" />
66
+ <rect x="19" y="1" width="12" height="12" rx="3" opacity="0.6" transform="rotate(14 25 7)" />
67
+ </g>
68
+ </svg>
69
+ );
70
+ }
71
+
72
+ export default function Welcome() {
73
+ return (
74
+ <Container maxW="4xl" px={{ base: "6", lg: "8" }} py={{ base: "16", lg: "24" }}>
75
+ <Stack gap="10" alignItems="stretch">
76
+ <Flex justifyContent="between" alignItems="center" gap="4">
77
+ <Flex alignItems="center" gap="3">
78
+ <AstralisMark />
79
+ <Badge variant="subtle" colorScheme="brand" size="xs">
80
+ Astralis UI
81
+ </Badge>
82
+ </Flex>
83
+ <ThemeToggle variant="text" colorScheme="gray" size="sm" aria-label="Toggle theme" />
84
+ </Flex>
85
+
86
+ <Stack gap="4" alignItems="start">
87
+ <Heading as="h1" size={{ base: "2xl", lg: "3xl" }} weight="semibold" letterSpacing="tight">
88
+ You&apos;re set up.
89
+ </Heading>
90
+ <Text size="lg" color="muted" lineHeight="relaxed">
91
+ Everything here is themed through one accent channel. Change{" "}
92
+ <Code>colorScheme</Code> on any component and the rest follows — no
93
+ rebuild, no Tailwind config in your project.
94
+ </Text>
95
+ </Stack>
96
+
97
+ {/* as="a" — Button is polymorphic, so these are real links rather than
98
+ buttons that look clickable and do nothing. */}
99
+ <Flex gap="3" wrap="wrap">
100
+ <Button
101
+ as="a"
102
+ href="https://astralis-ui.com/docs/quick-start"
103
+ target="_blank"
104
+ rel="noreferrer"
105
+ size="lg"
106
+ colorScheme="brand"
107
+ >
108
+ Get started
109
+ </Button>
110
+ <Button
111
+ as="a"
112
+ href="https://astralis-ui.com/docs"
113
+ target="_blank"
114
+ rel="noreferrer"
115
+ size="lg"
116
+ variant="outline"
117
+ colorScheme="gray"
118
+ >
119
+ Read the docs
120
+ </Button>
121
+ </Flex>
122
+
123
+ {/* No width prop on Card by design — the Stack above stretches it. */}
124
+ <Card variant="outline" size="lg">
125
+ <CardBody>
126
+ <Stack gap="3" alignItems="start">
127
+ <Heading as="h2" size="md" weight="semibold">
128
+ Try it
129
+ </Heading>
130
+ <Text color="muted" lineHeight="relaxed">
131
+ Drop in a prebuilt section with <Code>astralis add hero-01</Code>,
132
+ or import anything from <Code>astralis-ui</Code> and compose your
133
+ own.
134
+ </Text>
135
+ <Flex gap="2" wrap="wrap">
136
+ <Badge variant="subtle" colorScheme="green" size="xs">
137
+ green
138
+ </Badge>
139
+ <Badge variant="subtle" colorScheme="blue" size="xs">
140
+ blue
141
+ </Badge>
142
+ <Badge variant="subtle" colorScheme="purple" size="xs">
143
+ purple
144
+ </Badge>
145
+ <Badge variant="subtle" colorScheme="orange" size="xs">
146
+ orange
147
+ </Badge>
148
+ </Flex>
149
+ </Stack>
150
+ </CardBody>
151
+ </Card>
152
+ </Stack>
153
+ </Container>
154
+ );
155
+ }
156
+ `;
157
+ }
158
+
159
+ /**
160
+ * Where the welcome screen goes, derived from the entry file `init` already
161
+ * located — so this never has to guess at the project's layout a second time.
162
+ *
163
+ * Next renders `page.tsx` beside the root layout; Vite renders `App.tsx`
164
+ * beside `main.tsx`. The extension follows the entry, so a JavaScript project
165
+ * gets .jsx (the source carries no type annotations either way).
166
+ */
167
+ export function starterTarget(framework, entryPath) {
168
+ const dir = dirname(entryPath);
169
+ const ext = entryPath.endsWith("x") ? (entryPath.endsWith(".tsx") ? "tsx" : "jsx") : "tsx";
170
+ return join(dir, framework === "next" ? `page.${ext}` : `App.${ext}`);
171
+ }
172
+
173
+ export function starterFile(framework, entryPath) {
174
+ return { path: starterTarget(framework, entryPath), source: starterSource() };
175
+ }
176
+
177
+ /**
178
+ * The stylesheet the Vite template ships to style its demo, and which fights
179
+ * anything you put in its place:
180
+ *
181
+ * #root { text-align: center; display: flex; max-width; margin: 0 auto }
182
+ * :root { font; color; background; color-scheme: light dark }
183
+ *
184
+ * Left in place it centres text that was authored left-aligned, overrides the
185
+ * type scale, and paints the page from the OS colour scheme rather than the
186
+ * provider's — so toggling to light left dark bars either side of the content.
187
+ *
188
+ * Replaced rather than deleted: main.tsx imports it, and the import is the
189
+ * natural place for a consumer to put their own global CSS.
190
+ */
191
+ const VITE_RESET = `/*
192
+ * Your global stylesheet.
193
+ *
194
+ * Astralis ships its own reset inside astralis-ui/styles.css, scoped so it
195
+ * cannot leak into the rest of your app. The Vite template's demo styles were
196
+ * removed from here because they centred and re-coloured everything.
197
+ */
198
+ html,
199
+ body,
200
+ #root {
201
+ margin: 0;
202
+ min-height: 100%;
203
+ }
204
+ `;
205
+
206
+ /**
207
+ * Files the scaffolder wrote purely to dress its demo, which stop being true
208
+ * the moment the demo is replaced. Vite only — create-next-app's globals.css
209
+ * may hold the Tailwind directives the user asked for, so it is never touched.
210
+ */
211
+ export function starterCleanup(framework, entryPath) {
212
+ if (framework !== "vite") return { rewrite: [], remove: [] };
213
+ const dir = dirname(entryPath);
214
+ return {
215
+ rewrite: [{ path: join(dir, "index.css"), source: VITE_RESET }],
216
+ // Styled the old App.tsx, which no longer exists to import it.
217
+ remove: [join(dir, "App.css")],
218
+ };
219
+ }
@@ -0,0 +1,32 @@
1
+ /* Pure and dependency-free: validate-core runs in the browser too. */
2
+
3
+ /** Levenshtein distance, giving up (returning `cap`) once it can't come in under it. */
4
+ export function editDistance(a, b, cap = Infinity) {
5
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
6
+ for (let i = 1; i <= a.length; i++) {
7
+ const row = [i];
8
+ let rowMin = i;
9
+ for (let j = 1; j <= b.length; j++) {
10
+ row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
11
+ if (row[j] < rowMin) rowMin = row[j];
12
+ }
13
+ if (rowMin >= cap) return cap;
14
+ prev = row;
15
+ }
16
+ return Math.min(prev[b.length], cap);
17
+ }
18
+
19
+ /** The nearest candidate within edit distance 2, for "did you mean" hints; null if none. */
20
+ export function suggest(value, candidates) {
21
+ let best = null;
22
+ let bestDistance = 3;
23
+ for (const candidate of candidates) {
24
+ if (Math.abs(candidate.length - value.length) >= bestDistance) continue;
25
+ const distance = editDistance(value, candidate, bestDistance);
26
+ if (distance < bestDistance) {
27
+ bestDistance = distance;
28
+ best = candidate;
29
+ }
30
+ }
31
+ return best;
32
+ }
package/src/lib/ui.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import readline from "node:readline/promises";
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { banner } from "./menu.mjs";
2
5
 
3
- /**
4
- * Terminal output helpers — raw ANSI, no dependencies. Colors switch off for
5
- * non-TTY output (piped) and when NO_COLOR is set, per convention.
6
- */
6
+ /** Terminal output helpers: raw ANSI, off when piped or when NO_COLOR is set. */
7
7
 
8
8
  const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
9
9
  const wrap = (open, close) => (text) => (useColor ? `\x1b[${open}m${text}\x1b[${close}m` : String(text));
@@ -19,18 +19,26 @@ export const ok = (message) => console.log(`${green("✓")} ${message}`);
19
19
  export const warn = (message) => console.log(`${yellow("!")} ${message}`);
20
20
  export const info = (message) => console.log(`${cyan("→")} ${message}`);
21
21
 
22
- /** Thrown by fail() once the message is printed — index.mjs stops quietly on it. */
22
+ /**
23
+ * One line: the CLI's name and version, and what this command is
24
+ * about to do. In a terminal only: piped output and CI logs stay as they were.
25
+ */
26
+ export function printBanner(subtitle) {
27
+ if (!process.stdout.isTTY) return;
28
+ const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
29
+ console.log(banner({ version, subtitle, color: useColor }));
30
+ }
31
+
32
+ /** Forward slashes on every platform: shown paths and import specifiers both want them. */
33
+ export const posix = (path) => path.split("\\").join("/");
34
+
35
+ /** Thrown by fail() once the message is printed; index.mjs stops quietly on it. */
23
36
  export class CliExit extends Error {}
24
37
 
25
38
  /**
26
- * Print the error and stop — the CLI's only failure path.
27
- *
28
- * Sets an exit code and unwinds rather than calling process.exit(): on Windows,
29
- * process.exit() after any fetch() trips a libuv assertion
30
- * (`!(handle->flags & UV_HANDLE_CLOSING)`) and reports exit 127 instead of 1.
31
- * Verified in isolation — fetch alone is clean, exit alone is clean, only the
32
- * pair crashes. Unwinding lets the event loop drain, which also means finally
33
- * blocks and closePrompts() actually run.
39
+ * Print the error and stop: the CLI's only failure path. It unwinds instead of
40
+ * calling process.exit(), which on Windows trips a libuv assertion (exit 127)
41
+ * when a fetch() handle is still open.
34
42
  */
35
43
  export function fail(message) {
36
44
  console.error(`${red("✗")} ${message}`);
@@ -38,53 +46,79 @@ export function fail(message) {
38
46
  throw new CliExit(message);
39
47
  }
40
48
 
41
- /*
42
- * One shared readline for the whole process, draining lines through a queue.
43
- * readline reads ahead, so with piped input it emits the next line's `line`
44
- * event in the gap between one prompt resolving and the next registering its
45
- * listener (e.g. select → confirm) — a per-question `rl.question` loses it. A
46
- * standing `line` listener queues those reads instead. Callers run
47
- * closePrompts() when done so the open stream stops keeping the process alive.
49
+ /* ---- prompts ------------------------------------------------------------------ */
50
+
51
+ let assumeYes = false;
52
+
53
+ /** Set by the global -y/--yes: no prompt is shown and each takes its default. */
54
+ export function setAssumeYes(value) {
55
+ assumeYes = value;
56
+ }
57
+
58
+ export const isAssumeYes = () => assumeYes;
59
+
60
+ const PROMPT_CHILD = fileURLToPath(new URL("./prompt-child.mjs", import.meta.url));
61
+
62
+ /**
63
+ * Read one line from the user, or null when there is no one to answer (stdin
64
+ * at EOF, as in CI). Reads in a child process so this one never touches stdin;
65
+ * prompt-child.mjs explains why.
48
66
  */
49
- let sharedRl = null;
50
- let lineQueue = [];
51
- let lineWaiter = null;
52
-
53
- function ask(promptText) {
54
- if (!sharedRl) {
55
- sharedRl = readline.createInterface({ input: process.stdin, output: process.stdout });
56
- sharedRl.on("line", (line) => {
57
- if (lineWaiter) { const resolve = lineWaiter; lineWaiter = null; resolve(line); }
58
- else lineQueue.push(line);
59
- });
60
- // EOF (piped input exhausted): unblock a pending prompt with an empty answer.
61
- sharedRl.on("close", () => { if (lineWaiter) { const resolve = lineWaiter; lineWaiter = null; resolve(""); } });
67
+ export function ask(promptText) {
68
+ const result = spawnSync(process.execPath, [PROMPT_CHILD, promptText], {
69
+ stdio: ["inherit", "pipe", "inherit"],
70
+ encoding: "utf8",
71
+ });
72
+ if (result.status !== 0) {
73
+ if (result.status === 3) process.stderr.write("\n");
74
+ return null;
62
75
  }
63
- process.stdout.write(promptText);
64
- if (lineQueue.length) return Promise.resolve(lineQueue.shift());
65
- return new Promise((resolve) => { lineWaiter = resolve; });
76
+ return result.stdout.trim();
66
77
  }
67
78
 
68
- export function closePrompts() {
69
- sharedRl?.close();
70
- sharedRl = null;
71
- lineQueue = [];
72
- lineWaiter = null;
79
+ const noAnswer = (question, hint) =>
80
+ fail(`No answer to "${question}": there is no input to read.${hint ? ` ${hint}` : ""}`);
81
+
82
+ /**
83
+ * An arrow-key menu in a terminal, run in the prompt child like ask(). The
84
+ * chosen index; null when there is no terminal to draw it in. Cancelling
85
+ * stops the command.
86
+ */
87
+ export function menu(question, options, index = 0) {
88
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
89
+ const spec = JSON.stringify({ question, options: options.map(({ label, hint }) => ({ label, hint })), index, color: useColor });
90
+ const result = spawnSync(process.execPath, [PROMPT_CHILD, "--menu", spec], {
91
+ stdio: ["inherit", "pipe", "inherit"],
92
+ encoding: "utf8",
93
+ });
94
+ if (result.status === 130) fail("Cancelled.");
95
+ if (result.status !== 0) return null;
96
+ return Number(result.stdout.trim());
73
97
  }
74
98
 
75
- /** y/N prompt; default no. */
76
- export async function confirm(question) {
77
- const answer = await ask(`${question} ${dim("(y/N)")} `);
78
- return /^y(es)?$/i.test(answer.trim());
99
+ /** Yes or no; default no. Always yes under --yes. `hint` says how to answer non-interactively. */
100
+ export async function confirm(question, { hint = "Pass --yes to proceed without prompts." } = {}) {
101
+ if (assumeYes) return true;
102
+ const chosen = menu(question, [{ label: "Yes" }, { label: "No" }], 1);
103
+ if (chosen !== null) return chosen === 0;
104
+ const answer = ask(`${question} ${dim("(y/N)")} `);
105
+ if (answer === null) noAnswer(question, hint);
106
+ return /^y(es)?$/i.test(answer);
79
107
  }
80
108
 
81
109
  /**
82
- * Numbered single-choice prompt. `options` is [{ value, label }].
83
- * Returns the chosen value, or null if the answer isn't a listed number.
110
+ * Single-choice prompt. `options` is [{ value, label, hint? }]. An arrow-key
111
+ * menu in a terminal; a numbered prompt otherwise, which returns null if the
112
+ * answer isn't a listed number. Under --yes, or with no input, it stops with
113
+ * `hint`: a choice has no safe default.
84
114
  */
85
- export async function select(question, options) {
115
+ export async function select(question, options, { hint } = {}) {
116
+ if (assumeYes) fail(`"${question}" needs an answer, and --yes can't pick one.${hint ? ` ${hint}` : ""}`);
117
+ const chosen = menu(question, options);
118
+ if (chosen !== null) return options[chosen]?.value ?? null;
86
119
  console.log(question);
87
120
  options.forEach((o, i) => console.log(` ${cyan(String(i + 1))} ${o.label}`));
88
- const answer = await ask(`${dim("Enter a number:")} `);
89
- return options[Number(answer.trim()) - 1]?.value ?? null;
121
+ const answer = ask(`${dim("Enter a number:")} `);
122
+ if (answer === null) noAnswer(question, hint);
123
+ return options[Number(answer) - 1]?.value ?? null;
90
124
  }
@@ -0,0 +1,48 @@
1
+ /** One finding. `line` is 1-based, `column` 1-based; both are 0 when a position is unknown. */
2
+ export interface Finding {
3
+ /** Stable rule id, e.g. "unknown-import", "invalid-keyword-value", "missing-alt". */
4
+ code: string;
5
+ file: string;
6
+ line: number;
7
+ column: number;
8
+ message: string;
9
+ /** The astralis-ui component the finding is on, as the page names it ("Card.Body"); absent for imports and plain elements. */
10
+ component?: string;
11
+ /** The attribute the finding is on, when it is on one. */
12
+ prop?: string;
13
+ /** That attribute's literal value, when it is a literal. */
14
+ value?: string | number;
15
+ }
16
+
17
+ export interface ValidationResult {
18
+ /** Mistakes that render wrong or not at all. Sorted by position. */
19
+ errors: Finding[];
20
+ /** Doctrine nudges and claims file-local analysis can't prove. Sorted by position. */
21
+ warnings: Finding[];
22
+ }
23
+
24
+ export interface ValidateOptions {
25
+ /** Also warn on valid colours that bypass the tokens (the drift check). Default false. */
26
+ strictTokens?: boolean;
27
+ }
28
+
29
+ declare const prepared: unique symbol;
30
+
31
+ /** Lookup tables built from one spec by prepareSpec(); reuse it across files. */
32
+ export interface PreparedSpec {
33
+ readonly [prepared]: true;
34
+ }
35
+
36
+ /**
37
+ * Build the lookup tables for one parsed astralis-ui `dist/system-spec.json`.
38
+ * Takes `unknown` because the spec arrives from disk or the network as JSON.
39
+ */
40
+ export function prepareSpec(spec: unknown): PreparedSpec;
41
+
42
+ /** Validate one TSX/JSX source. Pure, and safe to run in a browser. */
43
+ export function validateSource(
44
+ source: string,
45
+ prepared: PreparedSpec,
46
+ filePath?: string,
47
+ opts?: ValidateOptions,
48
+ ): ValidationResult;