astralis-cli 0.7.0 → 0.8.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 CHANGED
@@ -6,6 +6,23 @@ breaking changes; a patch never does.
6
6
  Versions marked **internal** were set in the repository but never published to
7
7
  npm. Their changes reached npm in the next published version.
8
8
 
9
+ ## 0.8.0 (2026-11-23)
10
+
11
+ ### Removed
12
+
13
+ - **`astralis report`.** Reporting a problem stays in the DevTools, on the Report screen. The `./snapshot` and `./github` entry points the DevTools use are unchanged.
14
+
15
+ ### Changed
16
+
17
+ - **When a command can't finish, it says how to.** `create`, `init`, `init --devtools`, `init --ci` and `theme` finish what they can when a file can't be found, read, edited or written, or an install fails. They then print why, numbered steps with the exact file and code, how to check, and the docs section that explains it. A failed install, read or write exits 1; a file shape the CLI leaves alone exits 0.
18
+ - **The starter page** has a plain welcome, and the docs site's logo.
19
+ - `init` and `theme` recognise `app/layout.js`, and `init --ci` no longer needs a Next.js or Vite project.
20
+
21
+ ### Fixed
22
+
23
+ - **`theme` before `init`** put the theme ahead of the library's stylesheet, so it did not apply. It now adds both imports, in order.
24
+ - `init` no longer says the provider wraps an entry file it could not parse.
25
+
9
26
  ## 0.7.0 (2026-11-22)
10
27
 
11
28
  Published with astralis-ui 0.11.0: `unknown-prop` reads the spec's new `ownProps`, `domProps` and `domAttributes`. With an older spec it stays silent.
package/README.md CHANGED
@@ -125,38 +125,6 @@ astralis validate src/components --json
125
125
  astralis validate --strict-tokens
126
126
  ```
127
127
 
128
- ### `astralis report <files...>`
129
-
130
- Report a problem to the Astralis maintainers, with a snapshot built from your source files.
131
-
132
- | Option | |
133
- | --- | --- |
134
- | `--title <text>` | The report's title. Asked for when omitted; required with --yes. |
135
- | `--happened <text>` | What happened. |
136
- | `--expected <text>` | What you expected instead. |
137
- | `--include-text` | Keep the text in your JSX; by default it is replaced by placeholders. |
138
- | `--no-findings` | Leave out the validator's findings for these files. |
139
- | `--out <file>` | Write the snapshot to a file instead of sending it. |
140
- | `--dry-run` | Print the snapshot and send nothing. |
141
- | `--add-to <issue>` | Add the report to this existing issue instead of opening a new one. |
142
- | `--new` | Open a new issue without checking for an existing one. |
143
- | `--link` | Print a link to GitHub's own new-issue form, filled in, instead of signing in; you submit it there. |
144
- | `--sign-out` | Forget the saved GitHub sign-in, and do nothing else. |
145
- | `--spec <path>` | Build against this system-spec.json. Default: the installed astralis-ui's. |
146
-
147
- It prints the exact JSON first and sends nothing until you confirm; --yes confirms without asking.
148
-
149
- It opens a GitHub issue from your own account. The first time, you sign in with a code on github.com.
150
-
151
- Before opening one it looks for an issue that already reports the same problem, and offers to add your report to it.
152
-
153
- Only literal props are recorded, and only those the spec describes; links, sources and handlers never are.
154
-
155
- ```bash
156
- astralis report app/page.tsx
157
- astralis report src/App.tsx --title "Card loses its border" --out snapshot.json
158
- ```
159
-
160
128
  ### `astralis connect-mcp`
161
129
 
162
130
  Connect an AI coding agent to the Astralis MCP docs server.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astralis-cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Setup and tooling CLI for Astralis UI — scaffold or wire up a project, add blocks, generate a static brand theme, validate code against the design system, connect the MCP server.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,7 +34,7 @@ function printCatalogue(blocks) {
34
34
  }
35
35
  console.log("");
36
36
  }
37
- console.log(` ${dim(`Add one with ${cyan("astralis add <id>")}`)}\n`);
37
+ console.log(` ${dim(`Add one with ${cyan("npx astralis-cli add <id>")}`)}\n`);
38
38
  }
39
39
 
40
40
  export async function run(argv) {
@@ -48,7 +48,7 @@ export async function run(argv) {
48
48
  if (values.list) return printCatalogue((await fetchIndex(base)).blocks);
49
49
 
50
50
  if (positionals.length === 0) {
51
- fail(`Name at least one block, or list them with ${cyan("astralis add --list")}.`);
51
+ fail(`Name at least one block, or list them with ${cyan("npx astralis-cli add --list")}.`);
52
52
  }
53
53
 
54
54
  const badIds = positionals.filter((id) => !isBlockId(id));
@@ -63,7 +63,7 @@ export async function run(argv) {
63
63
  if (!block) {
64
64
  fail(
65
65
  `No block called ${cyan(id)}.\n` +
66
- ` Run ${cyan("astralis add --list")} to see what exists.`,
66
+ ` Run ${cyan("npx astralis-cli add --list")} to see what exists.`,
67
67
  );
68
68
  }
69
69
  items.push(block);
@@ -133,7 +133,7 @@ export async function run(argv) {
133
133
  console.log("");
134
134
  warn(
135
135
  `astralis-ui is not in this project's dependencies — the block will not compile.\n` +
136
- ` Run ${cyan(`${install} astralis-ui`)}, or ${cyan("astralis init")} to wire it up fully.`,
136
+ ` Run ${cyan(`${install} astralis-ui`)}, or ${cyan("npx astralis-cli init")} to wire it up fully.`,
137
137
  );
138
138
  }
139
139
 
@@ -1,4 +1,4 @@
1
- import { existsSync, writeFileSync, rmSync } from "node:fs";
1
+ import { existsSync, rmSync } from "node:fs";
2
2
  import { join, relative } from "node:path";
3
3
  import { ok, warn, info, fail, bold, cyan, dim, ask, isAssumeYes, menu, posix, printBanner } from "../lib/ui.mjs";
4
4
  import { parseCommandArgs } from "../lib/args.mjs";
@@ -6,6 +6,8 @@ import { commandNamed } from "../lib/commands.mjs";
6
6
  import { runCommand, UnsafeArgumentError } from "../lib/run.mjs";
7
7
  import { findEntryFile } from "../lib/detect.mjs";
8
8
  import { starterFile, starterCleanup } from "../lib/starter.mjs";
9
+ import { DOCS, commandProblem, createGuide, formatGuide, printGuide, tryWrite } from "../lib/manual.mjs";
10
+ import { likelyEntry } from "../lib/wiring.mjs";
9
11
 
10
12
  /**
11
13
  * Scaffold a brand-new project and wire Astralis into it. We own NO project
@@ -96,6 +98,56 @@ function promptLanguage() {
96
98
  return answer === "2" || answer === "js" || answer === "javascript" ? VITE_TEMPLATES.js : VITE_TEMPLATES.ts;
97
99
  }
98
100
 
101
+ /** The welcome screen in place of the scaffolder's demo, or the steps that put a first page there. */
102
+ function writeStarter(cwd, framework, pm) {
103
+ const entry = findEntryFile(cwd, framework);
104
+ const { path, source } = starterFile(framework, entry?.path ?? join(cwd, likelyEntry(cwd, framework).file));
105
+ const shown = posix(relative(cwd, path));
106
+ const guide = createGuide({
107
+ title: "The welcome screen isn't in place",
108
+ docs: DOCS.create,
109
+ check: `run ${pm} run dev: the page shows a styled button.`,
110
+ });
111
+ const pageStep = () => guide.step(`Open ${shown} and replace what is in it with a first page of your own:`, FIRST_PAGE);
112
+
113
+ if (!entry) {
114
+ guide.because("the project's entry file wasn't found, so the scaffolder's demo page was kept");
115
+ pageStep();
116
+ return printGuide(guide);
117
+ }
118
+ const problem = tryWrite(path, source);
119
+ if (problem) {
120
+ guide.because(`${shown} couldn't be written: ${problem}`, { failed: true });
121
+ pageStep();
122
+ } else {
123
+ ok(`welcome screen written ${dim(`(${shown})`)}`);
124
+ }
125
+
126
+ // The template's demo CSS centres and re-colours everything, so it goes with its demo.
127
+ const cleanup = starterCleanup(framework, entry.path);
128
+ for (const file of cleanup.rewrite) {
129
+ const unwritten = existsSync(file.path) && tryWrite(file.path, file.source);
130
+ if (!unwritten) continue;
131
+ const css = posix(relative(cwd, file.path));
132
+ guide.because(`${css} couldn't be replaced, and its demo styles fight the page: ${unwritten}`);
133
+ guide.step(`Open ${css} and replace what is in it with:`, file.source);
134
+ }
135
+ for (const orphan of cleanup.remove) {
136
+ try {
137
+ rmSync(orphan, { force: true });
138
+ } catch {
139
+ // Nothing imports it any more, so a file that won't delete is only clutter.
140
+ }
141
+ }
142
+ printGuide(guide);
143
+ }
144
+
145
+ const FIRST_PAGE = `import { Button } from "astralis-ui";
146
+
147
+ export default function Home() {
148
+ return <Button colorScheme="brand">Hello</Button>;
149
+ }`;
150
+
99
151
  export async function run(argv) {
100
152
  const args = parseCommandArgs(commandNamed("create"), argv);
101
153
  if (!args) return;
@@ -103,7 +155,7 @@ export async function run(argv) {
103
155
  const [name] = args.positionals;
104
156
  const yes = isAssumeYes();
105
157
 
106
- if (!name) fail(`Name the project: ${cyan("astralis create <name>")}.`);
158
+ if (!name) fail(`Name the project: ${cyan("npx astralis-cli create <name>")}.`);
107
159
  printBanner(`Creating ${name}`);
108
160
  if (!/^[a-z0-9@][a-z0-9-_.]*$/i.test(name)) fail(`"${name}" isn't a safe project name.`);
109
161
  if (existsSync(join(process.cwd(), name))) fail(`./${name} already exists.`);
@@ -125,7 +177,7 @@ export async function run(argv) {
125
177
 
126
178
  if (forwarded.some((arg) => arg === "-i" || arg === "--immediate")) {
127
179
  warn("--immediate starts a dev server that doesn't exit, so Astralis can't be wired in afterwards.");
128
- console.log(dim(` Run ${cyan("astralis init")} inside ./${name} once you've stopped it.`));
180
+ console.log(dim(` Run ${cyan("npx astralis-cli init")} inside ./${name} once you've stopped it.`));
129
181
  }
130
182
  info(`${bold([bin, ...scaffoldArgs].join(" "))} ${dim("(the scaffolder's own prompts — answer them as usual)")}`);
131
183
 
@@ -138,9 +190,19 @@ export async function run(argv) {
138
190
  if (error instanceof UnsafeArgumentError) fail(`Couldn't forward that to the scaffolder: ${error.message}.`);
139
191
  throw error;
140
192
  }
141
- if (scaffold.status !== 0) fail("Scaffolding failed or was cancelled — nothing to wire up.");
193
+ const wireCommand = `npx astralis-cli init${values["no-devtools"] ? "" : " --devtools"}`;
194
+ if (scaffold.status !== 0) {
195
+ const guide = createGuide({ title: "Scaffolding failed or was cancelled, so there is nothing to wire up", docs: DOCS.create })
196
+ .because(`${[bin, ...scaffoldArgs].join(" ")}: ${commandProblem(scaffold)}`)
197
+ .step(`Delete ./${name} if it was half made, then run the scaffolder yourself:`, [bin, ...scaffoldArgs].join(" "))
198
+ .step("Wire Astralis in:", `cd ${name}\n${wireCommand}`);
199
+ fail(formatGuide(guide));
200
+ }
142
201
  if (!existsSync(join(process.cwd(), name, "package.json"))) {
143
- fail(`Expected ./${name}/package.json after scaffolding — did the scaffolder use a different directory?`);
202
+ const guide = createGuide({ title: "The project was scaffolded, but Astralis isn't wired in", docs: DOCS.create })
203
+ .because(`Expected ./${name}/package.json. The scaffolder may have used a different directory`)
204
+ .step("Go to the folder it made, the one that holds package.json, and wire Astralis in:", `cd path/to/that-folder\n${wireCommand}`);
205
+ fail(formatGuide(guide));
144
206
  }
145
207
 
146
208
  ok(`project created in ./${name}`);
@@ -156,22 +218,7 @@ export async function run(argv) {
156
218
  * nothing to lose, and it makes "did init work?" visible on first `dev`.
157
219
  */
158
220
  if (!values["no-starter"]) {
159
- const entry = findEntryFile(process.cwd(), framework);
160
- if (entry) {
161
- const { path, source } = starterFile(framework, entry.path);
162
- writeFileSync(path, source);
163
-
164
- // The template's demo CSS centres and re-colours everything, so it goes with its demo.
165
- const cleanup = starterCleanup(framework, entry.path);
166
- for (const file of cleanup.rewrite) {
167
- if (existsSync(file.path)) writeFileSync(file.path, file.source);
168
- }
169
- for (const orphan of cleanup.remove) {
170
- if (existsSync(orphan)) rmSync(orphan);
171
- }
172
-
173
- ok(`welcome screen written ${dim(`(${posix(relative(process.cwd(), path))})`)}`);
174
- }
221
+ writeStarter(process.cwd(), framework, pm);
175
222
  }
176
223
 
177
224
  console.log(`\n${bold("Next steps:")}\n ${cyan(`cd ${name}`)}\n ${cyan(`${pm} run dev`)}`);
@@ -1,4 +1,5 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
2
3
  import { readPackageJson, detectPackageManager, detectFramework, findEntryFile } from "../lib/detect.mjs";
3
4
  import { addImports, wrapJsx, addTagAttribute, insertAfterBodyTag, addStatementAfterImports, parses } from "../lib/edits.mjs";
4
5
  import { ok, warn, info, fail, bold, dim, cyan, printBanner } from "../lib/ui.mjs";
@@ -7,22 +8,71 @@ import { commandNamed } from "../lib/commands.mjs";
7
8
  import { runCommand } from "../lib/run.mjs";
8
9
  import { setUpCi } from "../lib/ci-setup.mjs";
9
10
  import { devtoolsLayoutEdits, setUpDevtools } from "../lib/devtools-setup.mjs";
11
+ import { DOCS, commandProblem, createGuide, formatGuide, printGuide, tryRead, tryWrite } from "../lib/manual.mjs";
12
+ import {
13
+ PROVIDER_CLOSE,
14
+ PROVIDER_IMPORT,
15
+ PROVIDER_OPEN,
16
+ STYLES_IMPORT,
17
+ THEME_INIT_CONST,
18
+ THEME_INIT_ELEMENT,
19
+ addWiringSteps,
20
+ likelyEntry,
21
+ } from "../lib/wiring.mjs";
10
22
 
11
- const PROVIDER_IMPORT = 'import { AstralisProvider } from "astralis-ui";';
12
- const STYLES_IMPORT = 'import "astralis-ui/styles.css";';
23
+ const CHECK_WIRING =
24
+ "start your dev server and put <Button>Hello</Button> from astralis-ui on a page. It shows as a styled button, in light and in dark mode.";
13
25
 
14
- // Applies `.astralis-dark` before first paint so a stored/system dark
15
- // preference never flashes light (same script the Astralis docs site uses).
16
- const THEME_INIT_CONST =
17
- 'const astralisThemeInit = `(function(){try{var t=localStorage.getItem("astralis-ui-theme");var d=t==="dark"||((!t||t==="system")&&window.matchMedia("(prefers-color-scheme: dark)").matches);if(d)document.documentElement.classList.add("astralis-dark");}catch(e){}})();`;';
18
- const THEME_INIT_SCRIPT = '\n <script dangerouslySetInnerHTML={{ __html: astralisThemeInit }} />';
26
+ /** package.json is missing or unreadable: nothing can be wired, so init has failed. */
27
+ function failWithoutPackage(cwd) {
28
+ const path = join(cwd, "package.json");
29
+ if (!existsSync(path)) {
30
+ const guide = createGuide({ title: "No package.json here", docs: DOCS.byHand })
31
+ .because("init has to run in your project's root, and this folder isn't one")
32
+ .step("Go to the folder that holds your project's package.json, then run init:", "cd path/to/your-project\nnpx astralis-cli init")
33
+ .step("Or start a new project:", "npx astralis-cli create my-app");
34
+ fail(formatGuide(guide));
35
+ }
36
+ const { problem } = tryRead(path);
37
+ const guide = createGuide({ title: "package.json couldn't be read", docs: DOCS.byHand, retry: "npx astralis-cli init" })
38
+ .because(`${problem ?? "it isn't valid JSON"}, so nothing was changed`)
39
+ .step(problem ? "Open package.json's properties and allow yourself to read it." : "Open package.json and fix the JSON. This prints where it breaks:", problem ? undefined : "npm pkg get name")
40
+ .step("Or wire Astralis in without the CLI: the guide below has every step.");
41
+ fail(formatGuide(guide));
42
+ }
43
+
44
+ /**
45
+ * Every edit the entry file needs, applied to its text. Each is
46
+ * { id, label, status, what?, note? }; a "declined" one left the text alone.
47
+ */
48
+ function editEntry(source, framework, devtools) {
49
+ const edits = [];
50
+ // The parts of one edit stand or fall together: an import whose element has no place is only a lint error.
51
+ const apply = (id, label, what, results) => {
52
+ const note = results.find((r) => r.note)?.note;
53
+ const changed = results.some((r) => r.changed);
54
+ if (!note) source = results.at(-1).source;
55
+ edits.push({ id, label, what, note, status: note ? "declined" : changed ? "done" : "present" });
56
+ };
19
57
 
20
- const MANUAL_SNIPPET = `
21
- ${bold("Manual setup:")}
22
- 1. ${PROVIDER_IMPORT}
23
- 2. ${STYLES_IMPORT} ${dim("(once, at your entry point)")}
24
- 3. Wrap your app: <AstralisProvider defaultTheme="system">…</AstralisProvider>
25
- Full guide: ${cyan("https://astralis-ui.com/docs/installation")}`;
58
+ apply("imports", "imports added", "the imports", [addImports(source, [PROVIDER_IMPORT, STYLES_IMPORT])]);
59
+
60
+ const child = framework === "next" ? "{children}" : "<App />";
61
+ if (source.includes("<AstralisProvider")) {
62
+ edits.push({ id: "provider", status: "wrapped" });
63
+ } else {
64
+ apply("provider", `provider wrapped around ${child}`, "the provider", [wrapJsx(source, child, PROVIDER_OPEN, PROVIDER_CLOSE)]);
65
+ }
66
+
67
+ if (framework === "next") {
68
+ const declared = addStatementAfterImports(source, THEME_INIT_CONST);
69
+ const placed = insertAfterBodyTag(declared.source, `\n ${THEME_INIT_ELEMENT}`);
70
+ apply("themeScript", "theme script injected after <body>", "the dark mode script", [declared, placed]);
71
+ apply("html", "suppressHydrationWarning on <html>", "suppressHydrationWarning", [addTagAttribute(source, "html", "suppressHydrationWarning")]);
72
+ if (devtools) apply("devtools", "<AstralisDevTools /> placed before </body>", "the DevTools", devtoolsLayoutEdits(source));
73
+ }
74
+ return { source, edits };
75
+ }
26
76
 
27
77
  /**
28
78
  * `nested` is set when `create` calls this as its wiring step. It suppresses
@@ -41,27 +91,14 @@ export async function run(argv, { nested = false, pm: givenPm } = {}) {
41
91
  if (!nested) printBanner(ci ? "Setting up validation in CI" : devtools ? "Adding the DevTools" : "Adding Astralis UI to this project");
42
92
 
43
93
  const pkg = readPackageJson(cwd);
44
- if (!pkg) fail("No package.json here — run `astralis init` from your project root.");
94
+ if (!pkg) failWithoutPackage(cwd);
45
95
 
46
96
  const framework = detectFramework(pkg);
47
- if (!framework) {
48
- // Be specific about which half is missing. A Vue + Vite app used to be
49
- // told "couldn't detect Vite", which is untrue and points at the wrong
50
- // problem — Vite is there, React is not.
51
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
52
- if (deps.vite) {
53
- warn("This is a Vite project, but not a React one.");
54
- console.log(
55
- dim(" Astralis is a React library — react and react-dom are its peer dependencies."),
56
- );
57
- } else {
58
- warn("Couldn't detect Next.js or a React + Vite project here.");
59
- }
60
- console.log(MANUAL_SNIPPET);
61
- return;
62
- }
63
97
  const pm = givenPm ?? detectPackageManager(cwd);
64
-
98
+ const command = ["npx astralis-cli init", devtools && "--devtools", ci && "--ci"].filter(Boolean).join(" ");
99
+ const hasDep = Boolean(pkg.dependencies?.["astralis-ui"] ?? pkg.devDependencies?.["astralis-ui"]);
100
+ const notes = [];
101
+ const guides = [];
65
102
  /*
66
103
  * Step output is buffered until we know whether anything actually changed.
67
104
  * Re-running init on an already-wired project used to print a checklist of
@@ -83,6 +120,40 @@ export async function run(argv, { nested = false, pm: givenPm } = {}) {
83
120
  };
84
121
  const out = { step, flush, changed: () => (changed = true), after: (fn) => afterwards.push(fn) };
85
122
 
123
+ const setUpExtras = (context) => {
124
+ for (const [wanted, setUp] of [[devtools, setUpDevtools], [ci, setUpCi]]) {
125
+ if (!wanted) continue;
126
+ const result = setUp({ cwd, pkg, pm, framework, dryRun, force: args.values.force, out, command, ...context });
127
+ notes.push(...result.notes);
128
+ guides.push(result.guide);
129
+ }
130
+ };
131
+ const report = () => {
132
+ flush();
133
+ for (const note of notes) warn(note);
134
+ for (const guide of guides) printGuide(guide);
135
+ for (const fn of afterwards) fn();
136
+ };
137
+
138
+ if (!framework) {
139
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
140
+ const guide = createGuide({ title: "Astralis couldn't be wired in", docs: DOCS.byHand, check: CHECK_WIRING });
141
+ guides.push(guide);
142
+ // Be specific about which half is missing: a Vue + Vite app does have Vite.
143
+ if (deps.react) {
144
+ guide.because("Couldn't detect Next.js or a React + Vite project here, so there is no entry file init knows how to edit");
145
+ } else {
146
+ const found = deps.vite ? "This is a Vite project, but not a React one" : "Couldn't detect Next.js or a React + Vite project here";
147
+ guide.because(`${found}. Astralis is a React library, and react is not in package.json`);
148
+ guide.step("Use a React 19 project, or add React to this one:", `${pm} add react react-dom`);
149
+ }
150
+ if (!hasDep) guide.step("Install Astralis from your project's root:", `${pm} add astralis-ui`);
151
+ addWiringSteps(guide, { file: "the file your app starts from (often src/main.tsx, src/index.tsx or src/root.tsx)", kind: "vite" });
152
+ setUpExtras({ entry: null, place: null, layoutProblem: null });
153
+ report();
154
+ return;
155
+ }
156
+
86
157
  step(() =>
87
158
  info(
88
159
  `${bold(framework === "next" ? "Next.js" : "Vite")} project, ${bold(pm)}${dryRun ? dim(" (dry run — nothing will be written)") : ""}`,
@@ -90,7 +161,10 @@ export async function run(argv, { nested = false, pm: givenPm } = {}) {
90
161
  );
91
162
 
92
163
  // 1. Dependency
93
- const hasDep = Boolean(pkg.dependencies?.["astralis-ui"] ?? pkg.devDependencies?.["astralis-ui"]);
164
+ const entry = findEntryFile(cwd, framework);
165
+ const place = entry ? { file: entry.relative, kind: framework } : likelyEntry(cwd, framework);
166
+ const wiring = createGuide({ title: "Astralis isn't fully wired in yet", docs: DOCS[place.kind], check: CHECK_WIRING, retry: command });
167
+ guides.push(wiring);
94
168
  if (hasDep) {
95
169
  step(() => ok("astralis-ui already in dependencies"));
96
170
  } else if (dryRun) {
@@ -101,84 +175,79 @@ export async function run(argv, { nested = false, pm: givenPm } = {}) {
101
175
  flush();
102
176
  info(`installing astralis-ui with ${pm}…`);
103
177
  const result = runCommand(pm, ["add", "astralis-ui"]);
104
- if (result.status !== 0) fail(`${pm} add astralis-ui failed — install it manually, then re-run init.`);
105
- ok("astralis-ui installed");
178
+ if (result.status === 0) {
179
+ ok("astralis-ui installed");
180
+ } else {
181
+ warn(`${pm} add astralis-ui failed; carrying on with the rest`);
182
+ wiring.because(`astralis-ui wasn't installed: ${commandProblem(result)}`, { failed: true });
183
+ wiring.step("Install it from your project's root:", `${pm} add astralis-ui`);
184
+ }
106
185
  }
107
186
 
108
187
  // 2. Entry file
109
- const entry = findEntryFile(cwd, framework);
110
- if (!entry) {
111
- flush();
112
- warn(`Couldn't find your ${framework === "next" ? "root layout" : "src/main.tsx"} — wire the provider manually:`);
113
- console.log(MANUAL_SNIPPET);
114
- const extra = [
115
- ...(devtools ? setUpDevtools({ cwd, pkg, pm, framework, entry: null, dryRun, out }) : []),
116
- ...(ci ? setUpCi({ cwd, pkg, pm, dryRun, force: args.values.force, out }) : []),
117
- ];
118
- for (const note of extra) warn(note);
119
- for (const fn of afterwards) fn();
120
- return;
121
- }
122
-
123
- let source = readFileSync(entry.path, "utf8");
124
- const original = source;
125
- const notes = [];
126
- const apply = (result, label) => {
127
- source = result.source;
128
- if (result.changed) {
129
- changed = true;
130
- step(() => ok(`${label} ${dim(`(${entry.relative})`)}`));
131
- } else if (result.note) notes.push(`${label}: ${result.note}`);
132
- else step(() => ok(`${label} — already present`));
133
- };
188
+ // Why the layout has no <AstralisDevTools /> when it should; setUpDevtools gives the step.
189
+ let layoutProblem = null;
134
190
 
135
- apply(addImports(source, [PROVIDER_IMPORT, STYLES_IMPORT]), "imports added");
136
-
137
- if (source.includes("<AstralisProvider")) {
138
- step(() => ok("AstralisProvider already wraps this file"));
139
- } else if (framework === "next") {
140
- apply(
141
- wrapJsx(source, "{children}", '<AstralisProvider defaultTheme="system">', "</AstralisProvider>"),
142
- "provider wrapped around {children}",
191
+ const { text: original, problem: readProblem } = entry ? tryRead(entry.path) : {};
192
+ if (!entry) {
193
+ wiring.because(
194
+ place.kind === "nextPages"
195
+ ? `Couldn't find your root layout: this project uses the Pages Router (${place.file}), which init doesn't edit`
196
+ : `Couldn't find your ${framework === "next" ? "root layout (looked for app/layout and src/app/layout)" : "entry file (looked for src/main.tsx and src/main.jsx)"}`,
143
197
  );
198
+ addWiringSteps(wiring, place);
199
+ layoutProblem = "no root layout was found to put <AstralisDevTools /> in";
200
+ } else if (readProblem || !parses(original)) {
201
+ const why = readProblem ? `${entry.relative} couldn't be read: ${readProblem}` : `${entry.relative} doesn't parse, so it was left alone`;
202
+ wiring.because(why, { failed: Boolean(readProblem) });
203
+ addWiringSteps(wiring, place);
204
+ layoutProblem = why;
144
205
  } else {
145
- apply(
146
- wrapJsx(source, "<App />", '<AstralisProvider defaultTheme="system">', "</AstralisProvider>"),
147
- "provider wrapped around <App />",
148
- );
149
- }
206
+ const { source, edits } = editEntry(original, framework, devtools);
207
+ const unparseable = source !== original && !parses(source);
208
+ const writeProblem = source === original || unparseable ? null : tryWrite(entry.path, source, { dryRun });
150
209
 
151
- if (framework === "next") {
152
- apply(addStatementAfterImports(source, THEME_INIT_CONST), "anti-flash theme script const");
153
- apply(insertAfterBodyTag(source, THEME_INIT_SCRIPT), "theme script injected after <body>");
154
- apply(addTagAttribute(source, "html", "suppressHydrationWarning"), "suppressHydrationWarning on <html>");
155
- if (devtools) {
156
- const [imported, placed] = devtoolsLayoutEdits(source);
157
- apply(imported, "DevTools import added");
158
- apply(placed, "<AstralisDevTools /> placed before </body>");
210
+ if (unparseable || writeProblem) {
211
+ const why = unparseable
212
+ ? `${entry.relative}: the edits would leave it unparseable, so nothing was written`
213
+ : `${entry.relative} couldn't be written: ${writeProblem}`;
214
+ const needed = edits.filter((edit) => edit.status === "done" || edit.status === "declined").map((edit) => edit.id);
215
+ const own = needed.filter((id) => id !== "devtools");
216
+ if (own.length > 0) {
217
+ wiring.because(why, { failed: Boolean(writeProblem) });
218
+ addWiringSteps(wiring, place, own);
219
+ }
220
+ if (needed.includes("devtools")) layoutProblem = why;
221
+ if (writeProblem) process.exitCode = 1;
222
+ } else {
223
+ for (const edit of edits) {
224
+ if (edit.status === "done") {
225
+ changed = true;
226
+ step(() => ok(`${edit.label} ${dim(`(${entry.relative})`)}`));
227
+ } else if (edit.status === "present") {
228
+ step(() => ok(`${edit.label} — already present`));
229
+ } else if (edit.status === "wrapped") {
230
+ step(() => ok("AstralisProvider already wraps this file"));
231
+ } else if (edit.id === "devtools") {
232
+ layoutProblem = `${entry.relative}: ${edit.note}`;
233
+ } else {
234
+ wiring.because(`${edit.what}, in ${entry.relative}: ${edit.note}`);
235
+ addWiringSteps(wiring, place, [edit.id]);
236
+ }
237
+ }
238
+ if (dryRun && source !== original) step(() => info(`would update ${entry.relative}`));
159
239
  }
160
240
  }
161
241
 
162
- // 3. Write — never a file that no longer parses; hand over to the manual steps instead.
163
- if (source !== original && !parses(source)) {
164
- source = original;
165
- notes.push(`${entry.relative}: the edits would leave it unparseable, so nothing was written`);
166
- }
167
- if (source !== original) {
168
- if (dryRun) step(() => info(`would update ${entry.relative}`));
169
- else writeFileSync(entry.path, source);
170
- }
171
-
172
- // 4. DevTools and CI
173
- const wiringNotes = notes.length;
174
- if (devtools) notes.push(...setUpDevtools({ cwd, pkg, pm, framework, entry, dryRun, out }));
175
- if (ci) notes.push(...setUpCi({ cwd, pkg, pm, dryRun, force: args.values.force, out }));
242
+ // 3. DevTools and CI
243
+ setUpExtras({ entry, place, layoutProblem });
244
+ const needsHand = guides.some((guide) => guide.needed);
176
245
 
177
246
  /*
178
247
  * Nothing to do, and nothing that needed the reader's attention: say so in
179
248
  * one line instead of listing the steps that were already satisfied.
180
249
  */
181
- if (!changed && notes.length === 0) {
250
+ if (!changed && notes.length === 0 && !needsHand) {
182
251
  const extras = [devtools && "the DevTools", ci && "its CI check"].filter(Boolean);
183
252
  ok(
184
253
  extras.length
@@ -190,17 +259,14 @@ export async function run(argv, { nested = false, pm: givenPm } = {}) {
190
259
  return;
191
260
  }
192
261
 
193
- flush();
194
-
195
- for (const note of notes) warn(note);
196
- if (wiringNotes > 0) console.log(MANUAL_SNIPPET);
197
- for (const fn of afterwards) fn();
262
+ report();
198
263
 
199
264
  if (nested || !changed) return;
200
265
 
201
266
  if (dryRun) {
202
- console.log(`\n${bold("Dry run:")} nothing was written. Run ${cyan(["astralis init", devtools && "--devtools", ci && "--ci"].filter(Boolean).join(" "))} to apply it.`);
267
+ console.log(`\n${bold("Dry run:")} nothing was written. Run ${cyan(command)} to apply it.`);
203
268
  return;
204
269
  }
270
+ if (needsHand) return;
205
271
  console.log(`\n${bold("Done.")} Try it:\n ${cyan('import { Button } from "astralis-ui";')}\n ${cyan('<Button colorScheme="teal">Hello</Button>')}\nDocs: ${cyan("https://astralis-ui.com/docs")}`);
206
272
  }