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.
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 -29
  7. package/src/commands/create.mjs +73 -100
  8. package/src/commands/init.mjs +59 -22
  9. package/src/commands/report.mjs +257 -0
  10. package/src/commands/theme.mjs +77 -104
  11. package/src/commands/validate.mjs +101 -0
  12. package/src/index.mjs +26 -48
  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 +85 -39
  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 +11 -19
  37. package/src/lib/suggest.mjs +32 -0
  38. package/src/lib/ui.mjs +78 -36
  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,214 @@
1
+ /**
2
+ * The one command table. `--help`, the argument parser, the README and the
3
+ * docs site's CLI reference are all generated from it; test/reference.test.mjs
4
+ * fails when the README or docs page drift.
5
+ *
6
+ * Option fields: name, short?, type ("boolean" | "string"), arg? (placeholder
7
+ * for a string's value), description, default? (shown, not applied), group?.
8
+ */
9
+
10
+ export const DOCS_URL = "https://astralis-ui.com/docs/cli";
11
+
12
+ export const GLOBAL_OPTIONS = [
13
+ {
14
+ name: "yes",
15
+ short: "y",
16
+ type: "boolean",
17
+ description: "Never prompt; take the default answer. Replacing files still needs --overwrite or --force.",
18
+ },
19
+ { name: "help", short: "h", type: "boolean", description: "Show this command's options." },
20
+ { name: "debug", type: "boolean", description: "Print the stack trace if something fails unexpectedly." },
21
+ ];
22
+
23
+ export const COMMANDS = [
24
+ {
25
+ name: "create",
26
+ args: "<name>",
27
+ maxPositionals: 1,
28
+ passthrough: true,
29
+ summary: "Scaffold a new project with create-next-app or create-vite and wire Astralis into it",
30
+ options: [
31
+ { name: "framework", type: "string", arg: "next|vite", description: "Skip the framework prompt." },
32
+ {
33
+ name: "no-starter",
34
+ type: "boolean",
35
+ description: "Keep the scaffolder's demo page instead of the Astralis welcome screen.",
36
+ },
37
+ {
38
+ name: "no-devtools",
39
+ type: "boolean",
40
+ description: "Leave out the Astralis DevTools overlay, which new projects get in development.",
41
+ },
42
+ ],
43
+ notes: ["Any other argument passes straight to the scaffolder."],
44
+ examples: ["astralis create my-app", "astralis create my-app --framework vite --template react"],
45
+ },
46
+ {
47
+ name: "init",
48
+ args: "",
49
+ maxPositionals: 0,
50
+ summary: "Wire astralis-ui into an existing Next.js or React + Vite project",
51
+ options: [
52
+ { name: "dry-run", type: "boolean", description: "Show the changes without writing anything." },
53
+ {
54
+ name: "ci",
55
+ type: "boolean",
56
+ description:
57
+ "Also check every pull request: pin astralis-cli, add a validate script and write a GitHub Actions workflow.",
58
+ },
59
+ { name: "force", type: "boolean", description: "With --ci, replace an existing astralis-validate.yml." },
60
+ {
61
+ name: "devtools",
62
+ type: "boolean",
63
+ description:
64
+ "Also add the Astralis DevTools overlay (development only): install astralis-devtools and wire it into the root layout or vite.config.",
65
+ },
66
+ ],
67
+ notes: [
68
+ "init --ci is safe to re-run: it adds only what is missing and never replaces a workflow without --force.",
69
+ "init --devtools is safe to re-run too; production builds contain none of the DevTools.",
70
+ ],
71
+ examples: ["astralis init", "astralis init --dry-run", "astralis init --ci", "astralis init --devtools"],
72
+ },
73
+ {
74
+ name: "add",
75
+ args: "<block...>",
76
+ maxPositionals: Infinity,
77
+ summary: "Copy a block's source into this project",
78
+ options: [
79
+ { name: "list", type: "boolean", description: "Print every available block, by category, and exit." },
80
+ {
81
+ name: "dir",
82
+ type: "string",
83
+ arg: "path",
84
+ description: "Where to write.",
85
+ default: "src/components/blocks, or components/blocks without a src/",
86
+ },
87
+ { name: "overwrite", type: "boolean", description: "Replace existing files without asking." },
88
+ { name: "dry-run", type: "boolean", description: "Show what would be written; write nothing." },
89
+ { name: "registry", type: "string", arg: "url", description: "Read blocks from a different registry host." },
90
+ ],
91
+ examples: ["astralis add hero-01", "astralis add login-01 dashboard-02 --dir src/ui/blocks", "astralis add --list"],
92
+ },
93
+ {
94
+ name: "theme",
95
+ args: "[hex]",
96
+ maxPositionals: 1,
97
+ summary: "Generate a static theme stylesheet from a seed",
98
+ options: [
99
+ { group: "Colours", name: "brand", type: "string", arg: "hex", description: 'Brand hue, e.g. "#8b5cf6". A bare hex argument means the same.' },
100
+ { group: "Colours", name: "gray", type: "string", arg: "hex", description: "Neutral hue: every surface, label and border." },
101
+ { group: "Status", name: "error", type: "string", arg: "hex", description: "Seeds the error palette.", default: "red" },
102
+ { group: "Status", name: "warning", type: "string", arg: "hex", description: "Seeds the warning palette.", default: "orange" },
103
+ { group: "Status", name: "success", type: "string", arg: "hex", description: "Seeds the success palette.", default: "green" },
104
+ { group: "Status", name: "info", type: "string", arg: "hex", description: "Seeds the info palette.", default: "blue" },
105
+ { group: "Typefaces", name: "font-heading", type: "string", arg: "stack", description: "Heading font stack." },
106
+ { group: "Typefaces", name: "font-body", type: "string", arg: "stack", description: "Body font stack." },
107
+ { group: "Typefaces", name: "font-mono", type: "string", arg: "stack", description: "Monospace font stack." },
108
+ { group: "Scales", name: "radius", type: "string", arg: "n", description: "Border-radius multiplier.", default: "1" },
109
+ { group: "Scales", name: "spacing", type: "string", arg: "n", description: "Spacing multiplier: the density dial.", default: "1" },
110
+ { group: "Scales", name: "font-scale", type: "string", arg: "n", description: "Font-size multiplier.", default: "1" },
111
+ { group: "Scales", name: "motion", type: "string", arg: "n", description: "Duration multiplier; 0 turns transitions off.", default: "1" },
112
+ {
113
+ group: "Output",
114
+ name: "out",
115
+ type: "string",
116
+ arg: "file",
117
+ description: "Where to write the stylesheet.",
118
+ default: "src/astralis-theme.css, or astralis-theme.css without a src/",
119
+ },
120
+ { group: "Output", name: "force", type: "boolean", description: "Overwrite an existing file." },
121
+ { group: "Output", name: "no-import", type: "boolean", description: "Write the file but leave the entry file alone." },
122
+ {
123
+ group: "Output",
124
+ name: "strict-contrast",
125
+ type: "boolean",
126
+ description: "Exit 1, writing nothing, if any promised pairing fails WCAG AA.",
127
+ },
128
+ ],
129
+ notes: ["The status hues' own colorScheme values are never altered; each status seeds its own palette."],
130
+ examples: ['astralis theme "#8b5cf6"', 'astralis theme --brand "#8b5cf6" --gray "#64748b" --radius 1.5'],
131
+ },
132
+ {
133
+ name: "validate",
134
+ args: "[paths...]",
135
+ maxPositionals: Infinity,
136
+ summary: "Check TSX and JSX against the installed design system",
137
+ options: [
138
+ {
139
+ name: "format",
140
+ type: "string",
141
+ arg: "text|json|github",
142
+ description: "How to report: text for people, json for tools, github for inline pull-request annotations.",
143
+ default: "github inside GitHub Actions, text elsewhere",
144
+ },
145
+ { name: "json", type: "boolean", description: "Same as --format json." },
146
+ {
147
+ name: "spec",
148
+ type: "string",
149
+ arg: "path",
150
+ description: "Validate against this system-spec.json.",
151
+ default: "the installed astralis-ui's",
152
+ },
153
+ { name: "strict-tokens", type: "boolean", description: "Also warn on raw colors that bypass the tokens." },
154
+ ],
155
+ notes: [
156
+ "With no paths it checks the current directory, skipping node_modules and build output.",
157
+ "Exits 1 when there are errors; warnings are reported but never fail the run.",
158
+ ],
159
+ examples: ["astralis validate", "astralis validate src/components --json", "astralis validate --strict-tokens"],
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
+ {
198
+ name: "connect-mcp",
199
+ args: "",
200
+ maxPositionals: 0,
201
+ summary: "Connect an AI coding agent to the Astralis MCP docs server",
202
+ options: [
203
+ {
204
+ name: "client",
205
+ type: "string",
206
+ arg: "claude-code|codex|cursor|claude-desktop|antigravity",
207
+ description: "Skip the prompt and configure this client.",
208
+ },
209
+ ],
210
+ examples: ["astralis connect-mcp", "astralis connect-mcp --client cursor --yes"],
211
+ },
212
+ ];
213
+
214
+ export const commandNamed = (name) => COMMANDS.find((command) => command.name === name);
@@ -0,0 +1,141 @@
1
+ /* ==========================================================================
2
+ ASTRALIS — CSS VALUE GRAMMAR (Tier C)
3
+ --------------------------------------------------------------------------
4
+ Classifies an ARBITRARY channel value (a string that is not a token)
5
+ against the value type its channel carries — length, color, shadow,
6
+ number, integer (spec propGroups[*].valueType).
7
+
8
+ The design rule: NEVER reject valid CSS. A false "invalid" kills trust in
9
+ the whole validator, so the grammar only condemns what is definitely
10
+ wrong — a lone identifier outside the property's keyword set ("surfase",
11
+ "fulll"), a unit that doesn't exist ("37pxx"), a function that cannot
12
+ produce this value type (a gradient where a plain color goes). Anything
13
+ it cannot decide — multi-part shorthands, layered shadows, exotic but
14
+ plausible syntax — returns "no-claim" and passes.
15
+
16
+ Verdicts: ok | invalid (+reason) | bare-number (caller warns, same rule
17
+ as the runtime) | no-claim.
18
+ ========================================================================== */
19
+
20
+ const CSS_WIDE = new Set(["inherit", "initial", "unset", "revert", "revert-layer"]);
21
+
22
+ const LENGTH_KEYWORDS = new Set([
23
+ "auto", "none", "max-content", "min-content", "fit-content", "stretch",
24
+ ]);
25
+
26
+ const LENGTH_UNITS = new Set([
27
+ "px", "em", "rem", "ex", "ch", "cap", "ic", "lh", "rlh",
28
+ "vw", "vh", "vi", "vb", "vmin", "vmax",
29
+ "dvw", "dvh", "svw", "svh", "lvw", "lvh",
30
+ "cqw", "cqh", "cqi", "cqb", "cqmin", "cqmax",
31
+ "cm", "mm", "q", "in", "pt", "pc",
32
+ ]);
33
+
34
+ const FUNCTIONS = {
35
+ length: new Set(["var", "calc", "min", "max", "clamp", "env", "fit-content"]),
36
+ color: new Set([
37
+ "var", "rgb", "rgba", "hsl", "hsla", "hwb", "lab", "lch", "oklab", "oklch",
38
+ "color", "color-mix", "light-dark",
39
+ ]),
40
+ shadow: new Set(["var"]),
41
+ number: new Set(["var", "calc", "min", "max", "clamp"]),
42
+ integer: new Set(["var", "calc"]),
43
+ };
44
+
45
+ /** The CSS named colors, plus transparent/currentColor. */
46
+ const NAMED_COLORS = new Set([
47
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque",
48
+ "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood",
49
+ "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk",
50
+ "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray",
51
+ "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen",
52
+ "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
53
+ "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise",
54
+ "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue",
55
+ "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro",
56
+ "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "grey",
57
+ "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
58
+ "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
59
+ "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey",
60
+ "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
61
+ "lightslategrey", "lightsteelblue", "lightyellow", "lime", "limegreen",
62
+ "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue",
63
+ "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue",
64
+ "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue",
65
+ "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace",
66
+ "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod",
67
+ "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff",
68
+ "peru", "pink", "plum", "powderblue", "purple", "rebeccapurple", "red",
69
+ "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen",
70
+ "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray",
71
+ "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle",
72
+ "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow",
73
+ "yellowgreen",
74
+ "transparent", "currentcolor",
75
+ ]);
76
+
77
+ const ok = { verdict: "ok" };
78
+ const invalid = (reason) => ({ verdict: "invalid", reason });
79
+
80
+ /**
81
+ * Classify one arbitrary channel value against its value type.
82
+ * @returns {{ verdict: "ok"|"invalid"|"bare-number"|"no-claim", reason?: string }}
83
+ */
84
+ export function classifyChannelValue(raw, type) {
85
+ const value = raw.trim();
86
+
87
+ // Function calls first — their arguments may contain spaces and commas.
88
+ const fn = value.match(/^([a-zA-Z-]+)\((.*)\)$/s);
89
+ if (fn) {
90
+ const name = fn[1].toLowerCase();
91
+ if (FUNCTIONS[type]?.has(name)) return ok;
92
+ if (type === "color" && name.endsWith("gradient")) {
93
+ return invalid(
94
+ `${name}() is a background-image — this channel sets a plain color; use style={{ backgroundImage: ... }} for gradients`,
95
+ );
96
+ }
97
+ return invalid(`${name}() cannot produce a ${type}`);
98
+ }
99
+
100
+ // Multi-part values (padding shorthands, layered shadows): no claim.
101
+ if (/[\s,]/.test(value)) return { verdict: "no-claim" };
102
+
103
+ if (CSS_WIDE.has(value.toLowerCase())) return ok;
104
+
105
+ // Numbers, with or without a unit.
106
+ const num = value.match(/^[+-]?(?:\d+\.?\d*|\.\d+)([a-z%]*)$/i);
107
+ if (num) {
108
+ const unit = num[1].toLowerCase();
109
+ switch (type) {
110
+ case "integer":
111
+ return unit === "" && /^[+-]?\d+$/.test(value) ? ok : invalid("takes a whole number");
112
+ case "number":
113
+ return unit === "" || unit === "%" ? ok : invalid("takes a plain number or percentage");
114
+ case "length":
115
+ if (unit === "") return { verdict: "bare-number" };
116
+ return unit === "%" || LENGTH_UNITS.has(unit)
117
+ ? ok
118
+ : invalid(`"${unit}" is not a CSS length unit`);
119
+ default:
120
+ return invalid(`a number is not a ${type}`);
121
+ }
122
+ }
123
+
124
+ // A lone identifier — the class the grammar exists for ("surfase", "fulll").
125
+ if (/^[a-z-]+$/i.test(value)) {
126
+ const word = value.toLowerCase();
127
+ if (type === "color") return NAMED_COLORS.has(word) ? ok : invalid("not a CSS color name");
128
+ if (type === "length") return LENGTH_KEYWORDS.has(word) ? ok : invalid("not a CSS sizing keyword");
129
+ if (type === "shadow") return word === "none" ? ok : invalid("not a shadow");
130
+ return invalid(`takes a ${type === "integer" ? "whole number" : "number"}`);
131
+ }
132
+
133
+ if (type === "color") {
134
+ const hex = value.match(/^#([0-9a-f]+)$/i);
135
+ if (hex) {
136
+ return [3, 4, 6, 8].includes(hex[1].length) ? ok : invalid("malformed hex color");
137
+ }
138
+ }
139
+
140
+ return { verdict: "no-claim" };
141
+ }
@@ -0,0 +1,142 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { addArrayElement, addImports, insertBeforeBodyClose, parses } from "./edits.mjs";
4
+ import { ok, info, fail, bold, cyan, dim, posix } from "./ui.mjs";
5
+ import { runCommand } from "./run.mjs";
6
+
7
+ /* The --devtools half of `astralis init`: astralis-devtools as a
8
+ devDependency, and the wiring its framework needs. Next.js gets the overlay
9
+ component in the root layout and the bridge's route handler; Vite gets the
10
+ plugin. Every step is skipped when already done. */
11
+
12
+ export const PACKAGE = "astralis-devtools";
13
+ export const NEXT_IMPORT = 'import { AstralisDevTools } from "astralis-devtools/next";';
14
+ export const NEXT_ELEMENT = "<AstralisDevTools />";
15
+ export const ROUTE_SOURCE = 'export { GET, POST } from "astralis-devtools/next/route";\n';
16
+ /** What init wrote before the bridge took reports. */
17
+ const GET_ONLY_ROUTE_SOURCE = 'export { GET } from "astralis-devtools/next/route";\n';
18
+ export const VITE_IMPORT = 'import { astralisDevtools } from "astralis-devtools/vite";';
19
+ export const VITE_PLUGIN = "astralisDevtools()";
20
+
21
+ const VITE_CONFIGS = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs", "vite.config.cts", "vite.config.cjs"];
22
+
23
+ /**
24
+ * The bridge's route file next to the root layout's app directory:
25
+ * app/layout.tsx → app/api/astralis-devtools/[...path]/route.ts (.js for a
26
+ * JavaScript layout).
27
+ */
28
+ export function routeFilePath(layoutRelative) {
29
+ const appDir = dirname(layoutRelative);
30
+ const ext = /\.tsx$/.test(layoutRelative) ? "ts" : "js";
31
+ return posix(join(appDir, "api", "astralis-devtools", "[...path]", `route.${ext}`));
32
+ }
33
+
34
+ /** The layout's own edits: the import and the element before </body>. Chains into init's `apply`. */
35
+ export function devtoolsLayoutEdits(source) {
36
+ const imported = addImports(source, [NEXT_IMPORT]);
37
+ const placed = insertBeforeBodyClose(imported.source, NEXT_ELEMENT, "<AstralisDevTools");
38
+ return [imported, placed];
39
+ }
40
+
41
+ export function findViteConfig(cwd) {
42
+ return VITE_CONFIGS.find((name) => existsSync(join(cwd, name))) ?? null;
43
+ }
44
+
45
+ /** The Vite config with the import and the plugin added. */
46
+ export function devtoolsViteEdits(source) {
47
+ const imported = addImports(source, [VITE_IMPORT]);
48
+ const added = addArrayElement(imported.source, "plugins", VITE_PLUGIN, "astralisDevtools(");
49
+ return [imported, added];
50
+ }
51
+
52
+ function install({ cwd, pkg, pm, dryRun, out }) {
53
+ const had = Boolean(pkg.dependencies?.[PACKAGE] ?? pkg.devDependencies?.[PACKAGE]);
54
+ if (had) {
55
+ out.step(() => ok(`${PACKAGE} already in dependencies`));
56
+ } else if (dryRun) {
57
+ out.changed();
58
+ out.step(() => info(`would run: ${pm} add -D ${PACKAGE}`));
59
+ } else {
60
+ out.changed();
61
+ out.flush();
62
+ info(`installing ${PACKAGE} with ${pm}…`);
63
+ 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`);
66
+ }
67
+ }
68
+
69
+ function sayHowToOpen(out) {
70
+ out.after(() => {
71
+ console.log(`\n${bold("DevTools:")} start the dev server and click the ${cyan("✦")} button in the corner of the page.`);
72
+ console.log(dim(" Development only: production builds contain none of it."));
73
+ });
74
+ }
75
+
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 });
84
+
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`);
103
+ } 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);
109
+ }
110
+ }
111
+ sayHowToOpen(out);
112
+ return notes;
113
+ }
114
+
115
+ const config = findViteConfig(cwd);
116
+ if (!config) {
117
+ notes.push(`no vite.config found — add ${cyan(VITE_PLUGIN)} from "astralis-devtools/vite" to its plugins yourself`);
118
+ return notes;
119
+ }
120
+ const path = join(cwd, config);
121
+ const original = readFileSync(path, "utf8");
122
+ let source = original;
123
+ for (const result of devtoolsViteEdits(source)) {
124
+ if (result.note) {
125
+ notes.push(`${config}: ${result.note} — add ${cyan(VITE_PLUGIN)} to its plugins yourself`);
126
+ return notes;
127
+ }
128
+ source = result.source;
129
+ }
130
+ if (source === original) {
131
+ 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;
135
+ } else {
136
+ out.changed();
137
+ out.step(() => ok(`${dryRun ? "would add" : "added"} the DevTools plugin ${dim(`(${config})`)}`));
138
+ if (!dryRun) writeFileSync(path, source);
139
+ }
140
+ sayHowToOpen(out);
141
+ return notes;
142
+ }