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.
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { dirname, join, relative, resolve } from "node:path";
3
3
  import { ok, warn, fail, cyan, dim, posix } 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 { readPackageJson, detectFramework, findEntryFile } from "../lib/detect.mjs";
7
7
  import { addImports, parses } from "../lib/edits.mjs";
8
8
  import { loadThemeLibrary } from "../lib/library.mjs";
9
+ import { DOCS, createGuide, formatGuide, printGuide, tryRead, tryWrite } from "../lib/manual.mjs";
10
+ import { likelyEntry } from "../lib/wiring.mjs";
9
11
 
10
12
  /**
11
13
  * Renders a theme seed as a stylesheet: the static equivalent of
@@ -65,6 +67,31 @@ function checkContrast(library, seed) {
65
67
  }
66
68
  }
67
69
 
70
+ /**
71
+ * The import line for the theme and the entry file it goes in. Without one the
72
+ * CLI knows how to edit, `place` is the likeliest file and has no `path`.
73
+ */
74
+ function themeImport(cwd, outPath) {
75
+ const pkg = readPackageJson(cwd);
76
+ const framework = pkg ? detectFramework(pkg) : null;
77
+ const entry = findEntryFile(cwd, framework);
78
+ const file = entry?.relative ?? (framework ? likelyEntry(cwd, framework).file : null);
79
+ // With no framework the entry is unknown, and src/ is where most keep it.
80
+ const dir = file ? dirname(join(cwd, file)) : existsSync(join(cwd, "src")) ? join(cwd, "src") : cwd;
81
+ const specifier = posix(relative(dir, outPath));
82
+ return {
83
+ line: `import "${specifier.startsWith(".") ? specifier : `./${specifier}`}";`,
84
+ place: { path: entry?.path, file: file ?? "the file your app starts from (often src/main.tsx or app/layout.tsx)" },
85
+ };
86
+ }
87
+
88
+ /* Added with the theme when the entry lacks it (theme run before init): the
89
+ theme only wins when it comes second, and init appends what is missing. */
90
+ const LIBRARY_IMPORT = 'import "astralis-ui/styles.css";';
91
+
92
+ /** This run's own command line, to print for running again. */
93
+ const rerun = (argv) => `npx astralis-cli theme ${argv.map((arg) => (/^[\w./=-]+$/.test(arg) ? arg : `"${arg}"`)).join(" ")}`;
94
+
68
95
  export async function run(argv) {
69
96
  const args = parseCommandArgs(commandNamed("theme"), argv);
70
97
  if (!args) return;
@@ -73,9 +100,10 @@ export async function run(argv) {
73
100
  const seed = seedFrom(values, positionals);
74
101
  const cwd = process.cwd();
75
102
  const library = await loadThemeLibrary(cwd);
103
+ if (library.broken) warn(`Your project's astralis-ui couldn't be loaded (${library.broken}); using the CLI's own copy.`);
76
104
  const { themeCss, validateSeed, isEmptySeed } = library.serialize;
77
105
 
78
- if (isEmptySeed(seed)) fail(`Nothing to generate: no theme options given. Run ${cyan("astralis theme --help")}.`);
106
+ if (isEmptySeed(seed)) fail(`Nothing to generate: no theme options given. Run ${cyan("npx astralis-cli theme --help")}.`);
79
107
  const issues = validateSeed(seed);
80
108
  if (issues.length) {
81
109
  fail(`Invalid theme options:\n${issues.map((i) => ` ${i.field}: ${i.message}`).join("\n")}`);
@@ -108,37 +136,49 @@ export async function run(argv) {
108
136
  }
109
137
  }
110
138
 
111
- writeFileSync(outPath, themeCss(seed));
139
+ const shown = posix(out);
140
+ const { line, place } = themeImport(cwd, outPath);
141
+ const guide = createGuide({
142
+ title: "The theme isn't applied yet",
143
+ docs: DOCS.theme,
144
+ check: seed.brandColor
145
+ ? `start your dev server, open the page in the browser's inspector and select <html>: --astralis-color-brand-500 is ${seed.brandColor}.`
146
+ : "start your dev server, open the page in the browser's inspector and select <html>: the values come from your theme file.",
147
+ });
148
+ const importLines = `import "astralis-ui/styles.css";\n${line}`;
149
+
150
+ const writeProblem = tryWrite(outPath, themeCss(seed));
151
+ if (writeProblem) {
152
+ guide.because(`${shown} couldn't be written: ${writeProblem}`);
153
+ guide.step("Make that file and its folder writable, then run this again. To write somewhere else, change --out:", rerun(values.out ? argv : [...argv, "--out", shown]));
154
+ if (!values["no-import"]) guide.step(`If it then says the import is missing, open ${place.file} and add it after the library's stylesheet:`, importLines);
155
+ fail(formatGuide(guide));
156
+ }
112
157
  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)`)}`);
158
+ ok(`wrote ${cyan(shown)} ${dim(`(astralis-ui ${library.version}, ${from} copy)`)}`);
114
159
  if (library.outdated) {
115
160
  warn(`Your astralis-ui ${library.outdated} predates static themes; upgrade it so the file matches the library you ship.`);
116
161
  }
117
162
 
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.
120
- const pkg = readPackageJson(cwd);
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;
124
-
125
- if (!values["no-import"] && entry) {
126
- const result = addImports(readFileSync(entry.path, "utf8"), [line]);
127
- if (result.changed && parses(result.source)) {
128
- writeFileSync(entry.path, result.source);
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)}`);
163
+ // A generated stylesheet nobody imports changes nothing, silently.
164
+ if (!values["no-import"]) {
165
+ const { text, problem: readProblem } = place.path ? tryRead(place.path) : {};
166
+ const result = text === undefined ? null : addImports(text, [LIBRARY_IMPORT, line]);
167
+ if (!place.path) {
168
+ guide.because("No Next.js or Vite entry point was found to import it in");
169
+ } else if (readProblem) {
170
+ guide.because(`${place.file} couldn't be read: ${readProblem}`);
171
+ } else if (result.note || (result.changed && !parses(result.source))) {
172
+ guide.because(`${place.file}: ${result.note ?? "it couldn't be edited safely, so it was left alone"}`);
173
+ } else if (!result.changed) {
174
+ ok(`already imported in ${cyan(place.file)}`);
133
175
  } else {
134
- ok(`already imported in ${cyan(entry.relative)}`);
176
+ const problem = tryWrite(place.path, result.source);
177
+ if (problem) guide.because(`${place.file} couldn't be written: ${problem}`);
178
+ else ok(`imported in ${cyan(place.file)} ${dim("(after the library stylesheet)")}`);
135
179
  }
136
- } else if (!values["no-import"]) {
137
- warn("No Next.js or Vite entry point found — import it yourself:");
138
- console.log(
139
- ` ${cyan('import "astralis-ui/styles.css";')}\n` +
140
- ` ${cyan(`import "./${posix(out)}";`)} ${dim("← must come second")}`,
141
- );
180
+ if (guide.needed) guide.step(`Open ${place.file} and add your theme after the library's stylesheet. It must come second:`, importLines);
181
+ printGuide(guide);
142
182
  }
143
183
 
144
184
  if (seed.fontHeading || seed.fontBody || seed.fontMono) {
package/src/index.mjs CHANGED
@@ -11,7 +11,6 @@ const MODULES = {
11
11
  add: () => import("./commands/add.mjs"),
12
12
  theme: () => import("./commands/theme.mjs"),
13
13
  validate: () => import("./commands/validate.mjs"),
14
- report: () => import("./commands/report.mjs"),
15
14
  "connect-mcp": () => import("./commands/connect-mcp.mjs"),
16
15
  };
17
16
 
@@ -28,7 +27,7 @@ try {
28
27
  await run(rest);
29
28
  } else {
30
29
  const near = suggest(name, Object.keys(MODULES));
31
- fail(`Unknown command "${name}".${near ? ` Did you mean "${near}"?` : ""} Run ${cyan("astralis --help")} for the list.`);
30
+ fail(`Unknown command "${name}".${near ? ` Did you mean "${near}"?` : ""} Run ${cyan("npx astralis-cli --help")} for the list.`);
32
31
  }
33
32
  } catch (error) {
34
33
  if (!(error instanceof CliExit)) {
package/src/lib/args.mjs CHANGED
@@ -18,7 +18,7 @@ export function parseCommandArgs(command, argv) {
18
18
  const values = Object.fromEntries(options.filter((o) => o.type === "boolean").map((o) => [o.name, false]));
19
19
  const positionals = [];
20
20
  const forwarded = [];
21
- const usageHint = `Run ${cyan(`astralis ${command.name} --help`)} for its options.`;
21
+ const usageHint = `Run ${cyan(`npx astralis-cli ${command.name} --help`)} for its options.`;
22
22
 
23
23
  for (let i = 0; i < argv.length; i++) {
24
24
  const arg = argv[i];
@@ -128,7 +128,7 @@ export function mainHelp(commands) {
128
128
  ` ${bold("Global options")}`,
129
129
  ...optionLines([...GLOBAL_OPTIONS, versionFlag]),
130
130
  "",
131
- ` Run ${cyan("astralis <command> --help")} for a command's options.`,
131
+ ` Run ${cyan("npx astralis-cli <command> --help")} for a command's options.`,
132
132
  ` ${dim("Docs")} ${cyan(DOCS_URL)}`,
133
133
  "",
134
134
  ].join("\n");
@@ -1,8 +1,9 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { ok, info, fail, bold, dim, cyan, posix } from "./ui.mjs";
3
+ import { ok, warn, info, bold, dim, cyan, posix } from "./ui.mjs";
4
4
  import { runCommand } from "./run.mjs";
5
- import { CHECK_NAME, WORKFLOW_FILE, inspectProject, readText, validateScript, withScript, workflowYaml } from "./ci.mjs";
5
+ import { DOCS, commandProblem, createGuide, tryRead, tryWrite } from "./manual.mjs";
6
+ import { CHECK_NAME, WORKFLOW_FILE, inspectProject, validateScript, withScript, workflowYaml } from "./ci.mjs";
6
7
 
7
8
  const VALIDATE_COMMAND = "astralis validate";
8
9
 
@@ -10,10 +11,19 @@ const VALIDATE_COMMAND = "astralis validate";
10
11
  * The --ci half of `astralis init`: astralis-cli pinned as a devDependency, a
11
12
  * package.json script that runs the validator, and a GitHub Actions workflow
12
13
  * 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
+ * changes nothing stays one line. Returns { notes, guide }: notes to read, and
15
+ * what is left to do by hand.
14
16
  */
15
- export function setUpCi({ cwd, pkg, pm, dryRun, force, out }) {
17
+ export function setUpCi({ cwd, pkg, pm, dryRun, force, out, command }) {
16
18
  const notes = [];
19
+ const check = (script) => `run \`${pm} run ${script}\`, then open a pull request: "${CHECK_NAME}" runs on it.`;
20
+ const guide = createGuide({
21
+ title: "The CI check isn't fully set up yet",
22
+ docs: DOCS.ci,
23
+ check: check("validate"),
24
+ retry: command,
25
+ });
26
+ const result = { notes, guide };
17
27
  const had = (name) => Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
18
28
 
19
29
  if (had("astralis-cli")) {
@@ -25,25 +35,47 @@ export function setUpCi({ cwd, pkg, pm, dryRun, force, out }) {
25
35
  out.changed();
26
36
  out.flush();
27
37
  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");
38
+ const installed = runCommand(pm, ["add", "-D", "astralis-cli"], { cwd });
39
+ if (installed.status === 0) {
40
+ ok("astralis-cli installed as a devDependency");
41
+ } else {
42
+ warn(`${pm} add -D astralis-cli failed; carrying on with the rest`);
43
+ guide.because(`astralis-cli wasn't installed: ${commandProblem(installed)}`, { failed: true });
44
+ guide.step("Install it from your project's root, and commit the lockfile:", `${pm} add -D astralis-cli`);
45
+ }
31
46
  }
32
47
 
33
48
  // The install above rewrites package.json, so read it again before adding to it.
34
49
  const packagePath = join(cwd, "package.json");
35
- const packageText = readFileSync(packagePath, "utf8");
36
- const script = validateScript(JSON.parse(packageText).scripts);
50
+ const { text: packageText, problem: packageProblem } = tryRead(packagePath);
51
+ let scripts;
52
+ try {
53
+ scripts = JSON.parse(packageText).scripts;
54
+ } catch {
55
+ guide.because(`package.json couldn't be read: ${packageProblem ?? "it isn't valid JSON"}`, { failed: true });
56
+ guide.step("Open package.json, make it readable and valid, and add this to its scripts:", `"validate": "${VALIDATE_COMMAND}"`);
57
+ guide.step("Then have init write the workflow:", command);
58
+ return result;
59
+ }
60
+ const script = validateScript(scripts);
37
61
  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;
62
+ guide.because('package.json\'s "validate" and "astralis:validate" scripts both do something else, so there was no name left to use');
63
+ guide.step("Open package.json and have your validate script run the validator too:", `"validate": ${JSON.stringify(`${scripts.validate} && ${VALIDATE_COMMAND}`)}`);
64
+ guide.step("Then have init write the workflow:", command);
65
+ return result;
40
66
  }
67
+ guide.check = check(script.name);
41
68
  if (!script.isNew) {
42
69
  out.step(() => ok(`"${script.name}" script already runs the validator`));
43
70
  } 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));
71
+ const problem = tryWrite(packagePath, withScript(packageText, script.name, VALIDATE_COMMAND), { dryRun });
72
+ if (problem) {
73
+ guide.because(`package.json couldn't be written: ${problem}`, { failed: true });
74
+ guide.step("Open package.json and add this to its scripts:", `"${script.name}": "${VALIDATE_COMMAND}"`);
75
+ } else {
76
+ out.changed();
77
+ out.step(() => ok(`${dryRun ? "would add" : "added"} "${script.name}": "${VALIDATE_COMMAND}" ${dim("(package.json)")}`));
78
+ }
47
79
  }
48
80
 
49
81
  const project = inspectProject(cwd, pkg, pm);
@@ -51,28 +83,38 @@ export function setUpCi({ cwd, pkg, pm, dryRun, force, out }) {
51
83
  const shown = posix(join(".github", "workflows", WORKFLOW_FILE));
52
84
  const path = join(root, shown);
53
85
  const yaml = workflowYaml(project, script.name);
54
- const existing = readText(path);
86
+ const read = existsSync(path) ? tryRead(path) : { text: null };
87
+ const existing = read.text ?? null;
55
88
 
56
- if (existing === yaml) {
89
+ const problem =
90
+ read.problem ?? (existing === yaml || (existing !== null && !force) ? null : tryWrite(path, yaml, { dryRun }));
91
+ if (problem) {
92
+ guide.because(`${shown} couldn't be ${read.problem ? "read" : "written"}: ${problem}`, { failed: true });
93
+ guide.step(`Create ${posix(path)} with:`, yaml);
94
+ } else if (existing === yaml) {
57
95
  out.step(() => ok(`${shown} already present`));
58
96
  } else if (existing !== null && !force) {
59
97
  notes.push(`${shown} already exists and differs from what init would write; it was left alone (--force replaces it)`);
60
98
  } else {
61
99
  out.changed();
62
100
  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
101
  out.after(() => {
68
102
  console.log(`\n${bold("CI:")} push, then make ${cyan(`"${CHECK_NAME}"`)} a required status check so a failing run blocks the merge:`);
69
103
  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
104
  });
72
105
  }
73
106
 
107
+ if (!project.gitRoot) {
108
+ guide.because("This folder isn't in a git repository, so GitHub has nothing to run the check on yet");
109
+ guide.step("Make it one, from this folder:", 'git init -b main\ngit add -A\ngit commit -m "First commit"');
110
+ guide.step(
111
+ "Create an empty repository on GitHub and push to it (use its own address):",
112
+ "git remote add origin https://github.com/YOUR-NAME/YOUR-REPO.git\ngit push -u origin main",
113
+ );
114
+ }
115
+
74
116
  if (!project.lockfile) {
75
117
  notes.push(`no ${pm} lockfile found — commit one so CI installs the same versions you tested`);
76
118
  }
77
- return notes;
119
+ return result;
78
120
  }
package/src/lib/ci.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
2
  import { dirname, join, relative } from "node:path";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { posix } from "./ui.mjs";
@@ -151,5 +151,3 @@ export function withScript(packageJsonText, name, command) {
151
151
  const text = JSON.stringify(pkg, null, indent).replaceAll("\n", eol);
152
152
  return /\r?\n$/.test(packageJsonText) ? text + eol : text;
153
153
  }
154
-
155
- export const readText = (path) => (existsSync(path) ? readFileSync(path, "utf8") : null);
@@ -158,42 +158,6 @@ export const COMMANDS = [
158
158
  ],
159
159
  examples: ["astralis validate", "astralis validate src/components --json", "astralis validate --strict-tokens"],
160
160
  },
161
- {
162
- name: "report",
163
- args: "<files...>",
164
- maxPositionals: Infinity,
165
- summary: "Report a problem to the Astralis maintainers, with a snapshot built from your source files",
166
- options: [
167
- { name: "title", type: "string", arg: "text", description: "The report's title. Asked for when omitted; required with --yes." },
168
- { name: "happened", type: "string", arg: "text", description: "What happened." },
169
- { name: "expected", type: "string", arg: "text", description: "What you expected instead." },
170
- { name: "include-text", type: "boolean", description: "Keep the text in your JSX; by default it is replaced by placeholders." },
171
- { name: "no-findings", type: "boolean", description: "Leave out the validator's findings for these files." },
172
- { name: "out", type: "string", arg: "file", description: "Write the snapshot to a file instead of sending it." },
173
- { name: "dry-run", type: "boolean", description: "Print the snapshot and send nothing." },
174
- { name: "add-to", type: "string", arg: "issue", description: "Add the report to this existing issue instead of opening a new one." },
175
- { name: "new", type: "boolean", description: "Open a new issue without checking for an existing one." },
176
- { name: "link", type: "boolean", description: "Print a link to GitHub's own new-issue form, filled in, instead of signing in; you submit it there." },
177
- { name: "sign-out", type: "boolean", description: "Forget the saved GitHub sign-in, and do nothing else." },
178
- {
179
- name: "spec",
180
- type: "string",
181
- arg: "path",
182
- description: "Build against this system-spec.json.",
183
- default: "the installed astralis-ui's",
184
- },
185
- ],
186
- notes: [
187
- "It prints the exact JSON first and sends nothing until you confirm; --yes confirms without asking.",
188
- "It opens a GitHub issue from your own account. The first time, you sign in with a code on github.com.",
189
- "Before opening one it looks for an issue that already reports the same problem, and offers to add your report to it.",
190
- "Only literal props are recorded, and only those the spec describes; links, sources and handlers never are.",
191
- ],
192
- examples: [
193
- "astralis report app/page.tsx",
194
- 'astralis report src/App.tsx --title "Card loses its border" --out snapshot.json',
195
- ],
196
- },
197
161
  {
198
162
  name: "connect-mcp",
199
163
  args: "",
@@ -29,7 +29,7 @@ export function detectFramework(pkg) {
29
29
  }
30
30
 
31
31
  const ENTRY_CANDIDATES = {
32
- next: ["app/layout.tsx", "app/layout.jsx", "src/app/layout.tsx", "src/app/layout.jsx"],
32
+ next: ["app", "src/app"].flatMap((dir) => ["tsx", "jsx", "js"].map((ext) => `${dir}/layout.${ext}`)),
33
33
  vite: ["src/main.tsx", "src/main.jsx"],
34
34
  };
35
35
 
@@ -1,8 +1,9 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { addArrayElement, addImports, insertBeforeBodyClose, parses } from "./edits.mjs";
4
- import { ok, info, fail, bold, cyan, dim, posix } from "./ui.mjs";
4
+ import { ok, warn, info, bold, cyan, dim, posix } from "./ui.mjs";
5
5
  import { runCommand } from "./run.mjs";
6
+ import { DOCS, commandProblem, createGuide, tryRead, tryWrite } from "./manual.mjs";
6
7
 
7
8
  /* The --devtools half of `astralis init`: astralis-devtools as a
8
9
  devDependency, and the wiring its framework needs. Next.js gets the overlay
@@ -49,7 +50,7 @@ export function devtoolsViteEdits(source) {
49
50
  return [imported, added];
50
51
  }
51
52
 
52
- function install({ cwd, pkg, pm, dryRun, out }) {
53
+ function install({ cwd, pkg, pm, dryRun, out }, guide) {
53
54
  const had = Boolean(pkg.dependencies?.[PACKAGE] ?? pkg.devDependencies?.[PACKAGE]);
54
55
  if (had) {
55
56
  out.step(() => ok(`${PACKAGE} already in dependencies`));
@@ -61,82 +62,149 @@ function install({ cwd, pkg, pm, dryRun, out }) {
61
62
  out.flush();
62
63
  info(`installing ${PACKAGE} with ${pm}…`);
63
64
  const result = runCommand(pm, ["add", "-D", PACKAGE], { cwd });
64
- if (result.status !== 0) fail(`${pm} add -D ${PACKAGE} failed — install it manually, then re-run init --devtools.`);
65
- ok(`${PACKAGE} installed as a devDependency`);
65
+ if (result.status === 0) {
66
+ ok(`${PACKAGE} installed as a devDependency`);
67
+ } else {
68
+ warn(`${pm} add -D ${PACKAGE} failed; carrying on with the rest`);
69
+ guide.because(`${PACKAGE} wasn't installed: ${commandProblem(result)}`, { failed: true });
70
+ guide.step("Install it from your project's root:", `${pm} add -D ${PACKAGE}`);
71
+ }
66
72
  }
67
73
  }
68
74
 
69
75
  function sayHowToOpen(out) {
70
76
  out.after(() => {
71
- console.log(`\n${bold("DevTools:")} start the dev server and click the ${cyan("✦")} button in the corner of the page.`);
77
+ console.log(`\n${bold("DevTools:")} start the dev server and click the Astralis button at the bottom of the page, or press ${cyan("Shift+Alt+A")}.`);
72
78
  console.log(dim(" Development only: production builds contain none of it."));
73
79
  });
74
80
  }
75
81
 
76
- /**
77
- * Install the package and write the files outside the entry file (the Next.js
78
- * route; the Vite config). The Next.js layout edits go through init's own
79
- * pipeline via devtoolsLayoutEdits. Returns notes that need attention.
80
- */
81
- export function setUpDevtools({ cwd, pkg, pm, framework, entry, dryRun, out }) {
82
- const notes = [];
83
- install({ cwd, pkg, pm, dryRun, out });
82
+ const CHECK_OPEN = "start the dev server and open the app: the Astralis button is at the bottom of the page.";
84
83
 
85
- if (framework === "next") {
86
- if (!entry) {
87
- notes.push(`add ${NEXT_ELEMENT} to your root layout and the route ${cyan(ROUTE_SOURCE.trim())} yourself`);
88
- return notes;
89
- }
90
- const shown = routeFilePath(entry.relative);
91
- const path = join(cwd, shown);
92
- const existing = existsSync(path) ? readFileSync(path, "utf8") : null;
93
- if (existing !== null && existing.trim() === GET_ONLY_ROUTE_SOURCE.trim()) {
94
- // Written by an earlier init, before the bridge took reports: add POST.
95
- out.changed();
96
- out.step(() => ok(`${dryRun ? "would update" : "updated"} the DevTools route to take reports ${dim(`(${shown})`)}`));
97
- if (!dryRun) writeFileSync(path, ROUTE_SOURCE);
98
- } else if (existing !== null && existing.includes("astralis-devtools/next/route")) {
99
- out.step(() => ok(`DevTools route already present ${dim(`(${shown})`)}`));
100
- if (!/\bPOST\b/.test(existing)) notes.push(`${shown} does not export POST, so the DevTools cannot send reports; export POST from "astralis-devtools/next/route" too`);
101
- } else if (existing !== null) {
102
- notes.push(`${shown} already exists and does something else; add \`${ROUTE_SOURCE.trim()}\` to it yourself`);
84
+ const layoutStep = (guide, { file, kind }) =>
85
+ guide.step(
86
+ `Open ${file}${kind === "next" ? " (or the file that holds your <body>)" : ""}, import the DevTools and put them ${kind === "nextPages" ? "after <Component />, inside the provider" : "last inside <body>"}:`,
87
+ `${NEXT_IMPORT}\n\n${NEXT_ELEMENT}`,
88
+ );
89
+
90
+ const pluginStep = (guide, file) =>
91
+ guide.step(`Open ${file}, import the plugin and add it to plugins, keeping the ones already there:`, `${VITE_IMPORT}\n\nplugins: [react(), ${VITE_PLUGIN}],`);
92
+
93
+ const viteConfigSource = `import { defineConfig } from "vite";
94
+ import react from "@vitejs/plugin-react";
95
+ ${VITE_IMPORT}
96
+
97
+ export default defineConfig({
98
+ plugins: [react(), ${VITE_PLUGIN}],
99
+ });`;
100
+
101
+ /** The bridge's route handler: written, brought up to date, or left to the guide. */
102
+ function setUpRoute({ cwd, shown, dryRun, out, guide }) {
103
+ const path = join(cwd, shown);
104
+ const read = existsSync(path) ? tryRead(path) : { text: null };
105
+ const existing = read.text ?? null;
106
+ const byHand = (why, failed) => {
107
+ guide.because(`${shown} ${why}`, { failed });
108
+ guide.step(`Create ${shown} with:`, ROUTE_SOURCE);
109
+ };
110
+ if (read.problem) return byHand(`couldn't be read: ${read.problem}`, true);
111
+
112
+ const isOurs = existing !== null && existing.trim() === GET_ONLY_ROUTE_SOURCE.trim();
113
+ if (existing !== null && !isOurs) {
114
+ if (!existing.includes("astralis-devtools/next/route")) {
115
+ guide.because(`${shown} already exists and does something else, so it was left alone`);
116
+ guide.step(`Open ${shown}, move what it does to another route, and have it hold only:`, ROUTE_SOURCE);
103
117
  } else {
104
- out.changed();
105
- out.step(() => ok(`${dryRun ? "would write" : "wrote"} the DevTools route ${dim(`(${shown})`)}`));
106
- if (!dryRun) {
107
- mkdirSync(dirname(path), { recursive: true });
108
- writeFileSync(path, ROUTE_SOURCE);
118
+ out.step(() => ok(`DevTools route already present ${dim(`(${shown})`)}`));
119
+ if (!/\bPOST\b/.test(existing)) {
120
+ guide.because(`${shown} does not export POST, so the DevTools cannot send reports`);
121
+ guide.step(`Open ${shown} and export POST too:`, 'export { POST } from "astralis-devtools/next/route";');
109
122
  }
110
123
  }
111
- sayHowToOpen(out);
112
- return notes;
124
+ return;
113
125
  }
114
126
 
127
+ const problem = tryWrite(path, ROUTE_SOURCE, { dryRun });
128
+ if (problem) return byHand(`couldn't be written: ${problem}`, true);
129
+ out.changed();
130
+ out.step(() =>
131
+ ok(
132
+ isOurs
133
+ ? `${dryRun ? "would update" : "updated"} the DevTools route to take reports ${dim(`(${shown})`)}`
134
+ : `${dryRun ? "would write" : "wrote"} the DevTools route ${dim(`(${shown})`)}`,
135
+ ),
136
+ );
137
+ }
138
+
139
+ function setUpVite({ cwd, dryRun, out, guide }) {
115
140
  const config = findViteConfig(cwd);
116
141
  if (!config) {
117
- notes.push(`no vite.config found — add ${cyan(VITE_PLUGIN)} from "astralis-devtools/vite" to its plugins yourself`);
118
- return notes;
142
+ guide.because("no vite.config was found");
143
+ guide.step("Create vite.config.ts (vite.config.js in a JavaScript project) in your project's root with:", viteConfigSource);
144
+ return;
119
145
  }
120
146
  const path = join(cwd, config);
121
- const original = readFileSync(path, "utf8");
147
+ const { text: original, problem: readProblem } = tryRead(path);
148
+ if (readProblem) {
149
+ guide.because(`${config} couldn't be read: ${readProblem}`, { failed: true });
150
+ pluginStep(guide, config);
151
+ return;
152
+ }
122
153
  let source = original;
123
154
  for (const result of devtoolsViteEdits(source)) {
124
155
  if (result.note) {
125
- notes.push(`${config}: ${result.note} — add ${cyan(VITE_PLUGIN)} to its plugins yourself`);
126
- return notes;
156
+ guide.because(`${config}: ${result.note}`);
157
+ pluginStep(guide, config);
158
+ return;
127
159
  }
128
160
  source = result.source;
129
161
  }
130
162
  if (source === original) {
131
163
  out.step(() => ok(`DevTools plugin already in ${config}`));
132
- } else if (!parses(source)) {
133
- notes.push(`${config}: the edit would leave it unparseable, so nothing was written — add ${cyan(VITE_PLUGIN)} yourself`);
134
- return notes;
164
+ return;
165
+ }
166
+ const unparseable = !parses(source);
167
+ const problem = unparseable ? null : tryWrite(path, source, { dryRun });
168
+ if (unparseable || problem) {
169
+ guide.because(unparseable ? `${config}: the edit would leave it unparseable, so nothing was written` : `${config} couldn't be written: ${problem}`, {
170
+ failed: Boolean(problem),
171
+ });
172
+ pluginStep(guide, config);
173
+ return;
174
+ }
175
+ out.changed();
176
+ out.step(() => ok(`${dryRun ? "would add" : "added"} the DevTools plugin ${dim(`(${config})`)}`));
177
+ }
178
+
179
+ /**
180
+ * Install the package and write the files outside the entry file (the Next.js
181
+ * route; the Vite config). The Next.js layout edits go through init's own
182
+ * pipeline via devtoolsLayoutEdits; `layoutProblem` says why they didn't happen
183
+ * and `place` is the file they belong in. Returns { notes, guide }.
184
+ */
185
+ export function setUpDevtools({ cwd, pkg, pm, framework, entry, place, layoutProblem, dryRun, out, command }) {
186
+ const guide = createGuide({ title: "The DevTools aren't fully set up yet", docs: DOCS.devtools, check: CHECK_OPEN, retry: command });
187
+ const result = { notes: [], guide };
188
+
189
+ if (!framework) {
190
+ guide.because("the DevTools run in Next.js and in React + Vite projects, and this is neither as far as init can tell");
191
+ guide.step("If it is one of them, install the package:", `${pm} add -D ${PACKAGE}`);
192
+ guide.step("In a Vite project, add the plugin to vite.config.ts:", `${VITE_IMPORT}\n\nplugins: [react(), ${VITE_PLUGIN}],`);
193
+ guide.step("In a Next.js project, put this last inside <body> in app/layout.tsx:", `${NEXT_IMPORT}\n\n${NEXT_ELEMENT}`);
194
+ guide.step("And, for Next.js only, create app/api/astralis-devtools/[...path]/route.ts with:", ROUTE_SOURCE);
195
+ return result;
196
+ }
197
+
198
+ install({ cwd, pkg, pm, dryRun, out }, guide);
199
+ if (framework === "next") {
200
+ if (layoutProblem) {
201
+ guide.because(layoutProblem);
202
+ layoutStep(guide, place);
203
+ }
204
+ setUpRoute({ cwd, shown: entry ? routeFilePath(entry.relative) : routeFilePath(`${place.appDir}/layout.${/\.tsx$/.test(place.file) ? "tsx" : "js"}`), dryRun, out, guide });
135
205
  } else {
136
- out.changed();
137
- out.step(() => ok(`${dryRun ? "would add" : "added"} the DevTools plugin ${dim(`(${config})`)}`));
138
- if (!dryRun) writeFileSync(path, source);
206
+ setUpVite({ cwd, dryRun, out, guide });
139
207
  }
140
- sayHowToOpen(out);
141
- return notes;
208
+ if (!guide.needed) sayHowToOpen(out);
209
+ return result;
142
210
  }
@@ -8,8 +8,8 @@
8
8
  Astralis repository. It needs no client secret, so none ships here.
9
9
 
10
10
  The token is saved in a file only the user can read, in their config
11
- directory, and is shared by `astralis report` and the DevTools bridge. It
12
- never reaches a web page: both run in Node and call GitHub themselves.
11
+ directory, and is used by the DevTools bridge. It never reaches a web page:
12
+ the bridge runs in Node and calls GitHub itself.
13
13
  ========================================================================== */
14
14
 
15
15
  import { createHash } from "node:crypto";