astralis-cli 0.4.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.
- package/CHANGELOG.md +167 -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 +652 -0
- package/src/lib/validate.d.mts +33 -0
- package/src/lib/validate.mjs +8 -0
package/src/index.mjs
CHANGED
|
@@ -1,65 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { cyan, dim, red, fail, CliExit } from "./lib/ui.mjs";
|
|
4
|
+
import { COMMANDS } from "./lib/commands.mjs";
|
|
5
|
+
import { mainHelp } from "./lib/args.mjs";
|
|
6
|
+
import { suggest } from "./lib/suggest.mjs";
|
|
6
7
|
|
|
7
|
-
const
|
|
8
|
+
const MODULES = {
|
|
8
9
|
create: () => import("./commands/create.mjs"),
|
|
9
10
|
init: () => import("./commands/init.mjs"),
|
|
10
11
|
add: () => import("./commands/add.mjs"),
|
|
11
12
|
theme: () => import("./commands/theme.mjs"),
|
|
13
|
+
validate: () => import("./commands/validate.mjs"),
|
|
14
|
+
report: () => import("./commands/report.mjs"),
|
|
12
15
|
"connect-mcp": () => import("./commands/connect-mcp.mjs"),
|
|
13
16
|
};
|
|
14
17
|
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
${bold("Usage")}
|
|
19
|
-
astralis <command> [options]
|
|
20
|
-
|
|
21
|
-
${bold("Commands")}
|
|
22
|
-
${cyan("create <name>")} scaffold a new project with the official scaffolder
|
|
23
|
-
(create-next-app / create-vite) and wire Astralis into it
|
|
24
|
-
${dim("--framework next|vite Next.js, or React via Vite")}
|
|
25
|
-
${dim("--no-starter keep the scaffolder's demo page")}
|
|
26
|
-
${dim("extra args pass straight to the scaffolder")}
|
|
27
|
-
${cyan("init")} wire astralis-ui into an existing React project
|
|
28
|
-
${dim("Next.js, or React + Vite")}
|
|
29
|
-
${dim("--dry-run show the changes without writing")}
|
|
30
|
-
${cyan("add <block>...")} copy a block's source into this project
|
|
31
|
-
${dim("--list every available block, by category")}
|
|
32
|
-
${dim("--dir <path> where to write (default [src/]components/blocks)")}
|
|
33
|
-
${dim("--overwrite · --dry-run · --registry <url>")}
|
|
34
|
-
${cyan("theme")} generate a static theme stylesheet from a seed
|
|
35
|
-
${dim("--brand/--gray <hex> · --font-heading/-body/-mono <stack>")}
|
|
36
|
-
${dim("--radius/--spacing/--font-scale/--motion <n>")}
|
|
37
|
-
${dim("--out <file> (default astralis-theme.css) · --force")}
|
|
38
|
-
${dim("run `astralis theme --help` for the full list")}
|
|
39
|
-
${cyan("connect-mcp")} connect a client to the Astralis docs server
|
|
40
|
-
${dim("prompts for the client, then configures it for you")}
|
|
41
|
-
${dim("--client claude-code|codex|cursor|claude-desktop|antigravity")}
|
|
42
|
-
${dim(" skip the prompt and pick the client directly")}
|
|
43
|
-
|
|
44
|
-
${bold("Docs")} ${cyan("https://astralis-zeta.vercel.app/docs")}
|
|
45
|
-
`;
|
|
46
|
-
|
|
47
|
-
const [command, ...rest] = process.argv.slice(2);
|
|
18
|
+
const [name, ...rest] = process.argv.slice(2);
|
|
19
|
+
const debug = process.argv.includes("--debug");
|
|
48
20
|
|
|
49
21
|
try {
|
|
50
|
-
if (!
|
|
51
|
-
console.log(
|
|
52
|
-
} else if (
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
const { run } = await COMMANDS[command]();
|
|
22
|
+
if (!name || name === "--help" || name === "-h" || name === "help") {
|
|
23
|
+
console.log(mainHelp(COMMANDS));
|
|
24
|
+
} else if (name === "--version" || name === "-v") {
|
|
25
|
+
console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
|
|
26
|
+
} else if (MODULES[name]) {
|
|
27
|
+
const { run } = await MODULES[name]();
|
|
57
28
|
await run(rest);
|
|
58
29
|
} else {
|
|
59
|
-
|
|
30
|
+
const near = suggest(name, Object.keys(MODULES));
|
|
31
|
+
fail(`Unknown command "${name}".${near ? ` Did you mean "${near}"?` : ""} Run ${cyan("astralis --help")} for the list.`);
|
|
60
32
|
}
|
|
61
33
|
} catch (error) {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
34
|
+
if (!(error instanceof CliExit)) {
|
|
35
|
+
process.exitCode = 1;
|
|
36
|
+
if (debug) {
|
|
37
|
+
console.error(error);
|
|
38
|
+
} else {
|
|
39
|
+
console.error(`${red("✗")} Unexpected error: ${error?.message ?? error}`);
|
|
40
|
+
console.error(dim(` Run it again with --debug for the stack trace.`));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
65
43
|
}
|
package/src/lib/args.mjs
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { GLOBAL_OPTIONS, DOCS_URL } from "./commands.mjs";
|
|
2
|
+
import { bold, cyan, dim, fail, setAssumeYes } from "./ui.mjs";
|
|
3
|
+
import { suggest } from "./suggest.mjs";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The one argument parser every command uses. Accepts `--name value`,
|
|
7
|
+
* `--name=value` and the global flags; a string value may itself start with a
|
|
8
|
+
* dash (`--font-body "-apple-system, sans-serif"`).
|
|
9
|
+
*
|
|
10
|
+
* Returns { values, positionals, forwarded }, or null once --help is printed.
|
|
11
|
+
* A `passthrough` command collects unknown options, in order, into `forwarded`
|
|
12
|
+
* instead of rejecting them.
|
|
13
|
+
*/
|
|
14
|
+
export function parseCommandArgs(command, argv) {
|
|
15
|
+
const options = [...command.options, ...GLOBAL_OPTIONS];
|
|
16
|
+
const byName = new Map(options.map((o) => [o.name, o]));
|
|
17
|
+
const byShort = new Map(options.filter((o) => o.short).map((o) => [o.short, o]));
|
|
18
|
+
const values = Object.fromEntries(options.filter((o) => o.type === "boolean").map((o) => [o.name, false]));
|
|
19
|
+
const positionals = [];
|
|
20
|
+
const forwarded = [];
|
|
21
|
+
const usageHint = `Run ${cyan(`astralis ${command.name} --help`)} for its options.`;
|
|
22
|
+
|
|
23
|
+
for (let i = 0; i < argv.length; i++) {
|
|
24
|
+
const arg = argv[i];
|
|
25
|
+
if (arg === "--") {
|
|
26
|
+
(command.passthrough ? forwarded : positionals).push(...argv.slice(i + 1));
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let option = null;
|
|
31
|
+
let inline;
|
|
32
|
+
if (arg.startsWith("--")) {
|
|
33
|
+
const eq = arg.indexOf("=");
|
|
34
|
+
const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
|
|
35
|
+
inline = eq === -1 ? undefined : arg.slice(eq + 1);
|
|
36
|
+
option = byName.get(name) ?? null;
|
|
37
|
+
if (!option) {
|
|
38
|
+
if (command.passthrough) {
|
|
39
|
+
forwarded.push(arg);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const near = suggest(name, [...byName.keys()]);
|
|
43
|
+
fail(`Unknown option --${name} for astralis ${command.name}.${near ? ` Did you mean --${near}?` : ""}\n ${usageHint}`);
|
|
44
|
+
}
|
|
45
|
+
} else if (/^-[a-zA-Z]$/.test(arg)) {
|
|
46
|
+
option = byShort.get(arg.slice(1)) ?? null;
|
|
47
|
+
if (!option) {
|
|
48
|
+
if (command.passthrough) {
|
|
49
|
+
forwarded.push(arg);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
fail(`Unknown option ${arg} for astralis ${command.name}.\n ${usageHint}`);
|
|
53
|
+
}
|
|
54
|
+
} else if (command.passthrough && arg.startsWith("-")) {
|
|
55
|
+
forwarded.push(arg);
|
|
56
|
+
continue;
|
|
57
|
+
} else {
|
|
58
|
+
if (command.passthrough && positionals.length >= command.maxPositionals) forwarded.push(arg);
|
|
59
|
+
else positionals.push(arg);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (option.type === "boolean") {
|
|
64
|
+
if (inline !== undefined) fail(`--${option.name} takes no value.\n ${usageHint}`);
|
|
65
|
+
values[option.name] = true;
|
|
66
|
+
} else {
|
|
67
|
+
const value = inline ?? argv[++i];
|
|
68
|
+
if (value === undefined) fail(`--${option.name} needs a value${option.arg ? ` (${option.arg})` : ""}.\n ${usageHint}`);
|
|
69
|
+
values[option.name] = value;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (values.help) {
|
|
74
|
+
console.log(commandHelp(command));
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
if (positionals.length > command.maxPositionals) {
|
|
78
|
+
const extra = positionals.slice(command.maxPositionals).map((p) => `"${p}"`).join(", ");
|
|
79
|
+
fail(`astralis ${command.name} doesn't take ${extra}.\n ${usageHint}`);
|
|
80
|
+
}
|
|
81
|
+
if (values.yes) setAssumeYes(true);
|
|
82
|
+
return { values, positionals, forwarded };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/* ---- help text, rendered from the same table -------------------------------- */
|
|
86
|
+
|
|
87
|
+
const flagLabel = (o) =>
|
|
88
|
+
`${o.short ? `-${o.short}, ` : ""}--${o.name}${o.type === "string" ? ` <${o.arg ?? "value"}>` : ""}`;
|
|
89
|
+
|
|
90
|
+
function optionLines(options) {
|
|
91
|
+
const width = Math.max(...options.map((o) => flagLabel(o).length)) + 2;
|
|
92
|
+
return options.map((o) => {
|
|
93
|
+
const extra = o.default ? dim(` (default: ${o.default})`) : "";
|
|
94
|
+
return ` ${flagLabel(o).padEnd(width)}${o.description}${extra}`;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function commandHelp(command) {
|
|
99
|
+
const lines = [`${bold("Usage")} astralis ${command.name}${command.args ? ` ${command.args}` : ""} [options]`, ""];
|
|
100
|
+
lines.push(` ${command.summary}.`, "");
|
|
101
|
+
|
|
102
|
+
const groups = [...new Set(command.options.map((o) => o.group ?? "Options"))];
|
|
103
|
+
for (const group of groups) {
|
|
104
|
+
lines.push(` ${bold(group)}`, ...optionLines(command.options.filter((o) => (o.group ?? "Options") === group)), "");
|
|
105
|
+
}
|
|
106
|
+
lines.push(` ${bold("Global options")}`, ...optionLines(GLOBAL_OPTIONS), "");
|
|
107
|
+
|
|
108
|
+
for (const note of command.notes ?? []) lines.push(` ${dim(note)}`);
|
|
109
|
+
if (command.notes?.length) lines.push("");
|
|
110
|
+
lines.push(` ${bold("Examples")}`, ...command.examples.map((e) => ` ${cyan(e)}`), "");
|
|
111
|
+
lines.push(` ${dim("Docs")} ${cyan(DOCS_URL)}`);
|
|
112
|
+
return lines.join("\n");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function mainHelp(commands) {
|
|
116
|
+
const label = (c) => `${c.name}${c.args ? ` ${c.args}` : ""}`;
|
|
117
|
+
const width = Math.max(...commands.map((c) => label(c).length)) + 2;
|
|
118
|
+
const versionFlag = { name: "version", short: "v", type: "boolean", description: "Print the CLI version." };
|
|
119
|
+
return [
|
|
120
|
+
"",
|
|
121
|
+
`${bold("astralis")} — setup and tooling for Astralis UI`,
|
|
122
|
+
"",
|
|
123
|
+
`${bold("Usage")} astralis <command> [options]`,
|
|
124
|
+
"",
|
|
125
|
+
` ${bold("Commands")}`,
|
|
126
|
+
...commands.map((c) => ` ${cyan(label(c).padEnd(width))}${c.summary}`),
|
|
127
|
+
"",
|
|
128
|
+
` ${bold("Global options")}`,
|
|
129
|
+
...optionLines([...GLOBAL_OPTIONS, versionFlag]),
|
|
130
|
+
"",
|
|
131
|
+
` Run ${cyan("astralis <command> --help")} for a command's options.`,
|
|
132
|
+
` ${dim("Docs")} ${cyan(DOCS_URL)}`,
|
|
133
|
+
"",
|
|
134
|
+
].join("\n");
|
|
135
|
+
}
|
package/src/lib/aria.mjs
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/* ==========================================================================
|
|
2
|
+
ARIA 1.2 vocabulary — the finite sets the a11y checks close over.
|
|
3
|
+
A typo'd aria attribute or role is the same failure class as a dead
|
|
4
|
+
astralis class: it typechecks (React passes aria-* through untouched),
|
|
5
|
+
renders, and assistive technology hears nothing.
|
|
6
|
+
========================================================================== */
|
|
7
|
+
|
|
8
|
+
export const ARIA_ATTRS = new Set([
|
|
9
|
+
"aria-activedescendant", "aria-atomic", "aria-autocomplete",
|
|
10
|
+
"aria-braillelabel", "aria-brailleroledescription", "aria-busy",
|
|
11
|
+
"aria-checked", "aria-colcount", "aria-colindex", "aria-colindextext",
|
|
12
|
+
"aria-colspan", "aria-controls", "aria-current", "aria-describedby",
|
|
13
|
+
"aria-description", "aria-details", "aria-disabled", "aria-dropeffect",
|
|
14
|
+
"aria-errormessage", "aria-expanded", "aria-flowto", "aria-grabbed",
|
|
15
|
+
"aria-haspopup", "aria-hidden", "aria-invalid", "aria-keyshortcuts",
|
|
16
|
+
"aria-label", "aria-labelledby", "aria-level", "aria-live", "aria-modal",
|
|
17
|
+
"aria-multiline", "aria-multiselectable", "aria-orientation", "aria-owns",
|
|
18
|
+
"aria-placeholder", "aria-posinset", "aria-pressed", "aria-readonly",
|
|
19
|
+
"aria-relevant", "aria-required", "aria-roledescription", "aria-rowcount",
|
|
20
|
+
"aria-rowindex", "aria-rowindextext", "aria-rowspan", "aria-selected",
|
|
21
|
+
"aria-setsize", "aria-sort", "aria-valuemax", "aria-valuemin",
|
|
22
|
+
"aria-valuenow", "aria-valuetext",
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
/** Concrete (non-abstract) ARIA roles — abstract roles are invalid in markup. */
|
|
26
|
+
export const ROLES = new Set([
|
|
27
|
+
"alert", "alertdialog", "application", "article", "banner", "blockquote",
|
|
28
|
+
"button", "caption", "cell", "checkbox", "code", "columnheader", "combobox",
|
|
29
|
+
"complementary", "contentinfo", "definition", "deletion", "dialog",
|
|
30
|
+
"directory", "document", "emphasis", "feed", "figure", "form", "generic",
|
|
31
|
+
"grid", "gridcell", "group", "heading", "img", "insertion", "link", "list",
|
|
32
|
+
"listbox", "listitem", "log", "main", "marquee", "math", "menu", "menubar",
|
|
33
|
+
"menuitem", "menuitemcheckbox", "menuitemradio", "meter", "navigation",
|
|
34
|
+
"none", "note", "option", "paragraph", "presentation", "progressbar",
|
|
35
|
+
"radio", "radiogroup", "region", "row", "rowgroup", "rowheader",
|
|
36
|
+
"scrollbar", "search", "searchbox", "separator", "slider", "spinbutton",
|
|
37
|
+
"status", "strong", "subscript", "superscript", "switch", "tab", "table",
|
|
38
|
+
"tablist", "tabpanel", "term", "textbox", "time", "timer", "toolbar",
|
|
39
|
+
"tooltip", "tree", "treegrid", "treeitem",
|
|
40
|
+
]);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Rule: a component whose type requires children must be given some (requiresChildren, spec 3+). */
|
|
2
|
+
|
|
3
|
+
/** Whether a JSX child renders: whitespace spanning a line break and `{/* comments *\/}` do not. */
|
|
4
|
+
function renders(child) {
|
|
5
|
+
if (child.type === "JSXText") return child.value.trim() !== "" || !child.value.includes("\n");
|
|
6
|
+
if (child.type === "JSXExpressionContainer") return child.expression.type !== "JSXEmptyExpression";
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function checkRequiredChildren(ctx, identity, element) {
|
|
11
|
+
const comp = identity.specName ? ctx.spec.components[identity.specName] : null;
|
|
12
|
+
if (!comp?.requiresChildren) return;
|
|
13
|
+
const opening = element.openingElement;
|
|
14
|
+
// A spread may carry children, and an explicit children prop supplies them.
|
|
15
|
+
const supplied = opening.attributes.some(
|
|
16
|
+
(attr) => attr.type === "JSXSpreadAttribute" || (attr.name.type === "JSXIdentifier" && attr.name.name === "children"),
|
|
17
|
+
);
|
|
18
|
+
if (supplied || element.children.some(renders)) return;
|
|
19
|
+
const parts = ctx.spec.components[identity.owner ?? identity.specName]?.anatomy?.children;
|
|
20
|
+
const hint = parts && !identity.part ? ` — compose its parts (${parts.join(", ")})` : "";
|
|
21
|
+
ctx.error("missing-children", opening,
|
|
22
|
+
`${identity.display} requires children: its type makes them mandatory, so this fails type checking and renders empty${hint}`);
|
|
23
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { ok, info, fail, bold, dim, cyan, posix } from "./ui.mjs";
|
|
4
|
+
import { runCommand } from "./run.mjs";
|
|
5
|
+
import { CHECK_NAME, WORKFLOW_FILE, inspectProject, readText, validateScript, withScript, workflowYaml } from "./ci.mjs";
|
|
6
|
+
|
|
7
|
+
const VALIDATE_COMMAND = "astralis validate";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The --ci half of `astralis init`: astralis-cli pinned as a devDependency, a
|
|
11
|
+
* package.json script that runs the validator, and a GitHub Actions workflow
|
|
12
|
+
* that runs the script. Reports through init's buffered `out` so a re-run that
|
|
13
|
+
* changes nothing stays one line. Returns notes that need the user's attention.
|
|
14
|
+
*/
|
|
15
|
+
export function setUpCi({ cwd, pkg, pm, dryRun, force, out }) {
|
|
16
|
+
const notes = [];
|
|
17
|
+
const had = (name) => Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
|
|
18
|
+
|
|
19
|
+
if (had("astralis-cli")) {
|
|
20
|
+
out.step(() => ok("astralis-cli already in dependencies"));
|
|
21
|
+
} else if (dryRun) {
|
|
22
|
+
out.changed();
|
|
23
|
+
out.step(() => info(`would run: ${pm} add -D astralis-cli`));
|
|
24
|
+
} else {
|
|
25
|
+
out.changed();
|
|
26
|
+
out.flush();
|
|
27
|
+
info(`installing astralis-cli with ${pm}, pinned for CI…`);
|
|
28
|
+
const result = runCommand(pm, ["add", "-D", "astralis-cli"], { cwd });
|
|
29
|
+
if (result.status !== 0) fail(`${pm} add -D astralis-cli failed — install it manually, then re-run init --ci.`);
|
|
30
|
+
ok("astralis-cli installed as a devDependency");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The install above rewrites package.json, so read it again before adding to it.
|
|
34
|
+
const packagePath = join(cwd, "package.json");
|
|
35
|
+
const packageText = readFileSync(packagePath, "utf8");
|
|
36
|
+
const script = validateScript(JSON.parse(packageText).scripts);
|
|
37
|
+
if (!script) {
|
|
38
|
+
notes.push(`package.json's "validate" and "astralis:validate" scripts both do something else — add one that runs \`${VALIDATE_COMMAND}\` and re-run init --ci`);
|
|
39
|
+
return notes;
|
|
40
|
+
}
|
|
41
|
+
if (!script.isNew) {
|
|
42
|
+
out.step(() => ok(`"${script.name}" script already runs the validator`));
|
|
43
|
+
} else {
|
|
44
|
+
out.changed();
|
|
45
|
+
out.step(() => ok(`${dryRun ? "would add" : "added"} "${script.name}": "${VALIDATE_COMMAND}" ${dim("(package.json)")}`));
|
|
46
|
+
if (!dryRun) writeFileSync(packagePath, withScript(packageText, script.name, VALIDATE_COMMAND));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const project = inspectProject(cwd, pkg, pm);
|
|
50
|
+
const root = project.gitRoot ?? cwd;
|
|
51
|
+
const shown = posix(join(".github", "workflows", WORKFLOW_FILE));
|
|
52
|
+
const path = join(root, shown);
|
|
53
|
+
const yaml = workflowYaml(project, script.name);
|
|
54
|
+
const existing = readText(path);
|
|
55
|
+
|
|
56
|
+
if (existing === yaml) {
|
|
57
|
+
out.step(() => ok(`${shown} already present`));
|
|
58
|
+
} else if (existing !== null && !force) {
|
|
59
|
+
notes.push(`${shown} already exists and differs from what init would write; it was left alone (--force replaces it)`);
|
|
60
|
+
} else {
|
|
61
|
+
out.changed();
|
|
62
|
+
out.step(() => ok(`${dryRun ? "would write" : existing === null ? "wrote" : "replaced"} ${shown}${project.subdir ? dim(` (at the repository root; runs in ${project.subdir})`) : ""}`));
|
|
63
|
+
if (!dryRun) {
|
|
64
|
+
mkdirSync(join(root, ".github", "workflows"), { recursive: true });
|
|
65
|
+
writeFileSync(path, yaml);
|
|
66
|
+
}
|
|
67
|
+
out.after(() => {
|
|
68
|
+
console.log(`\n${bold("CI:")} push, then make ${cyan(`"${CHECK_NAME}"`)} a required status check so a failing run blocks the merge:`);
|
|
69
|
+
console.log(` GitHub → Settings → Rules → Rulesets (or Branches → branch protection) → Require status checks to pass.`);
|
|
70
|
+
if (!project.gitRoot) console.log(dim(" This folder isn't a git repository yet; GitHub runs the workflow once it is pushed as one."));
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (!project.lockfile) {
|
|
75
|
+
notes.push(`no ${pm} lockfile found — commit one so CI installs the same versions you tested`);
|
|
76
|
+
}
|
|
77
|
+
return notes;
|
|
78
|
+
}
|
package/src/lib/ci.mjs
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, relative } from "node:path";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { posix } from "./ui.mjs";
|
|
5
|
+
|
|
6
|
+
/** What `astralis init --ci` writes, and where. */
|
|
7
|
+
|
|
8
|
+
export const WORKFLOW_FILE = "astralis-validate.yml";
|
|
9
|
+
export const CHECK_NAME = "Astralis validate";
|
|
10
|
+
|
|
11
|
+
const ACTIONS = {
|
|
12
|
+
checkout: "actions/checkout@v7",
|
|
13
|
+
node: "actions/setup-node@v7",
|
|
14
|
+
pnpm: "pnpm/action-setup@v6",
|
|
15
|
+
bun: "oven-sh/setup-bun@v2",
|
|
16
|
+
};
|
|
17
|
+
const NODE_VERSION = 22;
|
|
18
|
+
|
|
19
|
+
const LOCKFILES = {
|
|
20
|
+
npm: ["package-lock.json"],
|
|
21
|
+
pnpm: ["pnpm-lock.yaml"],
|
|
22
|
+
yarn: ["yarn.lock"],
|
|
23
|
+
bun: ["bun.lock", "bun.lockb"],
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const SCRIPT_NAMES = ["validate", "astralis:validate"];
|
|
27
|
+
const RUNS_ASTRALIS_VALIDATE = /(^|[\s;&|])(npx\s+)?astralis(-cli)?\s+validate\b/;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The package.json script the workflow runs: an existing one that already calls
|
|
31
|
+
* `astralis validate`, else the first free name. Null when every name is taken
|
|
32
|
+
* by something else, so nothing of the user's is overwritten.
|
|
33
|
+
*/
|
|
34
|
+
export function validateScript(scripts = {}) {
|
|
35
|
+
for (const name of SCRIPT_NAMES) {
|
|
36
|
+
if (scripts[name] !== undefined && RUNS_ASTRALIS_VALIDATE.test(scripts[name])) return { name, isNew: false };
|
|
37
|
+
}
|
|
38
|
+
const free = SCRIPT_NAMES.find((name) => scripts[name] === undefined);
|
|
39
|
+
return free ? { name: free, isNew: true } : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The nearest directory at or above `start` holding .git, or null outside a repository. */
|
|
43
|
+
export function findGitRoot(start) {
|
|
44
|
+
let dir = start;
|
|
45
|
+
for (;;) {
|
|
46
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
47
|
+
const parent = dirname(dir);
|
|
48
|
+
if (parent === dir) return null;
|
|
49
|
+
dir = parent;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const declaredManager = (pkg, name) => {
|
|
54
|
+
const match = /^([a-z]+)@(\d+)/.exec(pkg?.packageManager ?? "");
|
|
55
|
+
return match && match[1] === name ? Number(match[2]) : null;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
function localPnpmMajor(cwd) {
|
|
59
|
+
const result = spawnSync(process.platform === "win32" ? "pnpm.cmd" : "pnpm", ["--version"], {
|
|
60
|
+
cwd,
|
|
61
|
+
encoding: "utf8",
|
|
62
|
+
shell: process.platform === "win32",
|
|
63
|
+
});
|
|
64
|
+
const major = /^(\d+)\./.exec(result.stdout ?? "")?.[1];
|
|
65
|
+
return major ? Number(major) : null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Everything the workflow depends on, read from the project. `pnpmVersion` is
|
|
70
|
+
* null when package.json's packageManager already pins pnpm: pnpm/action-setup
|
|
71
|
+
* reads it there and refuses a second, conflicting version.
|
|
72
|
+
*/
|
|
73
|
+
export function inspectProject(cwd, pkg, pm) {
|
|
74
|
+
const lockfile = LOCKFILES[pm].find((name) => existsSync(join(cwd, name))) ?? null;
|
|
75
|
+
const gitRoot = findGitRoot(cwd);
|
|
76
|
+
const subdir = gitRoot && gitRoot !== cwd ? posix(relative(gitRoot, cwd)) : "";
|
|
77
|
+
const pnpmPinned = declaredManager(pkg, "pnpm") !== null;
|
|
78
|
+
return {
|
|
79
|
+
pm,
|
|
80
|
+
lockfile,
|
|
81
|
+
gitRoot,
|
|
82
|
+
subdir,
|
|
83
|
+
pnpmVersion: pm === "pnpm" && !pnpmPinned ? (localPnpmMajor(cwd) ?? 10) : null,
|
|
84
|
+
pnpmPinned,
|
|
85
|
+
yarnBerry: pm === "yarn" && ((declaredManager(pkg, "yarn") ?? 1) >= 2 || existsSync(join(cwd, ".yarnrc.yml"))),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function installCommand({ pm, lockfile, yarnBerry }) {
|
|
90
|
+
if (pm === "npm") return lockfile ? "npm ci" : "npm install";
|
|
91
|
+
if (pm === "pnpm") return "pnpm install --frozen-lockfile";
|
|
92
|
+
if (pm === "yarn") return yarnBerry ? "yarn install --immutable" : "yarn install --frozen-lockfile";
|
|
93
|
+
return "bun install --frozen-lockfile";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const inSubdir = (subdir, file) => (subdir ? `${subdir}/${file}` : file);
|
|
97
|
+
|
|
98
|
+
/** The workflow file's text. Pure: every input comes from inspectProject(). */
|
|
99
|
+
export function workflowYaml(project, scriptName) {
|
|
100
|
+
const { pm, lockfile, subdir, pnpmVersion, pnpmPinned, yarnBerry } = project;
|
|
101
|
+
const steps = [` - uses: ${ACTIONS.checkout}`];
|
|
102
|
+
|
|
103
|
+
if (pm === "pnpm") {
|
|
104
|
+
const inputs = [];
|
|
105
|
+
if (pnpmVersion) inputs.push(`version: ${pnpmVersion}`);
|
|
106
|
+
if (pnpmPinned && subdir) inputs.push(`package_json_file: ${inSubdir(subdir, "package.json")}`);
|
|
107
|
+
steps.push(` - uses: ${ACTIONS.pnpm}${inputs.map((line, i) => `${i ? "" : "\n with:"}\n ${line}`).join("")}`);
|
|
108
|
+
}
|
|
109
|
+
if (pm === "yarn" && yarnBerry) steps.push(" - run: corepack enable");
|
|
110
|
+
if (pm === "bun") steps.push(` - uses: ${ACTIONS.bun}`);
|
|
111
|
+
|
|
112
|
+
const node = [`node-version: ${NODE_VERSION}`];
|
|
113
|
+
if (pm !== "bun" && lockfile) {
|
|
114
|
+
node.push(`cache: ${pm}`);
|
|
115
|
+
if (subdir) node.push(`cache-dependency-path: ${inSubdir(subdir, lockfile)}`);
|
|
116
|
+
}
|
|
117
|
+
steps.push(` - uses: ${ACTIONS.node}\n with:${node.map((line) => `\n ${line}`).join("")}`);
|
|
118
|
+
steps.push(` - run: ${installCommand(project)}`, ` - run: ${pm} run ${scriptName}`);
|
|
119
|
+
|
|
120
|
+
return [
|
|
121
|
+
`# Checks every pull request against the astralis-ui design system; written by`,
|
|
122
|
+
`# \`astralis init --ci\`. Make "${CHECK_NAME}" a required status check so a`,
|
|
123
|
+
`# failing run blocks the merge: GitHub → Settings → Rules (or Branches).`,
|
|
124
|
+
`name: ${CHECK_NAME}`,
|
|
125
|
+
"",
|
|
126
|
+
"on:",
|
|
127
|
+
" pull_request:",
|
|
128
|
+
" push:",
|
|
129
|
+
" branches: [main, master]",
|
|
130
|
+
"",
|
|
131
|
+
"permissions:",
|
|
132
|
+
" contents: read",
|
|
133
|
+
"",
|
|
134
|
+
"jobs:",
|
|
135
|
+
" validate:",
|
|
136
|
+
` name: ${CHECK_NAME}`,
|
|
137
|
+
" runs-on: ubuntu-latest",
|
|
138
|
+
...(subdir ? [" defaults:", " run:", ` working-directory: ${subdir}`] : []),
|
|
139
|
+
" steps:",
|
|
140
|
+
...steps,
|
|
141
|
+
"",
|
|
142
|
+
].join("\n");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** package.json with one script added, keeping the file's own indentation and final newline. */
|
|
146
|
+
export function withScript(packageJsonText, name, command) {
|
|
147
|
+
const pkg = JSON.parse(packageJsonText);
|
|
148
|
+
pkg.scripts = { ...pkg.scripts, [name]: command };
|
|
149
|
+
const indent = /^[ \t]+(?=")/m.exec(packageJsonText)?.[0] ?? " ";
|
|
150
|
+
const eol = packageJsonText.includes("\r\n") ? "\r\n" : "\n";
|
|
151
|
+
const text = JSON.stringify(pkg, null, indent).replaceAll("\n", eol);
|
|
152
|
+
return /\r?\n$/.test(packageJsonText) ? text + eol : text;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const readText = (path) => (existsSync(path) ? readFileSync(path, "utf8") : null);
|