@unbase-app/cli 0.0.0-stage → 0.3.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.
@@ -0,0 +1,329 @@
1
+ // ============================================================================
2
+ // Vite + React (React Router as a library: what Lovable makes): what the CLI
3
+ // does that is this framework's (frameworks/index.mjs has the shape). One
4
+ // package, @unbase-app/vite (kit/vite): the draft-pages kit and comment
5
+ // mode's loader in one plugin. init adds it, its line in vite.config
6
+ // (vite-config.mjs, through the syntax tree) and comment-modus.json;
7
+ // uninstall takes them out with unbase.pages.json; doctor reads four
8
+ // features with Unbase's own readers (lib/readers.mjs: detect, read_settings,
9
+ // list_pages, the kit's core and the CSP reader) on the working tree and one
10
+ // production build. The steps init leaves: agents/vite-react.md.
11
+ //
12
+ // React Router's framework mode (@react-router/dev, detection's
13
+ // "react-router") is not this: it renders its own document and reads its
14
+ // routes from app/routes.ts, neither of which the plugin or the readers read.
15
+ // ============================================================================
16
+
17
+ import { readFileSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { analyticsFeature } from "../analytics.mjs";
20
+ import { tailOf } from "../build.mjs";
21
+ import { hasOurScript } from "../compare.mjs";
22
+ import { CouldNotRun } from "../errors.mjs";
23
+ import { check, featureState } from "../feature.mjs";
24
+ import { core, readSettings, registryFiles, registryOf } from "../readers.mjs";
25
+ import { depsOf, installedVersion } from "../site.mjs";
26
+ import { addToViteConfig, inspectViteConfig, removeFromViteConfig } from "../vite-config.mjs";
27
+ import { BEFORE, PAGES, SELF, VITE } from "../versions.mjs";
28
+
29
+ const AGENTS = "agents/vite-react.md";
30
+ export const LINK_FILE = "comment-modus.json";
31
+ const STEPS = {
32
+ install: `${AGENTS} step 1: Install`,
33
+ settings: `${AGENTS} step 2: Site settings`,
34
+ drafts: `${AGENTS} step 3: Draft pages`,
35
+ comments: `${AGENTS} step 4: Comments on the site`,
36
+ analytics: `${AGENTS} step 5: Analytics`,
37
+ };
38
+ /** The settings index.html can hold, as read_settings names them. */
39
+ const SITE_SETTINGS = { name: "<title>", description: "meta description", language: "<html lang>", faviconLight: "icon", faviconDark: "dark icon", socialImage: "og:image" };
40
+
41
+ /** The project comment-modus.json names, or the one unbase() names in the config; null without. */
42
+ export function readLink(site) {
43
+ try {
44
+ const data = JSON.parse(readFileSync(join(site.root, LINK_FILE), "utf8"));
45
+ if (typeof data?.project === "string" && data.project.trim()) return data.project.trim();
46
+ } catch {}
47
+ try {
48
+ return site.configFile ? (inspectViteConfig(site.text(site.configFile), site.configFile).options?.project ?? null) : null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ // ── init ───────────────────────────────────────────────────────────────────
55
+
56
+ /** init's plan for vite.config and comment-modus.json (which links comment mode and analytics alike). */
57
+ function planInit(site, { comments, project, analytics = true }) {
58
+ if (!site.configFile) throw new CouldNotRun("no_config", "No vite.config.(ts|js|mjs|mts) in the site's folder.");
59
+ const config = addToViteConfig(site.text(site.configFile), site.configFile, { comments });
60
+ let link = null;
61
+ if (comments || analytics) {
62
+ const text = site.text(LINK_FILE);
63
+ if (text === null) link = { action: "created", data: { project }, indent: " ", changes: [project ? `project: "${project}"` : "project: null (Unbase fills it in when the site is connected)"] };
64
+ else {
65
+ let data;
66
+ try {
67
+ data = JSON.parse(text);
68
+ } catch {
69
+ throw new CouldNotRun("link_file", `${LINK_FILE} is not valid JSON.`, { file: LINK_FILE });
70
+ }
71
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new CouldNotRun("link_file", `${LINK_FILE} is not a JSON object.`, { file: LINK_FILE });
72
+ const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
73
+ if (project && data.project !== project) link = { action: "changed", data: { ...data, project }, indent, changes: [`project: ${JSON.stringify(data.project ?? null)} → "${project}"`] };
74
+ else if (!("project" in data)) link = { action: "changed", data: { project: null, ...data }, indent, changes: ["project: null"] };
75
+ }
76
+ }
77
+ return [
78
+ ...(config.changes.length ? [{ file: site.configFile, action: "changed", changes: config.changes, text: config.code }] : []),
79
+ ...(link ? [{ file: LINK_FILE, action: link.action, changes: link.changes, text: `${JSON.stringify(link.data, null, link.indent)}\n` }] : []),
80
+ ];
81
+ }
82
+
83
+ // ── The move (K5) ──────────────────────────────────────────────────────────
84
+
85
+ /**
86
+ * What init takes out once @unbase-app/vite is in: the kit's own Vite plugin under either name
87
+ * (unbase() takes its place in the config), unless the planned config still names it, and the CLI
88
+ * under its name before K5.
89
+ */
90
+ function planReplaced(site, planned) {
91
+ const deps = depsOf(site.pkg);
92
+ const config = planned.find((f) => f.file === site.configFile)?.text ?? site.text(site.configFile) ?? "";
93
+ const remove = [PAGES.name, BEFORE.pages].filter((n) => deps[n] !== undefined && !config.includes(n));
94
+ if (deps[BEFORE.cli] !== undefined) remove.push(BEFORE.cli);
95
+ return { remove, keep: [], by: VITE.name };
96
+ }
97
+
98
+ /** unbase()'s `analytics` in the config as it is: false only when it says so literally. */
99
+ function analyticsOption(site) {
100
+ if (!site.configFile) return true;
101
+ try {
102
+ return inspectViteConfig(site.text(site.configFile), site.configFile).options?.analytics !== false;
103
+ } catch {
104
+ return true;
105
+ }
106
+ }
107
+
108
+ /** What of Unbase the site has now, for init's defaults: null without any of it; else whether comment mode is on. */
109
+ function currentOf(site) {
110
+ const deps = depsOf(site.pkg);
111
+ if (![VITE.name, PAGES.name, BEFORE.pages].some((n) => deps[n] !== undefined) || !site.configFile) return null;
112
+ try {
113
+ const config = inspectViteConfig(site.text(site.configFile), site.configFile);
114
+ return { comments: config.has.unbase && config.options?.comments !== false };
115
+ } catch {
116
+ return null;
117
+ }
118
+ }
119
+
120
+ // ── uninstall ──────────────────────────────────────────────────────────────
121
+
122
+ /** uninstall's plan: vite.config without our lines, the packages (the old kit's too), and the files they read. */
123
+ function planUninstall(site) {
124
+ const config = site.configFile ? removeFromViteConfig(site.text(site.configFile), site.configFile) : { code: null, changes: [] };
125
+ return {
126
+ packages: [VITE.name, PAGES.name, BEFORE.pages, SELF.name, BEFORE.cli],
127
+ files: config.changes.length ? [{ file: site.configFile, action: "changed", changes: config.changes, text: config.code }] : [],
128
+ remove: [LINK_FILE, core.PAGE_FILE],
129
+ };
130
+ }
131
+
132
+ // ── doctor ─────────────────────────────────────────────────────────────────
133
+
134
+ function envHas(site, name) {
135
+ if (process.env[name]) return true;
136
+ return [".env", ".env.production", ".env.local", ".env.production.local"].some((f) => new RegExp(`^\\s*(export\\s+)?${name}\\s*=\\s*\\S`, "m").test(site.text(f) ?? ""));
137
+ }
138
+
139
+ /** doctor's three features on a Vite + React site, from the production build doctor made (null: --no-build). */
140
+ async function doctorFeatures(site, { build }) {
141
+ const built = !!build?.ok;
142
+ const deps = depsOf(site.pkg);
143
+ const detection = site.detection;
144
+ const file = site.configFile ?? "vite.config.ts";
145
+ let config = null;
146
+ let configError = null;
147
+ if (site.configFile) {
148
+ try {
149
+ config = inspectViteConfig(site.text(site.configFile), site.configFile);
150
+ } catch (e) {
151
+ if (!(e instanceof CouldNotRun)) throw e;
152
+ configError = e.message;
153
+ }
154
+ }
155
+ const version = installedVersion(site, VITE.name) ?? deps[VITE.name];
156
+ const listed = !!deps[VITE.name];
157
+ const features = [];
158
+
159
+ // ── Visual editing ────────────────────────────────────────────────────────
160
+ {
161
+ const checks = [check("react", "ok", "A Vite + React app: Unbase finds its texts by matching them to where they are written, proven by a probe; nothing to install.")];
162
+ if (!build) checks.push(check("build", "skipped", "Not built (--no-build)."));
163
+ else if (built) checks.push(check("build", "ok", "A production build works."));
164
+ else checks.push(check("build", "missing", "The production build fails, so Unbase cannot start or check the site.", { missing: "a site that builds", file, detail: tailOf(build.output) }));
165
+ const names = detection.settings.map((s) => s.name);
166
+ if (names.length) checks.push(check("settings", "info", `The code reads ${names.length} setting(s) (${names.slice(0, 6).join(", ")}${names.length > 6 ? ", …" : ""}). If the site needs them to start, give them development values in Unbase.`));
167
+ features.push({ id: "visual-editing", name: "Visual editing", state: featureState(checks), checks });
168
+ }
169
+
170
+ // The package, as both other features need it.
171
+ const packageCheck = () =>
172
+ !listed && (installedVersion(site, VITE.name) || config?.has.unbase)
173
+ ? check("listed", "missing", `${VITE.name} is ${installedVersion(site, VITE.name) ? "in node_modules" : "used in the config"} but not listed in package.json.`, { missing: `${VITE.name} in devDependencies, pinned`, file: "package.json", step: STEPS.install })
174
+ : null;
175
+
176
+ // ── Comments on the site ──────────────────────────────────────────────────
177
+ {
178
+ const checks = [];
179
+ const unlisted = packageCheck();
180
+ const off = config?.options && !config.options.comments;
181
+ if (unlisted) checks.push(unlisted);
182
+ else if (!listed || (config && !config.has.unbase)) {
183
+ checks.push(check("package", "info", `Not in the code: \`unbase init --comments\` adds ${VITE.name}. Comments on the canvas in Unbase work without it.`));
184
+ } else if (configError) checks.push(check("config", "missing", configError, { file, step: STEPS.install }));
185
+ else if (off) checks.push(check("config", "info", `${file} calls unbase({ comments: false }): comments on the site are left out. \`unbase init --comments\` turns them on.`));
186
+ else {
187
+ checks.push(check("package", "ok", `${VITE.name} ${version} is a dependency, and unbase() is in ${file}'s plugins.`));
188
+ if (config && config.has.unbase && !config.options) checks.push(check("options", "info", "unbase()'s options are not literal; doctor reads the project from comment-modus.json."));
189
+ const project = readLink(site);
190
+ if (project) checks.push(check("link", "ok", `Linked to the Unbase project "${project}".`, { file: LINK_FILE }));
191
+ else
192
+ checks.push(
193
+ check("link", "waiting", "Not linked to an Unbase project yet, so comment mode stays off. Unbase fills in `project` in comment-modus.json when the site is connected; or run `unbase init --project <id or slug>`.", {
194
+ missing: "project in comment-modus.json",
195
+ file: LINK_FILE,
196
+ step: STEPS.comments,
197
+ }),
198
+ );
199
+ if (built && project) {
200
+ const page = build.html.get("index.html") ?? "";
201
+ const files = ["version.json", "comment-modus/pages.json"].filter((f) => build.file(f) === null);
202
+ checks.push(
203
+ hasOurScript(page, build.file)
204
+ ? check("loader", "ok", "The ?comment loader is in the built index.html; it loads nothing unless someone opens ?comment.")
205
+ : check("loader", "missing", "The ?comment loader is not in the built index.html.", { missing: "unbase() running in vite build", file, step: STEPS.install }),
206
+ );
207
+ checks.push(
208
+ files.length
209
+ ? check("files", "missing", `The build has no ${files.join(" and ")}.`, { missing: files.join(", "), file, step: STEPS.install })
210
+ : check("files", "ok", "The build has version.json and comment-modus/pages.json (the pages for comment mode's page tree)."),
211
+ );
212
+ }
213
+ if (!envHas(site, "PUBLIC_SUPABASE_URL") || !envHas(site, "PUBLIC_SUPABASE_ANON_KEY"))
214
+ checks.push(check("backend", "info", "comment mode finds Unbase's backend through PUBLIC_SUPABASE_URL and PUBLIC_SUPABASE_ANON_KEY where the site is built; they are not set here, and doctor cannot see your host's."));
215
+ }
216
+ const chose = !unlisted && (!listed || (config && !config.has.unbase) || off);
217
+ features.push({ id: "comments", name: "Comments on the site", state: featureState(checks, !!chose), checks });
218
+ }
219
+
220
+ // ── Page management: draft pages, and the site settings in index.html ─────
221
+ {
222
+ const checks = [];
223
+ const text = (p) => site.text(p);
224
+ const kit = core.kitInstalled({ framework: "vite-react", text });
225
+ const unlisted = packageCheck();
226
+ if (unlisted) checks.push(unlisted);
227
+ else if (config?.has.unbase && config?.has.kit)
228
+ checks.push(check("kit", "missing", `${file} calls unbase() and ${PAGES.name}'s plugin: two kits would each remove the same routes, and the build stops.`, { missing: `${PAGES.name}'s plugin out of plugins`, file, step: STEPS.install }));
229
+ else if (kit && config?.has.unbase) checks.push(check("kit", "ok", `The draft-pages kit runs in ${VITE.name}'s unbase().`));
230
+ else if (kit) checks.push(check("kit", "ok", `${PAGES.name}'s Vite plugin is in ${file}. \`unbase init\` moves it to ${VITE.name}, which also brings comments on the site.`));
231
+ else
232
+ checks.push(
233
+ check("kit", "missing", listed ? `${file} does not call unbase() in plugins.` : `${VITE.name} is not a dependency.`, {
234
+ missing: listed ? "unbase() in plugins" : VITE.name,
235
+ file: listed ? file : "package.json",
236
+ step: STEPS.install,
237
+ }),
238
+ );
239
+
240
+ // The drafts unbase.pages.json holds now, as a production build will treat them.
241
+ const files = site.appPaths.filter(registryFiles).map((p) => ({ path: p, text: text(p) ?? "" }));
242
+ const byPath = new Map(files.map((f) => [f.path, f.text]));
243
+ const pageFile = core.parsePageFile(text(core.PAGE_FILE));
244
+ if (!pageFile.ok) checks.push(check("drafts", "missing", `${core.PAGE_FILE} is invalid: ${pageFile.error}.`, { missing: `a valid ${core.PAGE_FILE}`, file: core.PAGE_FILE, step: STEPS.drafts }));
245
+ else {
246
+ const plan = core.draftPlan({ framework: "vite-react", paths: [...byPath.keys()].sort(), text: (p) => byPath.get(p) ?? null, pageFile });
247
+ if (plan.failed.length)
248
+ checks.push(
249
+ check("drafts", "missing", `A production build would stop: ${plan.failed.map((f) => `${f.path} (${f.reason}${f.detail ? `: ${f.detail}` : ""})`).join(", ")}.`, {
250
+ missing: "drafts the kit can keep out",
251
+ file: core.PAGE_FILE,
252
+ step: STEPS.drafts,
253
+ }),
254
+ );
255
+ else checks.push(check("drafts", "ok", plan.checks.length ? `${plan.checks.length} draft(s) in ${core.PAGE_FILE}, each kept out of production builds.` : "No drafts now."));
256
+ }
257
+ if (kit && build) {
258
+ if (!built) checks.push(check("fails-closed", "skipped", "The build failed."));
259
+ else if (/production build \(UNBASE_DEPLOY_CONTEXT\)/.test(build.output)) checks.push(check("fails-closed", "ok", "The kit ran in the production build: a draft it cannot keep out stops the build."));
260
+ else checks.push(check("fails-closed", "missing", "The kit did not run in the production build.", { missing: "unbase() running in vite build", file, step: STEPS.install }));
261
+ }
262
+ // Which pages can be drafts, as Unbase's page tree will say (staged: Publishing with a Live branch, set in Unbase).
263
+ const registry = registryOf({ files, framework: "vite-react", appPath: site.appPath, staged: true, truncated: false });
264
+ const pages = registry.pages.filter((p) => p.kind !== "template");
265
+ if (!pages.length)
266
+ checks.push(check("routes", "missing", "Unbase finds no route in the code: it reads JSX <Route path element> in a file that imports react-router(-dom).", { missing: "<Route path element> routes", file: "src/App.tsx", step: STEPS.drafts }));
267
+ else if (kit) {
268
+ const ok = pages.filter((p) => p.capabilities.draft.ok).length;
269
+ const why = {};
270
+ for (const p of pages) if (!p.capabilities.draft.ok) (why[p.capabilities.draft.reason] ??= []).push(p.path);
271
+ const rest = Object.entries(why).map(([r, list]) => `${r}: ${list.slice(0, 3).join(", ")}${list.length > 3 ? ", …" : ""}`);
272
+ checks.push(check("draftable", "info", `${ok} of ${pages.length} pages can be drafts${rest.length ? ` (not: ${rest.join("; ")})` : ""}. In Unbase, draft pages also need Publishing with a Live branch.`));
273
+ }
274
+
275
+ // Site settings: read_settings, on index.html. Page settings: none on a single-page app.
276
+ const settings = await readSettings(site.repo, site.appPath, "vite-react");
277
+ const found = Object.keys(settings?.site ?? {});
278
+ const absent = Object.keys(SITE_SETTINGS).filter((k) => !found.includes(k) && k !== "faviconDark");
279
+ if (!site.exists("index.html")) checks.push(check("site-settings", "missing", "No index.html in the site's folder.", { missing: "index.html", file: "index.html", step: STEPS.settings }));
280
+ else if (!found.length)
281
+ checks.push(check("site-settings", "missing", "index.html has none of the settings Unbase reads (a <title>, a meta description, <html lang>, one icon, og:image) as a plain value.", { missing: "<title> in index.html", file: "index.html", step: STEPS.settings }));
282
+ else
283
+ checks.push(
284
+ check(
285
+ "site-settings",
286
+ "ok",
287
+ `Site settings in index.html: ${found.map((k) => SITE_SETTINGS[k]).join(", ")}.${absent.length ? ` Not there, so not offered: ${absent.map((k) => SITE_SETTINGS[k]).join(", ")}.` : ""}`,
288
+ ),
289
+ );
290
+ checks.push(check("page-settings", "info", "No page settings: every route of a single-page app is index.html, so a route has no <head> of its own to set."));
291
+ features.push({ id: "page-management", name: "Page management", state: featureState(checks), checks });
292
+ }
293
+
294
+ // ── Analytics ─────────────────────────────────────────────────────────────
295
+ features.push(
296
+ analyticsFeature(site, {
297
+ umbrella: VITE,
298
+ version: listed ? version : null,
299
+ configured: !!config?.has.unbase,
300
+ option: config?.has.unbase ? (config.options ? config.options.analytics : null) : null,
301
+ project: readLink(site),
302
+ before: !listed && [PAGES.name, BEFORE.pages].some((n) => deps[n] !== undefined),
303
+ step: STEPS.analytics,
304
+ install: STEPS.install,
305
+ config: file,
306
+ }),
307
+ );
308
+ return features;
309
+ }
310
+
311
+ export default {
312
+ id: "vite-react",
313
+ name: "Vite + React",
314
+ /** In the order the kit looks for them (kitFiles). */
315
+ configFiles: core.kitFiles("vite-react").filter((f) => f !== "package.json"),
316
+ agents: AGENTS,
317
+ comments: true,
318
+ /** comment-modus.json links analytics without comment mode too: the plugin reads it itself. */
319
+ analyticsLink: true,
320
+ analyticsOption,
321
+ build: { bin: "vite", args: (outDir) => ["build", "--outDir", outDir, "--emptyOutDir"], env: {}, output: [] },
322
+ packages: () => [VITE, SELF],
323
+ init: planInit,
324
+ replaced: planReplaced,
325
+ current: currentOf,
326
+ linked: readLink,
327
+ uninstall: planUninstall,
328
+ doctor: doctorFeatures,
329
+ };
package/lib/init.mjs ADDED
@@ -0,0 +1,186 @@
1
+ // ============================================================================
2
+ // unbase init — adds Unbase to a site: the packages at pinned versions (with
3
+ // the site's own package manager), and the framework's own files (on Astro:
4
+ // its line in astro.config, and comment-modus.json; frameworks/*.mjs
5
+ // `init`). Touches no content. Every step checks what is there first, so a
6
+ // second run changes nothing. Plans every change before making one: a config
7
+ // it cannot edit safely stops the run with nothing changed.
8
+ //
9
+ // A site from before K5 (03-11) is moved across: the framework's module says
10
+ // which old packages its package replaces (`replaced`), init takes them out
11
+ // once the new one is in, and the pointer line moves to the CLI's new name.
12
+ // Running init again is also how a site updates; with --yes a site that has
13
+ // Unbase keeps its choice of comments.
14
+ //
15
+ // Analytics comes with the framework's package, on unless its config says
16
+ // `analytics: false`: init adds nothing for it but the collector's origin in
17
+ // the site's CSP, where it can edit it safely (lib/analytics.mjs: vercel.json,
18
+ // public/_headers), and names the CSPs it cannot edit. On Astro and Vite
19
+ // comment-modus.json links analytics too, so --no-comments still writes it.
20
+ // ============================================================================
21
+
22
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { COLLECTOR_ORIGIN, cspElsewhereIn, elsewhereSteps, planCsp } from "./analytics.mjs";
25
+ import { CouldNotRun, PASSED } from "./errors.mjs";
26
+ import { addPackages, dropDependencies, installAsListed, lockfileOf, packageManagerOf, tarballFor, writeDependencies } from "./pm.mjs";
27
+ import { installedVersion, openSite } from "./site.mjs";
28
+ import { BEFORE, compareVersions, SELF, versionIn } from "./versions.mjs";
29
+
30
+ export const POINTER_FILES = ["AGENTS.md", "CLAUDE.md"];
31
+ const pointerLine = (cli) => `Unbase: when you change this site, follow node_modules/${cli}/AGENTS.md, so its texts, pages and settings stay editable in Unbase.`;
32
+ export const POINTER_LINE = pointerLine(SELF.name);
33
+ /** The line under the CLI's name before K5: init replaces it, uninstall takes it out. */
34
+ export const POINTER_BEFORE = pointerLine(BEFORE.cli);
35
+ /** What Unbase reads a project key as (detect.ts, the Astro adapter): a uuid or a slug. */
36
+ const PROJECT = /^[a-z0-9][a-z0-9-]{0,39}$/;
37
+
38
+ /** A choice from its flags, a question in a terminal, or an error without one (never a silent default). */
39
+ async function choose(io, flags, { yes, no, question, fallback }) {
40
+ if (flags[yes]) return true;
41
+ if (flags[no]) return false;
42
+ if (flags.yes) return fallback;
43
+ if (io.interactive) return io.ask(question, fallback);
44
+ throw new CouldNotRun("choice_missing", `Pass --${yes} or --${no} (or --yes for the defaults): there is no terminal to ask in.`);
45
+ }
46
+
47
+ /**
48
+ * What init does with one package: add it, move it up to the pinned version when the one there is
49
+ * older, or keep it (the pinned version already, a newer one, or one whose version cannot be read).
50
+ * Never down. The version there is node_modules', else the one package.json names.
51
+ */
52
+ export function planPackage(site, p) {
53
+ const pkg = site.pkg;
54
+ const inDev = pkg.devDependencies?.[p.name] !== undefined;
55
+ const spec = pkg.dependencies?.[p.name] ?? pkg.devDependencies?.[p.name];
56
+ if (spec === undefined) return { ...p, action: "added" };
57
+ const dev = inDev && pkg.dependencies?.[p.name] === undefined;
58
+ // An exact version in package.json is what gets installed (so --no-install twice is still a no-op); else what is installed, else the range's floor.
59
+ const exact = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(String(spec).trim()) ? String(spec).trim() : null;
60
+ const have = exact ?? installedVersion(site, p.name) ?? versionIn(spec);
61
+ if (!have) return { ...p, dev, action: "kept", have: spec, note: "its version cannot be read" };
62
+ const order = compareVersions(have, p.version);
63
+ if (order < 0) return { ...p, dev, action: "updated", from: have, to: p.version, have: spec };
64
+ if (order > 0) return { ...p, dev, action: "kept", have: spec, note: `newer than the ${p.version} this CLI pins` };
65
+ return { ...p, dev, action: "kept", have: spec };
66
+ }
67
+
68
+ export async function init(flags, io) {
69
+ const site = await openSite(flags.dir ?? process.cwd());
70
+ const fw = site.framework;
71
+
72
+ const project = typeof flags.project === "string" ? flags.project : null;
73
+ if (project !== null && !PROJECT.test(project)) throw new CouldNotRun("usage", `--project is the Unbase project's id or slug (lower case, digits, dashes), not "${project}".`);
74
+ if (!fw.comments && (flags.comments || project)) throw new CouldNotRun("usage", `Comments on the live site have no package for ${fw.name} yet: leave out --comments and --project.`);
75
+ // --yes: a site that has Unbase keeps what it chose; a new one gets comments.
76
+ const now = fw.current?.(site) ?? null;
77
+ const comments = fw.comments && (await choose(io, flags, { yes: "comments", no: "no-comments", question: "Add comments on the live site (?comment, comment-modus)?", fallback: now ? now.comments : true }));
78
+ // Analytics: on unless the site's config already says analytics: false (init never writes it).
79
+ const analytics = fw.analyticsOption ? fw.analyticsOption(site) : true;
80
+ /** comment-modus.json links what is on: comment mode, or on Astro and Vite analytics alone. */
81
+ const links = comments || (analytics && !!fw.analyticsLink);
82
+ if (!links && project)
83
+ throw new CouldNotRun("usage", fw.analyticsLink ? "--project links comments and analytics; with --no-comments and analytics: false there is nothing to link." : `--project links comments; it cannot go with --no-comments (on ${fw.name}, analytics comes with comments).`);
84
+ const pointerWanted = await choose(io, flags, { yes: "pointer", no: "no-pointer", question: "Add a line to AGENTS.md or CLAUDE.md pointing your coding agent at Unbase's conventions?", fallback: false });
85
+ let pointerFile = null;
86
+ if (pointerWanted) {
87
+ pointerFile = typeof flags.pointer === "string" ? flags.pointer : (POINTER_FILES.find((f) => site.exists(f)) ?? "AGENTS.md");
88
+ if (!POINTER_FILES.includes(pointerFile)) throw new CouldNotRun("usage", `--pointer is AGENTS.md or CLAUDE.md, not "${pointerFile}".`);
89
+ }
90
+
91
+ // ── Plan ──────────────────────────────────────────────────────────────────
92
+ // The framework's own files (on Astro: astro.config, comment-modus.json), planned: nothing is written yet.
93
+ const own = fw.init(site, { comments, project, analytics });
94
+ // The collector's origin in the site's CSP, where the CLI can edit it; the other places named.
95
+ const csp = analytics ? planCsp(site, { add: true }) : { files: [], invalid: [] };
96
+ const elsewhere = analytics ? cspElsewhereIn(site) : [];
97
+ // What the framework's package replaced (K5): out once it is in; what the site keeps, moved to the version it brings.
98
+ const replaced = fw.replaced?.(site, own) ?? { remove: [], keep: [], by: null };
99
+ const packages = [...fw.packages({ comments }), ...replaced.keep].map((p) => planPackage(site, p));
100
+ const toAdd = packages.filter((p) => p.action !== "kept").map((p) => ({ ...p, tarball: tarballFor(flags.tarballs, p) ?? undefined }));
101
+ if (flags.tarballs && !existsSync(flags.tarballs)) throw new CouldNotRun("usage", `--tarballs: no folder ${flags.tarballs}.`);
102
+
103
+ const pointers = [];
104
+ // The old line moves to the new name wherever it is, asked or not: it points at a package that goes.
105
+ for (const file of POINTER_FILES) {
106
+ const text = site.text(file);
107
+ if (text?.split("\n").some((l) => l.trim() === POINTER_BEFORE))
108
+ pointers.push({ file, action: "changed", text: text.split("\n").map((l) => (l.trim() === POINTER_BEFORE ? POINTER_LINE : l)).join("\n"), changes: [`${POINTER_BEFORE} → ${POINTER_LINE}`] });
109
+ }
110
+ if (pointerFile && !pointers.some((p) => p.file === pointerFile)) {
111
+ const text = site.text(pointerFile);
112
+ if (text === null) pointers.push({ file: pointerFile, action: "created", text: `${POINTER_LINE}\n`, changes: [POINTER_LINE] });
113
+ else if (!text.split("\n").some((l) => l.trim() === POINTER_LINE)) pointers.push({ file: pointerFile, action: "changed", text: `${text}${text.endsWith("\n") || !text ? "" : "\n"}\n${POINTER_LINE}\n`, changes: [POINTER_LINE] });
114
+ }
115
+
116
+ // ── Apply ─────────────────────────────────────────────────────────────────
117
+ const pm = packageManagerOf(site);
118
+ const files = [];
119
+ const line = (p) => `${p.dev ? "devDependencies" : "dependencies"}: ${p.name} ${p.action === "updated" ? `${p.from} → ` : ""}${p.tarball && !flags["no-install"] ? `${p.version} (${p.tarball})` : p.version}`;
120
+ const removed = (n) => `removed ${n}${replaced.by ? ` (replaced by ${replaced.by})` : ""}`;
121
+ if (toAdd.length || replaced.remove.length) {
122
+ if (flags["no-install"]) {
123
+ if (toAdd.length) writeDependencies(site, toAdd);
124
+ if (replaced.remove.length) dropDependencies(site, replaced.remove);
125
+ files.push({ file: "package.json", action: "changed", changes: [...toAdd.map(line), ...replaced.remove.map(removed)] });
126
+ } else if (replaced.remove.length) {
127
+ // The move: package.json with the new packages in and the old ones out, then one install, so
128
+ // a bin the old and the new CLI both name is the new one's. A failed install puts it back.
129
+ const before = readFileSync(join(site.root, "package.json"), "utf8");
130
+ writeDependencies(site, toAdd.map((p) => (p.tarball ? { ...p, version: `file:${p.tarball}` } : p)));
131
+ dropDependencies(site, replaced.remove);
132
+ io.progress(`Moving to ${toAdd.map((p) => `${p.name}@${p.version}`).join(", ") || replaced.by}, without ${replaced.remove.join(", ")}, with ${pm}…`);
133
+ installAsListed(site, pm, before, { quiet: io.json });
134
+ files.push({ file: "package.json", action: "changed", changes: [...toAdd.map(line), ...replaced.remove.map(removed)] });
135
+ files.push({ file: lockfileOf(site, pm), action: "changed", changes: [`${pm} installed ${toAdd.length} and removed ${replaced.remove.length} package(s)`] });
136
+ } else {
137
+ if (toAdd.length) {
138
+ io.progress(`Installing ${toAdd.map((p) => `${p.name}@${p.version}${p.tarball ? " (from a local tarball)" : ""}`).join(", ")} with ${pm}…`);
139
+ addPackages(site, pm, toAdd, { quiet: io.json });
140
+ }
141
+ files.push({ file: "package.json", action: "changed", changes: toAdd.map(line) });
142
+ files.push({ file: lockfileOf(site, pm), action: "changed", changes: [`${pm} installed ${toAdd.length} package(s)`] });
143
+ }
144
+ }
145
+ for (const f of [...own, ...csp.files]) {
146
+ writeFileSync(join(site.root, f.file), f.text);
147
+ files.push({ file: f.file, action: f.action, changes: f.changes });
148
+ }
149
+ for (const p of pointers) {
150
+ writeFileSync(join(site.root, p.file), p.text);
151
+ files.push({ file: p.file, action: p.action, changes: p.changes });
152
+ }
153
+
154
+ const linked = links ? fw.linked(site) : null;
155
+ const agents = `node_modules/${SELF.name}/${fw.agents}`;
156
+ return {
157
+ command: "init",
158
+ ok: true,
159
+ exitCode: PASSED,
160
+ site: site.root,
161
+ framework: { id: fw.id, name: fw.name },
162
+ /** The steps init leaves, for this framework. */
163
+ agents,
164
+ packageManager: pm,
165
+ installed: !flags["no-install"],
166
+ comments,
167
+ /** Analytics comes with the package, on unless the config says analytics: false. */
168
+ analytics,
169
+ project: linked,
170
+ /** The CSP files init allowed the collector in, the ones it could not read, and the other places that may set a CSP. */
171
+ csp: { files: csp.files.map((f) => f.file), invalid: csp.invalid, elsewhere },
172
+ changed: files.length > 0,
173
+ packages: [
174
+ ...packages.map(({ name, version, dev, action, have, from, to, note }) => ({ name, version, dev, action, ...(from ? { from, to } : {}), ...(have ? { have } : {}), ...(note ? { note } : {}) })),
175
+ ...replaced.remove.map((name) => ({ name, action: "removed", ...(replaced.by ? { replacedBy: replaced.by } : {}) })),
176
+ ],
177
+ files,
178
+ next: [
179
+ ...(flags["no-install"] && toAdd.length ? [`Install the packages: ${pm} install`] : []),
180
+ ...elsewhereSteps(elsewhere),
181
+ ...csp.invalid.map((f) => `${f} cannot be read, so the CLI did not edit it: allow ${COLLECTOR_ORIGIN} in its Content-Security-Policy's connect-src.`),
182
+ `Do the steps in ${agents} that this site still needs.`,
183
+ "Run npx @unbase-app/cli doctor until it passes; then commit on a new branch.",
184
+ ],
185
+ };
186
+ }