astralis-cli 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 -27
- package/src/commands/create.mjs +133 -39
- package/src/commands/init.mjs +125 -28
- package/src/commands/report.mjs +257 -0
- package/src/commands/theme.mjs +100 -82
- package/src/commands/validate.mjs +101 -0
- package/src/index.mjs +26 -47
- 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 +97 -0
- 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 +219 -0
- package/src/lib/suggest.mjs +32 -0
- package/src/lib/ui.mjs +85 -51
- 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
|
@@ -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
|
+
}
|
package/src/lib/edits.mjs
CHANGED
|
@@ -1,26 +1,149 @@
|
|
|
1
|
+
import { parse } from "@babel/parser";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Idempotent transforms for init's and theme's entry-file edits. Every function
|
|
5
|
+
* returns { source, changed, note? } and NEVER guesses: when a file's shape is
|
|
6
|
+
* ambiguous or unparseable it declines with a note, so the caller can print
|
|
7
|
+
* manual instructions instead of corrupting code.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const PARSE_OPTIONS = { sourceType: "module", plugins: ["typescript", "jsx"] };
|
|
11
|
+
|
|
12
|
+
function parseModule(source) {
|
|
13
|
+
try {
|
|
14
|
+
return parse(source, PARSE_OPTIONS);
|
|
15
|
+
} catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** True when the source is a module Babel can parse — the check before any write. */
|
|
21
|
+
export function parses(source) {
|
|
22
|
+
return parseModule(source) !== null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const importedName = (specifier) =>
|
|
26
|
+
specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
|
|
27
|
+
|
|
28
|
+
/** Named imports that provide a runtime value (`import type` provides none). */
|
|
29
|
+
function valueNames(declaration) {
|
|
30
|
+
if (declaration.importKind === "type") return [];
|
|
31
|
+
return declaration.specifiers
|
|
32
|
+
.filter((s) => s.type === "ImportSpecifier" && s.importKind !== "type")
|
|
33
|
+
.map(importedName);
|
|
34
|
+
}
|
|
35
|
+
|
|
1
36
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
37
|
+
* Where a new top-level line goes: after the last import, else after the
|
|
38
|
+
* directive prologue ("use client"), else at the very top. Positioned at the
|
|
39
|
+
* end of that statement's line, unless a comment opened on that line runs past
|
|
40
|
+
* it — then right after the statement.
|
|
6
41
|
*/
|
|
42
|
+
function insertionPoint(ast, source) {
|
|
43
|
+
const imports = ast.program.body.filter((n) => n.type === "ImportDeclaration");
|
|
44
|
+
const anchor = imports.at(-1) ?? ast.program.directives.at(-1) ?? ast.program.interpreter;
|
|
45
|
+
if (!anchor) return { at: 0, top: true };
|
|
7
46
|
|
|
8
|
-
|
|
47
|
+
const newline = source.indexOf("\n", anchor.end);
|
|
48
|
+
const lineEnd = newline === -1 ? source.length : newline;
|
|
49
|
+
const spanning = ast.comments.some((c) => c.start >= anchor.end && c.start < lineEnd && c.end > lineEnd);
|
|
50
|
+
return { at: spanning ? anchor.end : lineEnd, top: false };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The file's own quote and semicolon habit, read off its last import. */
|
|
54
|
+
function importStyle(ast) {
|
|
55
|
+
const last = ast.program.body.filter((n) => n.type === "ImportDeclaration").at(-1);
|
|
56
|
+
if (!last) return null;
|
|
57
|
+
return { quote: last.source.extra.raw[0], semicolon: last.source.end < last.end };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Re-render a single-line import in the file's style. */
|
|
61
|
+
function restyle(line, declaration, style) {
|
|
62
|
+
if (!style) return line;
|
|
63
|
+
const { start, end } = declaration.source;
|
|
64
|
+
const quoted = style.quote + declaration.source.value + style.quote;
|
|
65
|
+
const body = line.slice(0, start) + quoted + line.slice(end, declaration.end).replace(/;\s*$/, "");
|
|
66
|
+
return body + (style.semicolon ? ";" : "");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Add imports that aren't already satisfied, judged by parsed specifiers, not
|
|
71
|
+
* text: `import { AstralisProvider, Button } from 'astralis-ui'` already
|
|
72
|
+
* provides AstralisProvider, however it is quoted or wrapped. A named import
|
|
73
|
+
* missing from an existing declaration of the same module is merged into it,
|
|
74
|
+
* so the file never gains a second import of the same binding.
|
|
75
|
+
*
|
|
76
|
+
* `lines` are single import statements, e.g. `import "astralis-ui/styles.css";`.
|
|
77
|
+
* A default or namespace import is added whole unless one already exists.
|
|
78
|
+
*/
|
|
9
79
|
export function addImports(source, lines) {
|
|
10
|
-
const
|
|
11
|
-
if (
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
80
|
+
const ast = parseModule(source);
|
|
81
|
+
if (!ast) return { source, changed: false, note: "the file doesn't parse, so it was left alone" };
|
|
82
|
+
|
|
83
|
+
const existing = ast.program.body.filter((n) => n.type === "ImportDeclaration");
|
|
84
|
+
const style = importStyle(ast);
|
|
85
|
+
const merges = []; // { at, text }
|
|
86
|
+
const additions = [];
|
|
87
|
+
|
|
88
|
+
for (const line of lines) {
|
|
89
|
+
const wanted = parse(line, PARSE_OPTIONS).program.body[0];
|
|
90
|
+
const from = wanted.source.value;
|
|
91
|
+
const sameModule = existing.filter((n) => n.source.value === from);
|
|
92
|
+
|
|
93
|
+
if (wanted.specifiers.length === 0) {
|
|
94
|
+
// Any import of a module evaluates it, so a side-effect import is satisfied by any of them.
|
|
95
|
+
if (sameModule.length === 0) additions.push(restyle(line, wanted, style));
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (wanted.specifiers.some((s) => s.type !== "ImportSpecifier")) {
|
|
100
|
+
const kinds = wanted.specifiers.map((s) => s.type);
|
|
101
|
+
const satisfied = sameModule.some(
|
|
102
|
+
(n) => n.importKind !== "type" && kinds.every((kind) => n.specifiers.some((s) => s.type === kind)),
|
|
103
|
+
);
|
|
104
|
+
if (!satisfied) additions.push(restyle(line, wanted, style));
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const have = new Set(sameModule.flatMap(valueNames));
|
|
109
|
+
const missing = valueNames(wanted).filter((name) => !have.has(name));
|
|
110
|
+
if (missing.length === 0) continue;
|
|
111
|
+
|
|
112
|
+
const target = sameModule.find(
|
|
113
|
+
(n) => n.importKind !== "type" && n.specifiers.some((s) => s.type === "ImportSpecifier"),
|
|
114
|
+
);
|
|
115
|
+
if (target) {
|
|
116
|
+
const lastSpecifier = target.specifiers.filter((s) => s.type === "ImportSpecifier").at(-1);
|
|
117
|
+
merges.push({ at: lastSpecifier.end, text: missing.map((name) => `, ${name}`).join("") });
|
|
118
|
+
} else {
|
|
119
|
+
const named = `import { ${missing.join(", ")} } from "${from}";`;
|
|
120
|
+
additions.push(restyle(named, parse(named, PARSE_OPTIONS).program.body[0], style));
|
|
121
|
+
}
|
|
19
122
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
123
|
+
|
|
124
|
+
if (merges.length === 0 && additions.length === 0) return { source, changed: false };
|
|
125
|
+
|
|
126
|
+
// Splice from the end backwards so earlier offsets stay valid.
|
|
127
|
+
const { at, top } = insertionPoint(ast, source);
|
|
128
|
+
const edits = [...merges];
|
|
129
|
+
if (additions.length > 0) {
|
|
130
|
+
edits.push({ at, text: top ? additions.join("\n") + "\n" : "\n" + additions.join("\n") });
|
|
131
|
+
}
|
|
132
|
+
let next = source;
|
|
133
|
+
for (const edit of edits.sort((a, b) => b.at - a.at)) {
|
|
134
|
+
next = next.slice(0, edit.at) + edit.text + next.slice(edit.at);
|
|
135
|
+
}
|
|
136
|
+
return { source: next, changed: true };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Insert a top-level statement after the import block (e.g. the theme-init const). */
|
|
140
|
+
export function addStatementAfterImports(source, statement) {
|
|
141
|
+
if (source.includes(statement.slice(0, 40))) return { source, changed: false };
|
|
142
|
+
const ast = parseModule(source);
|
|
143
|
+
if (!ast) return { source, changed: false, note: "the file doesn't parse, so it was left alone" };
|
|
144
|
+
const { at, top } = insertionPoint(ast, source);
|
|
145
|
+
const text = top ? statement + "\n\n" : "\n\n" + statement;
|
|
146
|
+
return { source: source.slice(0, at) + text + source.slice(at), changed: true };
|
|
24
147
|
}
|
|
25
148
|
|
|
26
149
|
/** Wrap a single unambiguous occurrence of `target` in open/close JSX tags. */
|
|
@@ -39,6 +162,71 @@ export function addTagAttribute(source, tag, attribute) {
|
|
|
39
162
|
return { source: source.replace(matches[0][0], `<${tag} ${attribute}`), changed: true };
|
|
40
163
|
}
|
|
41
164
|
|
|
165
|
+
/**
|
|
166
|
+
* Insert markup as the last child of <body>, on its own line indented one
|
|
167
|
+
* step inside the body when </body> starts its line, else just before it.
|
|
168
|
+
* Skipped when `marker` (e.g. "<AstralisDevTools") is already in the file.
|
|
169
|
+
*/
|
|
170
|
+
export function insertBeforeBodyClose(source, markup, marker = markup) {
|
|
171
|
+
if (source.includes(marker)) return { source, changed: false };
|
|
172
|
+
const matches = [...source.matchAll(/<\/body>/g)];
|
|
173
|
+
if (matches.length !== 1) return { source, changed: false, note: "</body> not found unambiguously" };
|
|
174
|
+
const at = matches[0].index;
|
|
175
|
+
const lineStart = source.lastIndexOf("\n", at - 1) + 1;
|
|
176
|
+
const before = source.slice(lineStart, at);
|
|
177
|
+
if (/^\s*$/.test(before)) {
|
|
178
|
+
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
|
179
|
+
return { source: `${source.slice(0, lineStart)}${before} ${markup}${eol}${source.slice(lineStart)}`, changed: true };
|
|
180
|
+
}
|
|
181
|
+
return { source: source.slice(0, at) + markup + source.slice(at), changed: true };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Append an element to the one array literal assigned to `property` (Vite's
|
|
186
|
+
* `plugins: [react()]`), matching the array's layout: inline stays inline, one
|
|
187
|
+
* per line stays one per line, a trailing comma stays. Skipped when `marker`
|
|
188
|
+
* already appears inside the array.
|
|
189
|
+
*/
|
|
190
|
+
export function addArrayElement(source, property, element, marker = element) {
|
|
191
|
+
const ast = parseModule(source);
|
|
192
|
+
if (!ast) return { source, changed: false, note: "the file doesn't parse, so it was left alone" };
|
|
193
|
+
|
|
194
|
+
const arrays = [];
|
|
195
|
+
(function walk(node) {
|
|
196
|
+
if (!node || typeof node.type !== "string") return;
|
|
197
|
+
if (
|
|
198
|
+
(node.type === "ObjectProperty" || node.type === "Property") &&
|
|
199
|
+
!node.computed &&
|
|
200
|
+
(node.key.name ?? node.key.value) === property &&
|
|
201
|
+
node.value.type === "ArrayExpression"
|
|
202
|
+
) {
|
|
203
|
+
arrays.push(node.value);
|
|
204
|
+
}
|
|
205
|
+
for (const key of Object.keys(node)) {
|
|
206
|
+
if (key === "loc" || key === "start" || key === "end") continue;
|
|
207
|
+
const value = node[key];
|
|
208
|
+
if (Array.isArray(value)) value.forEach(walk);
|
|
209
|
+
else if (value && typeof value === "object") walk(value);
|
|
210
|
+
}
|
|
211
|
+
})(ast.program);
|
|
212
|
+
|
|
213
|
+
if (arrays.length !== 1) return { source, changed: false, note: `no single \`${property}: [...]\` array found` };
|
|
214
|
+
const array = arrays[0];
|
|
215
|
+
if (source.slice(array.start, array.end).includes(marker)) return { source, changed: false };
|
|
216
|
+
|
|
217
|
+
const items = array.elements.filter(Boolean);
|
|
218
|
+
if (items.length === 0) {
|
|
219
|
+
return { source: source.slice(0, array.start + 1) + element + source.slice(array.end - 1), changed: true };
|
|
220
|
+
}
|
|
221
|
+
const last = items.at(-1);
|
|
222
|
+
const multiline = source.slice(array.start, array.end).includes("\n");
|
|
223
|
+
if (!multiline) return { source: `${source.slice(0, last.end)}, ${element}${source.slice(last.end)}`, changed: true };
|
|
224
|
+
const lineStart = source.lastIndexOf("\n", last.start - 1) + 1;
|
|
225
|
+
const indent = source.slice(lineStart, last.start).match(/^\s*/)[0];
|
|
226
|
+
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
|
227
|
+
return { source: `${source.slice(0, last.end)},${eol}${indent}${element}${source.slice(last.end)}`, changed: true };
|
|
228
|
+
}
|
|
229
|
+
|
|
42
230
|
/** Insert markup right after the opening <body ...> tag. */
|
|
43
231
|
export function insertAfterBodyTag(source, insert) {
|
|
44
232
|
if (source.includes(insert.trim())) return { source, changed: false };
|
|
@@ -47,11 +235,3 @@ export function insertAfterBodyTag(source, insert) {
|
|
|
47
235
|
const at = matches[0].index + matches[0][0].length;
|
|
48
236
|
return { source: source.slice(0, at) + insert + source.slice(at), changed: true };
|
|
49
237
|
}
|
|
50
|
-
|
|
51
|
-
/** Insert a top-level statement after the import block (e.g. the theme-init const). */
|
|
52
|
-
export function addStatementAfterImports(source, statement) {
|
|
53
|
-
if (source.includes(statement.slice(0, 40))) return { source, changed: false };
|
|
54
|
-
const imports = [...source.matchAll(/^import\s[^\n]*$/gm)];
|
|
55
|
-
const insertAt = imports.length > 0 ? imports[imports.length - 1].index + imports[imports.length - 1][0].length : 0;
|
|
56
|
-
return { source: source.slice(0, insertAt) + "\n\n" + statement + source.slice(insertAt), changed: true };
|
|
57
|
-
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
2
|
+
import { posix } from "./ui.mjs";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* GitHub Actions workflow commands: one `::error` / `::warning` line per
|
|
6
|
+
* finding, which GitHub shows on the changed line of the pull request.
|
|
7
|
+
* https://docs.github.com/actions/reference/workflow-commands-for-github-actions
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const escapeData = (text) => String(text).replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
|
|
11
|
+
const escapeProperty = (text) => escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* GitHub places an annotation by its path from the repository root, which is
|
|
15
|
+
* not the working directory when the project sits in a subfolder of the repo.
|
|
16
|
+
*/
|
|
17
|
+
export function repositoryPath(file, { cwd = process.cwd(), workspace = process.env.GITHUB_WORKSPACE } = {}) {
|
|
18
|
+
const absolute = isAbsolute(file) ? file : resolve(cwd, file);
|
|
19
|
+
return posix(workspace ? relative(workspace, absolute) : relative(cwd, absolute));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function annotation(kind, finding, options) {
|
|
23
|
+
const file = repositoryPath(finding.file, options);
|
|
24
|
+
const properties = [`file=${escapeProperty(file)}`, `line=${finding.line}`, `col=${finding.column}`, `title=${escapeProperty(`astralis ${finding.code}`)}`];
|
|
25
|
+
return `::${kind === "error" ? "error" : "warning"} ${properties.join(",")}::${escapeData(finding.message)}`;
|
|
26
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Snapshot } from "./snapshot.mjs";
|
|
2
|
+
|
|
3
|
+
/** Reporting to GitHub: sign-in through the Astralis DevTools GitHub App, the saved sign-in, and issues. Node only. */
|
|
4
|
+
|
|
5
|
+
export const GITHUB_CLIENT_ID: string;
|
|
6
|
+
export const ISSUES_REPO: string;
|
|
7
|
+
/** The app's client ID (ASTRALIS_GITHUB_CLIENT_ID overrides it). Empty when sign-in is not set up. */
|
|
8
|
+
export function clientId(): string;
|
|
9
|
+
/** The repository reports go to (ASTRALIS_ISSUES_REPO overrides it). */
|
|
10
|
+
export function issuesRepo(): string;
|
|
11
|
+
|
|
12
|
+
export type GitHubErrorCode = "network" | "signed-out" | "forbidden" | "github" | "not-configured" | "expired" | "denied" | "cancelled";
|
|
13
|
+
export class GitHubError extends Error {
|
|
14
|
+
code: GitHubErrorCode;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface SavedSignIn {
|
|
18
|
+
token: string;
|
|
19
|
+
login: string;
|
|
20
|
+
savedAt: string;
|
|
21
|
+
}
|
|
22
|
+
/** The user's config directory for Astralis. */
|
|
23
|
+
export function configDir(env?: Record<string, string | undefined>): string;
|
|
24
|
+
export function tokenStore(dir?: string): {
|
|
25
|
+
file: string;
|
|
26
|
+
read(): SavedSignIn | null;
|
|
27
|
+
write(signIn: { token: string; login: string }): void;
|
|
28
|
+
clear(): void;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export interface SignInFlow {
|
|
32
|
+
deviceCode: string;
|
|
33
|
+
userCode: string;
|
|
34
|
+
verificationUri: string;
|
|
35
|
+
expiresAt: number;
|
|
36
|
+
interval: number;
|
|
37
|
+
}
|
|
38
|
+
interface FetchOptions {
|
|
39
|
+
fetchImpl?: typeof fetch;
|
|
40
|
+
}
|
|
41
|
+
export function startSignIn(options?: FetchOptions): Promise<SignInFlow>;
|
|
42
|
+
export function finishSignIn(
|
|
43
|
+
flow: SignInFlow,
|
|
44
|
+
options?: FetchOptions & { sleep?: (ms: number) => Promise<void>; signal?: AbortSignal },
|
|
45
|
+
): Promise<{ token: string; login: string }>;
|
|
46
|
+
|
|
47
|
+
export interface IssueSummary {
|
|
48
|
+
number: number;
|
|
49
|
+
title: string;
|
|
50
|
+
state: "open" | "closed";
|
|
51
|
+
stateReason: string | null;
|
|
52
|
+
url: string;
|
|
53
|
+
comments: number;
|
|
54
|
+
labels: string[];
|
|
55
|
+
createdAt: string;
|
|
56
|
+
updatedAt: string;
|
|
57
|
+
}
|
|
58
|
+
export function createIssue(token: string, issue: { title: string; body: string }, options?: FetchOptions): Promise<{ number: number; url: string }>;
|
|
59
|
+
export function listIssues(token: string, login: string, options?: FetchOptions): Promise<IssueSummary[]>;
|
|
60
|
+
/** The title and Markdown body of the issue a snapshot becomes. */
|
|
61
|
+
export function issueFromSnapshot(snapshot: Snapshot): { title: string; body: string };
|
|
62
|
+
|
|
63
|
+
/** Add a report to an existing issue, as a comment. */
|
|
64
|
+
export function commentOnIssue(token: string, number: number, body: string, options?: FetchOptions): Promise<{ number: number; url: string }>;
|
|
65
|
+
/** The words a report's issue carries so a later search can find it: the same problem, and the same component. */
|
|
66
|
+
export function matchKeys(snapshot: Snapshot): { fingerprint: string | null; component: string | null };
|
|
67
|
+
/** Issues that may already report this: the same fingerprint, and other open issues about the same component. */
|
|
68
|
+
export function findSimilar(token: string, snapshot: Snapshot, options?: FetchOptions): Promise<{ duplicates: IssueSummary[]; related: IssueSummary[] }>;
|
|
69
|
+
/** The comment a snapshot becomes when it is added to an existing issue. */
|
|
70
|
+
export function commentFromSnapshot(snapshot: Snapshot): string;
|
|
71
|
+
/** GitHub's own new-issue form, pre-filled with the report: for reporting without signing in. At most about 8 kB. */
|
|
72
|
+
export function newIssueUrl(snapshot: Snapshot): string;
|