@unbase-app/cli 0.0.0-stage → 0.2.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/lib/site.mjs ADDED
@@ -0,0 +1,153 @@
1
+ // ============================================================================
2
+ // The site on disk, read the way Unbase reads a commit: a list of paths
3
+ // relative to the repository and a read(path). Unbase's readers
4
+ // (lib/readers.mjs) take exactly that, so doctor runs them on the working
5
+ // tree as Unbase runs them on the branch.
6
+ // ============================================================================
7
+
8
+ import { execFileSync } from "node:child_process";
9
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
10
+ import { join, relative, resolve, sep } from "node:path";
11
+ import { CouldNotRun } from "./errors.mjs";
12
+ import { detect } from "./readers.mjs";
13
+
14
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", ".astro", ".vercel", ".netlify", ".output", ".next", ".turbo", ".cache", ".unbase"]);
15
+
16
+ const posix = (p) => p.split(sep).join("/");
17
+
18
+ function git(cwd, args) {
19
+ try {
20
+ return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+
26
+ /** Every file a commit would hold: git's view (tracked and new, not ignored), or a walk outside git. */
27
+ function listFiles(root) {
28
+ const out = git(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]);
29
+ if (out !== null) return [...new Set(out.split("\0").filter(Boolean))].filter((p) => existsSync(join(root, p))).sort();
30
+ const files = [];
31
+ const walk = (dir) => {
32
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
33
+ if (e.isDirectory()) {
34
+ if (!SKIP_DIRS.has(e.name)) walk(join(dir, e.name));
35
+ } else if (e.isFile()) files.push(posix(relative(root, join(dir, e.name))));
36
+ }
37
+ };
38
+ walk(root);
39
+ return files.sort();
40
+ }
41
+
42
+ /**
43
+ * The site at `dir`: its folder, the repository it is in, Unbase's detection of it, and the
44
+ * module for its framework (frameworks/index.mjs). Throws CouldNotRun when there is no
45
+ * package.json, or no module for the framework detection names.
46
+ */
47
+ export async function openSite(dir) {
48
+ const root = resolve(dir);
49
+ if (!existsSync(join(root, "package.json"))) throw new CouldNotRun("no_site", `No package.json in ${root}: run this in the site's folder, or pass --dir.`);
50
+ let pkg;
51
+ try {
52
+ pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
53
+ } catch {
54
+ throw new CouldNotRun("package_json", "package.json is not valid JSON.", { file: "package.json" });
55
+ }
56
+ const top = git(root, ["rev-parse", "--show-toplevel"])?.trim();
57
+ const repoRoot = top ? resolve(top) : root;
58
+ const appPath = posix(relative(repoRoot, root));
59
+ const site = {
60
+ root,
61
+ repoRoot,
62
+ appPath,
63
+ git: !!top,
64
+ pkg,
65
+ /** Paths relative to the repository root (what Unbase's RepoReader holds). */
66
+ paths: listFiles(repoRoot),
67
+ /** A file of the site, relative to its folder, or null. */
68
+ text(p) {
69
+ try {
70
+ return readFileSync(join(root, p), "utf8");
71
+ } catch {
72
+ return null;
73
+ }
74
+ },
75
+ exists: (p) => existsSync(join(root, p)),
76
+ /** Unbase's RepoReader over the repository. */
77
+ get repo() {
78
+ return { paths: this.paths, read: async (p) => readFileOrNull(join(repoRoot, p)) };
79
+ },
80
+ /** The site's own files, relative to its folder. */
81
+ get appPaths() {
82
+ if (!appPath) return this.paths;
83
+ return this.paths.filter((p) => p.startsWith(`${appPath}/`)).map((p) => p.slice(appPath.length + 1));
84
+ },
85
+ configFile: null,
86
+ detection: null,
87
+ /** The framework's module: its config files, packages, steps and checks. */
88
+ framework: null,
89
+ };
90
+ site.detection = await detect(site.repo, "working tree", false, appPath);
91
+ // Loaded here, not imported above: a framework's module imports this one.
92
+ const { FRAMEWORKS, frameworkOf } = await import("./frameworks/index.mjs");
93
+ site.framework = frameworkOf(site.detection.framework?.id);
94
+ if (!site.framework) {
95
+ const supported = FRAMEWORKS.map((f) => f.name).join(", ");
96
+ throw new CouldNotRun(
97
+ "framework_unsupported",
98
+ site.detection.framework
99
+ ? `Unbase's CLI has no package for ${site.detection.framework.name} yet; it supports ${supported}.`
100
+ : `Unbase's CLI finds no framework it knows in package.json; it supports ${supported}.`,
101
+ { file: "package.json" },
102
+ );
103
+ }
104
+ site.configFile = configFileOf(site);
105
+ return site;
106
+ }
107
+
108
+ /** The framework's config file the site has: the first of its names that is there, or null. */
109
+ const configFileOf = (site) => site.framework.configFiles.find((f) => existsSync(join(site.root, f))) ?? null;
110
+
111
+ export function readFileOrNull(file) {
112
+ try {
113
+ return statSync(file).isFile() ? readFileSync(file, "utf8") : null;
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ /** Re-read the file list (after a build wrote schemas, or init changed files). */
120
+ export async function refresh(site) {
121
+ site.paths = listFiles(site.repoRoot);
122
+ site.configFile = configFileOf(site);
123
+ try {
124
+ site.pkg = JSON.parse(readFileSync(join(site.root, "package.json"), "utf8"));
125
+ } catch {}
126
+ site.detection = await detect(site.repo, "working tree", false, site.appPath);
127
+ return site;
128
+ }
129
+
130
+ /** Whether git says files under `path` differ from what is committed (new, changed or deleted). */
131
+ export function uncommitted(site, path) {
132
+ if (!site.git) return [];
133
+ const out = git(site.root, ["status", "--porcelain", "--untracked-files=all", "--", path]);
134
+ return out ? out.split("\n").filter(Boolean).map((l) => l.slice(3)) : [];
135
+ }
136
+
137
+ /** The site's dependencies, both kinds. */
138
+ export const depsOf = (pkg) => ({ ...(pkg.devDependencies ?? {}), ...(pkg.dependencies ?? {}) });
139
+
140
+ /** The version of `name` installed in the site's node_modules, or null. */
141
+ export function installedVersion(site, name) {
142
+ try {
143
+ return JSON.parse(readFileSync(join(site.root, "node_modules", name, "package.json"), "utf8")).version ?? null;
144
+ } catch {
145
+ // Not installed here (a fresh checkout, Unbase's sandbox): npm's lockfile says which version a
146
+ // spec resolved to, also one that is not a version (a vendored `file:vendor/….tgz`).
147
+ try {
148
+ return JSON.parse(readFileSync(join(site.root, "package-lock.json"), "utf8")).packages?.[`node_modules/${name}`]?.version ?? null;
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+ }
@@ -0,0 +1,136 @@
1
+ // ============================================================================
2
+ // unbase uninstall — init backwards. Refuses while unbase.pages.json holds a
3
+ // draft (without the kit a draft is built and goes live). Then removes the
4
+ // packages, what the framework's module names (on Astro: their lines in
5
+ // astro.config, comment-modus.json, unbase.pages.json,
6
+ // src/content/.schemas/) and the pointer line init may have written, and
7
+ // compares every built page's HTML before and after: the packages may change
8
+ // how a site is edited and built, never how it renders.
9
+ // ============================================================================
10
+
11
+ import { rmSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { buildSite, tailOf } from "./build.mjs";
14
+ import { comparePages } from "./compare.mjs";
15
+ import { CouldNotRun, FAILED, PASSED } from "./errors.mjs";
16
+ import { POINTER_BEFORE, POINTER_FILES, POINTER_LINE } from "./init.mjs";
17
+ import { dropDependencies, lockfileOf, packageManagerOf, removePackages } from "./pm.mjs";
18
+ import { core } from "./readers.mjs";
19
+ import { depsOf, openSite } from "./site.mjs";
20
+
21
+ export async function uninstall(flags, io) {
22
+ const site = await openSite(flags.dir ?? process.cwd());
23
+
24
+ // Drafts first: they are what an uninstall would publish.
25
+ const pageFile = core.parsePageFile(site.text(core.PAGE_FILE));
26
+ if (!pageFile.ok) throw new CouldNotRun("page_file", `${core.PAGE_FILE} is invalid (${pageFile.error}); fix it or publish the drafts in Unbase first.`, { file: core.PAGE_FILE });
27
+ const drafts = core.draftPaths(pageFile);
28
+ if (drafts.length) {
29
+ return {
30
+ command: "uninstall",
31
+ ok: false,
32
+ exitCode: FAILED,
33
+ site: site.root,
34
+ refused: "drafts",
35
+ drafts,
36
+ message: `${core.PAGE_FILE} holds ${drafts.length} draft page(s). Without the kit they would be built and go live: publish or delete each in Unbase first.`,
37
+ };
38
+ }
39
+
40
+ if (!flags.yes) {
41
+ if (!io.interactive) throw new CouldNotRun("choice_missing", "Pass --yes to remove Unbase from this site: there is no terminal to ask in.");
42
+ if (!(await io.ask("Remove Unbase's packages and files from this site?", false))) throw new CouldNotRun("cancelled", "Nothing was changed.");
43
+ }
44
+
45
+ // Plan everything before changing anything: a config that cannot be edited stops here.
46
+ const plan = site.framework.uninstall(site);
47
+ const deps = depsOf(site.pkg);
48
+ const packages = plan.packages.filter((n) => deps[n]);
49
+ const pm = packages.length && !flags["no-install"] ? packageManagerOf(site) : null;
50
+ const paths = plan.remove.filter((p) => site.exists(p));
51
+ /** init's pointer line, under the CLI's name now or before K5. */
52
+ const isPointer = (l) => l.trim() === POINTER_LINE || l.trim() === POINTER_BEFORE;
53
+ const pointers = POINTER_FILES.map((f) => ({ file: f, text: site.text(f) })).filter((p) => p.text?.split("\n").some(isPointer));
54
+
55
+ if (!plan.files.length && !packages.length && !paths.length && !pointers.length)
56
+ return { command: "uninstall", ok: true, exitCode: PASSED, site: site.root, packages: [], files: [], comparison: null, message: "Nothing to remove: Unbase is not in this site." };
57
+
58
+ let before = null;
59
+ if (!flags["no-build"]) {
60
+ io.progress("Building the site before (production)…");
61
+ before = buildSite(site, { label: "before" });
62
+ if (!before.ok) {
63
+ before.dispose();
64
+ throw new CouldNotRun("build_failed", `The site does not build before uninstalling, so there is nothing to compare with; nothing was changed.\n${tailOf(before.output)}`);
65
+ }
66
+ }
67
+
68
+ // ── Apply ─────────────────────────────────────────────────────────────────
69
+ const files = [];
70
+ for (const f of plan.files) {
71
+ writeFileSync(join(site.root, f.file), f.text);
72
+ files.push({ file: f.file, action: f.action, changes: f.changes });
73
+ }
74
+ for (const p of paths) {
75
+ rmSync(join(site.root, p), { recursive: true, force: true });
76
+ files.push({ file: p, action: "removed", changes: [] });
77
+ }
78
+ for (const p of pointers) {
79
+ const rest = p.text
80
+ .split("\n")
81
+ .filter((l) => !isPointer(l))
82
+ .join("\n")
83
+ .replace(/\n{3,}/g, "\n\n")
84
+ .replace(/\n+$/, "\n");
85
+ if (!rest.trim()) {
86
+ rmSync(join(site.root, p.file));
87
+ files.push({ file: p.file, action: "removed", changes: [POINTER_LINE] });
88
+ } else {
89
+ writeFileSync(join(site.root, p.file), rest);
90
+ files.push({ file: p.file, action: "changed", changes: [`removed: ${POINTER_LINE}`] });
91
+ }
92
+ }
93
+ if (packages.length) {
94
+ if (pm) {
95
+ io.progress(`Removing ${packages.join(", ")} with ${pm}…`);
96
+ removePackages(site, pm, packages, { quiet: io.json });
97
+ } else dropDependencies(site, packages);
98
+ files.push({ file: "package.json", action: "changed", changes: packages.map((n) => `removed ${n}`) });
99
+ if (pm) files.push({ file: lockfileOf(site, pm), action: "changed", changes: [`${pm} removed ${packages.length} package(s)`] });
100
+ }
101
+
102
+ let comparison = null;
103
+ if (before) {
104
+ io.progress("Building the site after…");
105
+ const after = buildSite(site, { label: "after" });
106
+ if (!after.ok) {
107
+ before.dispose();
108
+ after.dispose();
109
+ return { command: "uninstall", ok: false, exitCode: FAILED, site: site.root, packages, files, built: false, message: `The site does not build after uninstalling:\n${tailOf(after.output)}` };
110
+ }
111
+ const pre = site.framework.normalise;
112
+ comparison = comparePages(before, after, null, pre);
113
+ comparison.secondBuild = false;
114
+ if (comparison.diffs.length) {
115
+ // Tell a change from build noise (an id made at random on every render): build the after state once more.
116
+ io.progress(`${comparison.diffs.length} page(s) differ; building again to tell changes from what differs between any two builds…`);
117
+ const again = buildSite(site, { label: "again" });
118
+ if (again.ok) comparison = { ...comparePages(before, after, again, pre), secondBuild: true };
119
+ again.dispose();
120
+ }
121
+ before.dispose();
122
+ after.dispose();
123
+ }
124
+ const differs = !!comparison?.diffs.length;
125
+ return {
126
+ command: "uninstall",
127
+ ok: !differs,
128
+ exitCode: differs ? FAILED : PASSED,
129
+ site: site.root,
130
+ packages,
131
+ files,
132
+ comparison: comparison ? { pages: comparison.pages, differences: comparison.diffs, secondBuild: comparison.secondBuild } : null,
133
+ message: !comparison ? "Removed. Not compared (--no-build)." : differs ? `${comparison.diffs.length} of ${comparison.pages} built pages differ.` : `No differences in the built pages (${comparison.pages} compared).`,
134
+ };
135
+ }
136
+
@@ -0,0 +1,71 @@
1
+ // ============================================================================
2
+ // What `unbase init` installs, pinned. One place: bumping a package to a new
3
+ // release is one line here (and the README's table).
4
+ // ============================================================================
5
+
6
+ import { readFileSync } from "node:fs";
7
+
8
+ const own = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
9
+
10
+ /** The CLI itself, installed as a devDependency so its AGENTS.md and `unbase doctor` are pinned by the lockfile. */
11
+ export const SELF = { name: own.name, version: own.version, dev: true };
12
+
13
+ /**
14
+ * Unbase in an Astro site, one package (K5): comment mode and the draft-pages kit below, at the
15
+ * versions its own package.json pins (kit/astro; a test holds the two equal).
16
+ */
17
+ export const ASTRO = { name: "@unbase-app/astro", version: "0.1.0", dev: false };
18
+
19
+ /** Comments on the live site (`?comment`), and the content schemas, page list and markers it writes. Inside ASTRO. */
20
+ export const COMMENT_MODUS = { name: "@jens4m/comment-modus", version: "1.9.0", dev: false };
21
+
22
+ /** Keeps draft pages out of production builds. Inside ASTRO. */
23
+ export const PAGES = { name: "@unbase-app/pages", version: "0.3.0", dev: false };
24
+
25
+ /**
26
+ * The names before K5 (03-11): a site installed then has the pair (comment-modus and the kit) and
27
+ * the CLI under these. init replaces them; doctor and uninstall know them.
28
+ */
29
+ export const BEFORE = { pages: "@jens4m/unbase-pages", cli: "@jens4m/unbase" };
30
+
31
+ /** Vite + React Router: the draft-pages kit and comment mode's loader, in one Vite plugin (kit/vite). A build tool, so a devDependency, beside vite. */
32
+ export const VITE = { name: "@unbase-app/vite", version: "0.1.0", dev: true };
33
+
34
+ /** Next.js: draft pages kept out of production builds, and comments on the live site (`withUnbase`). */
35
+ export const NEXT = { name: "@unbase-app/next", version: "0.1.0", dev: false };
36
+
37
+ /** Where comment mode's layer is served from: only fetched by a visitor who opens `?comment` (ADR-0012's one exception). */
38
+ export const LAYER_URL = "https://layer.unbase.app/v1/loader.js";
39
+
40
+ /**
41
+ * A build failure doctor can explain: comment-modus up to 1.8.0 cannot build its /version.json
42
+ * route when it is in node_modules but not listed in package.json (npm install --no-save, or
43
+ * through another package). Listing it fixes it; 1.8.1 builds either way.
44
+ */
45
+ export const UNLISTED_BUILD_FAILURE = { package: COMMENT_MODUS.name, upTo: "1.8.0", fixedIn: "1.8.1", output: /Invalid URL/ };
46
+
47
+ /**
48
+ * The first comment-modus that knows `componentMarker: "preview"`: data-c in the dev server and
49
+ * previews, none in a production build (plan-packages *Open* 5). An older one ignores the value
50
+ * and marks every build. init does not write the option, so the pin above stays where it is.
51
+ */
52
+ export const MARKERS_PREVIEW = { package: COMMENT_MODUS.name, since: "1.9.0" };
53
+
54
+ /** "1.8.1" from a version or a range ("^1.7.0" → 1.7.0); null for a tag, a URL or a file. */
55
+ export function versionIn(spec) {
56
+ const m = /^[\^~=v\s]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(String(spec ?? "").trim());
57
+ return m ? m[1] : null;
58
+ }
59
+
60
+ /** -1, 0 or 1: a before b, the same, after. A pre-release comes before its release. */
61
+ export function compareVersions(a, b) {
62
+ const [ca, pa = ""] = String(a).split("-", 2);
63
+ const [cb, pb = ""] = String(b).split("-", 2);
64
+ const na = ca.split(".").map(Number);
65
+ const nb = cb.split(".").map(Number);
66
+ for (let i = 0; i < 3; i++) if ((na[i] ?? 0) !== (nb[i] ?? 0)) return (na[i] ?? 0) < (nb[i] ?? 0) ? -1 : 1;
67
+ if (pa === pb) return 0;
68
+ if (!pa) return 1;
69
+ if (!pb) return -1;
70
+ return pa < pb ? -1 : 1;
71
+ }
@@ -0,0 +1,294 @@
1
+ // ============================================================================
2
+ // Editing vite.config safely, as config-edit.mjs edits astro.config: parsed
3
+ // (Babel, with TypeScript for .ts), the places found in the syntax tree, the
4
+ // change a splice at those offsets, the result parsed and checked again.
5
+ //
6
+ // The shapes a Vite app's config has, Lovable's among them:
7
+ //
8
+ // export default defineConfig({ plugins: [react()] })
9
+ // export default defineConfig(({ mode }) => ({ plugins: [react(), mode === "development" && componentTagger()].filter(Boolean) }))
10
+ // export default defineConfig(({ mode }) => { …; return { plugins: […] }; })
11
+ // export default { plugins: […] } (or through a const)
12
+ //
13
+ // init adds `import { unbase } from "@unbase-app/vite"` and `unbase()` last
14
+ // in `plugins` (`unbase({ comments: false })` without comments). A config
15
+ // with the draft-pages kit's own plugin (`unbasePages()` from
16
+ // @jens4m/unbase-pages/vite) has it replaced in place: @unbase-app/vite
17
+ // carries the kit, and two of them in one build would each remove the same
18
+ // routes. Anything the tree does not make certain stops with the file named.
19
+ // ============================================================================
20
+
21
+ import { parse } from "@babel/parser";
22
+ import { applySplices, indentAt, isComma, keyName, lineRange, multiline, references, styleOf, tokenAfter, unwrap } from "./config-edit.mjs";
23
+ import { CouldNotRun } from "./errors.mjs";
24
+ import { BEFORE, PAGES, VITE } from "./versions.mjs";
25
+
26
+ /** What init imports, and the kit's own Vite plugin it replaces (under its name since K5, and before). */
27
+ export const VITE_SOURCES = { unbase: VITE.name, kit: `${PAGES.name}/vite` };
28
+ const OLD_KIT = new Set([`${PAGES.name}/vite`, PAGES.name, `${BEFORE.pages}/vite`, BEFORE.pages]);
29
+ const NAME = "unbase";
30
+ /** The names a call of ours may go by, by what the module exports: the plugin, and its two halves. */
31
+ const ENTRIES = { unbase: ["default", "unbase", "unbaseComments"], kit: ["default", "unbasePages"] };
32
+ /** The comment line above unbase() in a multi-line `plugins`. */
33
+ const LINE = (comments) =>
34
+ comments
35
+ ? "// Unbase: draft pages kept out of production builds; comments on the site with ?comment once comment-modus.json names the project."
36
+ : "// Unbase: draft pages kept out of production builds.";
37
+
38
+ const unsafe = (file, why) =>
39
+ new CouldNotRun("config_unsafe", `${file} cannot be edited safely: ${why}. Make the change by hand (step 1 of agents/vite-react.md in @unbase-app/cli), then run the command again.`, { file });
40
+
41
+ function parseConfig(code, file) {
42
+ if (/\.cjs$/.test(file)) throw unsafe(file, "it is CommonJS, and the packages are ES modules");
43
+ try {
44
+ return parse(code, { sourceType: "module", plugins: /\.(m|c)?ts$/.test(file) ? ["typescript"] : [], tokens: true, errorRecovery: false });
45
+ } catch (e) {
46
+ throw unsafe(file, `it does not parse (${e.message})`);
47
+ }
48
+ }
49
+
50
+ /** The object a function hands back: an arrow's object, or a block's one top-level `return { … }`. */
51
+ function returned(fn) {
52
+ const body = unwrap(fn.body);
53
+ if (body?.type === "ObjectExpression") return body;
54
+ if (body?.type !== "BlockStatement") return null;
55
+ const returns = body.body.filter((s) => s.type === "ReturnStatement");
56
+ return returns.length === 1 ? unwrap(returns[0].argument) : null;
57
+ }
58
+
59
+ /** The object literal the config hands Vite. */
60
+ function configObject(ast, file) {
61
+ const body = ast.program.body;
62
+ const exp = body.find((n) => n.type === "ExportDefaultDeclaration");
63
+ if (!exp) throw unsafe(file, "it has no `export default`");
64
+ const constNamed = (name) => {
65
+ for (const n of body) {
66
+ const decl = n.type === "ExportNamedDeclaration" ? n.declaration : n;
67
+ if (decl?.type !== "VariableDeclaration" || decl.kind !== "const") continue;
68
+ const d = decl.declarations.find((v) => v.id.type === "Identifier" && v.id.name === name);
69
+ if (d?.init) return d.init;
70
+ }
71
+ return null;
72
+ };
73
+ let node = unwrap(exp.declaration);
74
+ for (let step = 0; step < 4 && node; step++) {
75
+ if (node.type === "ObjectExpression") return node;
76
+ if (node.type === "Identifier") node = unwrap(constNamed(node.name));
77
+ else if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "defineConfig" && node.arguments.length === 1) node = unwrap(node.arguments[0]);
78
+ else if ((node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") && !node.async) node = returned(node);
79
+ else break;
80
+ }
81
+ throw unsafe(file, "its `export default` is not `defineConfig(…)` with an object, a function returning one, or an object literal");
82
+ }
83
+
84
+ /** The imports of our modules: their local names, by what they import. */
85
+ function importsOf(ast) {
86
+ const found = { unbase: [], kit: [], nodes: [], all: new Set() };
87
+ for (const n of ast.program.body) {
88
+ if (n.type !== "ImportDeclaration") continue;
89
+ for (const s of n.specifiers) found.all.add(s.local.name);
90
+ const src = n.source.value;
91
+ const kind = src === VITE_SOURCES.unbase ? "unbase" : OLD_KIT.has(src) ? "kit" : null;
92
+ if (!kind) continue;
93
+ found.nodes.push({ kind, node: n });
94
+ for (const s of n.specifiers) {
95
+ const imported = s.type === "ImportDefaultSpecifier" ? "default" : s.type === "ImportSpecifier" ? (s.imported.name ?? s.imported.value) : "*";
96
+ if (ENTRIES[kind].includes(imported)) found[kind].push(s.local.name);
97
+ }
98
+ }
99
+ return found;
100
+ }
101
+
102
+ /** The call an element of `plugins` makes, possibly behind `x &&` or `x ?`; null for anything else. */
103
+ function callOf(el) {
104
+ let e = unwrap(el);
105
+ if (e?.type === "LogicalExpression" && e.operator === "&&") e = unwrap(e.right);
106
+ else if (e?.type === "ConditionalExpression") e = unwrap(e.consequent);
107
+ return e?.type === "CallExpression" && e.callee.type === "Identifier" ? e : null;
108
+ }
109
+
110
+ /** `plugins: [ … ]`, or Lovable's `plugins: [ … ].filter(Boolean)`: the array literal; null for any other shape. */
111
+ function pluginsArray(prop) {
112
+ const v = unwrap(prop.value);
113
+ if (v.type === "ArrayExpression") return v;
114
+ if (v.type === "CallExpression" && v.callee.type === "MemberExpression" && unwrap(v.callee.object).type === "ArrayExpression") return unwrap(v.callee.object);
115
+ return null;
116
+ }
117
+
118
+ /** unbase()'s literal options: `comments: false`, a literal `project`; null when they cannot be read. */
119
+ function optionsOf(call) {
120
+ if (!call.arguments.length) return { comments: true, project: null, only: null };
121
+ const o = unwrap(call.arguments[0]);
122
+ if (o?.type !== "ObjectExpression" || o.properties.some((p) => p.type !== "ObjectProperty" || p.computed)) return null;
123
+ const prop = (name) => o.properties.find((p) => keyName(p) === name);
124
+ const c = prop("comments") ? unwrap(prop("comments").value) : null;
125
+ const p = prop("project") ? unwrap(prop("project").value) : null;
126
+ return {
127
+ comments: !(c?.type === "BooleanLiteral" && c.value === false),
128
+ project: p?.type === "StringLiteral" ? p.value : null,
129
+ /** The one property there is, when there is one: init turns `{ comments: false }` into nothing. */
130
+ only: o.properties.length === 1 ? keyName(o.properties[0]) : null,
131
+ };
132
+ }
133
+
134
+ /** What a vite.config holds of Unbase, read from its tree: for doctor, init and uninstall. */
135
+ export function inspectViteConfig(code, file) {
136
+ const ast = parseConfig(code, file);
137
+ const obj = configObject(ast, file);
138
+ const imports = importsOf(ast);
139
+ const prop = obj.properties.find((p) => p.type === "ObjectProperty" && !p.computed && keyName(p) === "plugins");
140
+ const spread = obj.properties.some((p) => p.type === "SpreadElement");
141
+ const array = prop ? pluginsArray(prop) : null;
142
+ if (prop && !array) throw unsafe(file, "`plugins` is not an array literal");
143
+ const entries = (array?.elements ?? []).map((el, index) => {
144
+ const call = el ? callOf(el) : null;
145
+ const kind = call && imports.unbase.includes(call.callee.name) ? "unbase" : call && imports.kit.includes(call.callee.name) ? "kit" : null;
146
+ return { index, el, call, kind };
147
+ });
148
+ const ours = entries.find((e) => e.kind === "unbase");
149
+ return {
150
+ ast,
151
+ obj,
152
+ prop,
153
+ array,
154
+ spread,
155
+ imports,
156
+ entries,
157
+ has: { unbase: !!ours, kit: entries.some((e) => e.kind === "kit") },
158
+ /** unbase()'s literal options; null without unbase(), or when they are not literal. */
159
+ options: ours ? optionsOf(ours.call) : null,
160
+ };
161
+ }
162
+
163
+ const verify = (code, file) => {
164
+ try {
165
+ return inspectViteConfig(code, file);
166
+ } catch (e) {
167
+ throw unsafe(file, `the edited config would not parse (${e.message}); nothing was written`);
168
+ }
169
+ };
170
+
171
+ /**
172
+ * The config with unbase() in `plugins` and its import, the old kit's plugin replaced by it, and
173
+ * with `comments` an unbase({ comments: false }) turned on. The same code and no changes when
174
+ * nothing is missing.
175
+ */
176
+ export function addToViteConfig(code, file, { comments }) {
177
+ const info = inspectViteConfig(code, file);
178
+ const style = styleOf(code, info.ast);
179
+ const q = (s) => `${style.quote}${s}${style.quote}`;
180
+ const call = comments ? `${NAME}()` : `${NAME}({ comments: false })`;
181
+ const splices = [];
182
+ const changes = [];
183
+
184
+ if (info.has.unbase) {
185
+ // Turned on again (init --comments): `{ comments: false }` goes, the rest of the call stays.
186
+ const o = info.options;
187
+ if (!comments || !o || o.comments) return { code, changes: [] };
188
+ const ours = info.entries.find((e) => e.kind === "unbase").call;
189
+ if (o.only !== "comments") throw unsafe(file, "unbase() has more options than `comments: false`; take that one out by hand");
190
+ splices.push({ start: ours.arguments[0].start, end: ours.arguments[0].end, text: "" });
191
+ changes.push(`plugins: ${NAME}({ comments: false }) → ${NAME}()`);
192
+ } else {
193
+ if (info.imports.unbase.length) throw unsafe(file, `it imports ${VITE_SOURCES.unbase} but does not call it in plugins`);
194
+ if (info.imports.all.has(NAME) || references(info.ast.program, new Set([NAME])).length) throw unsafe(file, `it already uses the name ${NAME}`);
195
+ if (!info.prop && info.spread) throw unsafe(file, "its config spreads another object, which may hold `plugins`");
196
+ const kitEntries = info.entries.filter((e) => e.kind === "kit");
197
+ if (info.imports.kit.length && !kitEntries.length) throw unsafe(file, `it imports the draft-pages kit but does not call it in plugins`);
198
+ if (kitEntries.length > 1) throw unsafe(file, `it calls the draft-pages kit's plugin more than once`);
199
+
200
+ // The import: after the last one, or at the top; the old kit's import goes.
201
+ const kitImports = info.imports.nodes.filter((n) => n.kind === "kit");
202
+ const line = `import { ${NAME} } from ${q(VITE_SOURCES.unbase)}${style.semi ? ";" : ""}`;
203
+ const lastImport = info.ast.program.body.filter((n) => n.type === "ImportDeclaration").pop();
204
+ if (lastImport) {
205
+ const nl = code.indexOf("\n", lastImport.end);
206
+ const eol = nl === -1 ? code.length : nl;
207
+ const at = /^[ \t]*(\/\/[^\n]*)?$/.test(code.slice(lastImport.end, eol)) ? eol : lastImport.end;
208
+ splices.push({ start: at, end: at, text: `\n${line}` });
209
+ } else splices.push({ start: 0, end: 0, text: `${line}\n\n` });
210
+ for (const { node } of kitImports) splices.push(lineRange(code, node.start, node.end) ?? { start: node.start, end: node.end });
211
+ changes.push(`import { ${NAME} } from "${VITE_SOURCES.unbase}"`, ...kitImports.map(({ node }) => `removed import from "${node.source.value}"`));
212
+
213
+ const { obj, prop, array } = info;
214
+ if (kitEntries.length) {
215
+ // In the old kit's place: unbase() is it, and comment mode with it.
216
+ const kit = kitEntries[0].call;
217
+ const names = new Set(info.imports.kit);
218
+ const elsewhere = references(info.ast.program, names).filter((n) => n.start < kit.start || n.end > kit.end);
219
+ if (elsewhere.length) throw unsafe(file, `it uses ${elsewhere[0].name} (line ${elsewhere[0].loc.start.line}) outside plugins`);
220
+ splices.push({ start: kit.start, end: kit.end, text: call });
221
+ changes.push(`plugins: ${kit.callee.name}() → ${call}`);
222
+ } else if (!prop) {
223
+ const props = obj.properties;
224
+ const pIndent = props.length ? indentAt(code, props[0].start) : indentAt(code, obj.start) + style.unit;
225
+ const block = `plugins: [${call}]`;
226
+ if (!props.length) splices.push({ start: obj.start, end: obj.end, text: `{\n${pIndent}${block},\n${indentAt(code, obj.start)}}` });
227
+ else {
228
+ const last = props[props.length - 1];
229
+ const comma = tokenAfter(info.ast, last.end);
230
+ const multi = multiline(code, obj.start, obj.end);
231
+ if (isComma(comma)) splices.push({ start: comma.end, end: comma.end, text: `${multi ? `\n${pIndent}` : " "}${block},` });
232
+ else splices.push({ start: last.end, end: last.end, text: `,${multi ? `\n${pIndent}` : " "}${block}` });
233
+ }
234
+ changes.push(`plugins: [${call}]`);
235
+ } else {
236
+ const els = array.elements;
237
+ const last = els[els.length - 1];
238
+ if (els.length && !last) throw unsafe(file, "`plugins` ends with a hole");
239
+ if (!els.length) splices.push({ start: array.start, end: array.end, text: `[${call}]` });
240
+ else if (multiline(code, array.start, array.end)) {
241
+ const eIndent = indentAt(code, els[0].start);
242
+ const comma = tokenAfter(info.ast, last.end);
243
+ if (isComma(comma)) splices.push({ start: comma.end, end: comma.end, text: `\n${eIndent}${LINE(comments)}\n${eIndent}${call},` });
244
+ else splices.push({ start: last.end, end: last.end, text: `,\n${eIndent}${LINE(comments)}\n${eIndent}${call}` });
245
+ } else splices.push({ start: last.end, end: last.end, text: `, ${call}` });
246
+ changes.push(`plugins: ${call}`);
247
+ }
248
+ }
249
+
250
+ const next = applySplices(code, splices);
251
+ const after = verify(next, file);
252
+ if (!after.has.unbase || after.has.kit || !after.options || after.options.comments !== comments) throw unsafe(file, "the edited config did not come out as expected");
253
+ return { code: next, changes };
254
+ }
255
+
256
+ /** The config without unbase() and the old kit's plugin, and their imports. Stops when a name they bring is used elsewhere. */
257
+ export function removeFromViteConfig(code, file) {
258
+ const info = inspectViteConfig(code, file);
259
+ const ours = info.entries.filter((e) => e.kind);
260
+ if (!ours.length && !info.imports.nodes.length) return { code, changes: [] };
261
+ const splices = [];
262
+ const els = info.array?.elements ?? [];
263
+ for (const e of ours) {
264
+ const el = e.el;
265
+ const prevEnd = e.index > 0 ? els[e.index - 1].end : info.array.start + 1;
266
+ const lead = (el.leadingComments ?? []).filter((c) => c.start >= prevEnd && code.slice(prevEnd, c.start).includes("\n"));
267
+ const start = Math.min(el.start, ...lead.map((c) => c.start));
268
+ const comma = tokenAfter(info.ast, el.end);
269
+ const whole = lineRange(code, start, isComma(comma) ? comma.end : el.end);
270
+ if (whole) splices.push(whole);
271
+ else if (isComma(comma)) splices.push({ start, end: comma.end + /^\s*/.exec(code.slice(comma.end))[0].length });
272
+ else splices.push({ start, end: el.end });
273
+ }
274
+ const names = new Set(info.imports.nodes.flatMap((n) => n.node.specifiers.map((s) => s.local.name)));
275
+ const removed = (n) => splices.some((s) => n.start >= s.start && n.end <= s.end);
276
+ // The last entry going without a comma after it: the entry before it loses the comma init gave it.
277
+ const lastEl = els[els.length - 1];
278
+ const kept = els.filter((el, i) => el && !ours.some((e) => e.index === i));
279
+ if (lastEl && ours.some((e) => e.el === lastEl) && !isComma(tokenAfter(info.ast, lastEl.end)) && kept.length) {
280
+ const comma = tokenAfter(info.ast, kept[kept.length - 1].end);
281
+ const oneLine = !multiline(code, info.array.start, info.array.end);
282
+ if (isComma(comma) && !removed(comma)) splices.push({ start: comma.start, end: oneLine ? comma.end + /^\s*/.exec(code.slice(comma.end))[0].length : comma.end });
283
+ }
284
+ const elsewhere = references(info.ast.program, names).filter((n) => !removed(n));
285
+ if (elsewhere.length) throw unsafe(file, `it uses ${elsewhere[0].name} (line ${elsewhere[0].loc.start.line}) outside plugins; remove that use by hand`);
286
+ for (const { node } of info.imports.nodes) splices.push(lineRange(code, node.start, node.end) ?? { start: node.start, end: node.end });
287
+ const next = applySplices(code, splices);
288
+ const after = verify(next, file);
289
+ if (after.has.unbase || after.has.kit || after.imports.nodes.length) throw unsafe(file, "the edited config did not come out as expected");
290
+ return {
291
+ code: next,
292
+ changes: [...info.imports.nodes.map(({ node }) => `removed import from "${node.source.value}"`), ...ours.map((e) => `removed plugins: ${e.call.callee.name}(…)`)],
293
+ };
294
+ }