@unbase-app/cli 0.2.0 → 0.4.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/page.mjs ADDED
@@ -0,0 +1,193 @@
1
+ // ============================================================================
2
+ // unbase page — rename, duplicate or delete a page, or list what can be done
3
+ // to each, by the kit's own rule (core.planPage, docs/plan-page-actions.md):
4
+ // the same files give the same changes as Unbase's editor makes. It writes
5
+ // them in the working tree and commits nothing.
6
+ //
7
+ // unbase page rename <from> <to> [--name <name>] [--not-live]
8
+ // unbase page duplicate <path> [<to>] [--name <name>]
9
+ // unbase page delete <path> [--redirect <to> | --not-found] [--not-live]
10
+ // unbase page list [--not-live]
11
+ //
12
+ // A page counts as live unless --not-live says it never was on the live
13
+ // site: a live page that is renamed or deleted leaves a redirect in
14
+ // unbase.pages.json, which only the framework's package applies from the
15
+ // version core.REDIRECTS_SINCE names. Without one the action is refused,
16
+ // never an address broken.
17
+ // ============================================================================
18
+
19
+ import { copyFileSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
20
+ import { dirname, join } from "node:path";
21
+ import { CouldNotRun, FAILED, PASSED } from "./errors.mjs";
22
+ import { core } from "./readers.mjs";
23
+ import { openSite } from "./site.mjs";
24
+
25
+ export const ACTIONS = ["rename", "duplicate", "delete", "list"];
26
+
27
+ /** Per action: how many addresses it takes (at least, at most), and which of the page flags. */
28
+ const SHAPE = {
29
+ rename: { args: [2, 2], usage: "rename <from> <to>", flags: ["name", "not-live"] },
30
+ duplicate: { args: [1, 2], usage: "duplicate <path> [<to>]", flags: ["name"] },
31
+ delete: { args: [1, 1], usage: "delete <path>", flags: ["redirect", "not-found", "not-live"] },
32
+ list: { args: [0, 0], usage: "list", flags: ["not-live"] },
33
+ };
34
+ const PAGE_FLAGS = ["name", "redirect", "not-found", "not-live"];
35
+
36
+ /** Each framework's package that applies the page file's redirects. */
37
+ const PACKAGE = { astro: "@unbase-app/astro", "vite-react": "@unbase-app/vite", next: "@unbase-app/next" };
38
+
39
+ /** Files the core reads as text: code and content. Everything else is only moved, copied or deleted, by its bytes. */
40
+ const TEXT = /\.(astro|tsx|jsx|ts|js|mjs|cjs|mts|cts|vue|svelte|md|mdx|markdown|html?|json|jsonc|css|scss|sass|less|ya?ml|toml|txt|svg|xml)$/i;
41
+
42
+ /**
43
+ * What each refusal means, in one line. The reasons are core.planPage's (and pageActions'); the
44
+ * plan's table has them too (docs/plan-page-actions.md, Reasons).
45
+ * @type {Record<string, (detail: string, framework: string | null) => string>}
46
+ */
47
+ export const REASONS = {
48
+ invalid: (d) => `${core.PAGE_FILE} is not valid${d ? ` (${d})` : ""}: fix it first`,
49
+ framework: () => "the kit has no page actions for this framework; it has them for Astro, Next.js and Vite + React Router",
50
+ missing: () => "the code makes no page at this address",
51
+ template: (d) => `the page is made by a dynamic route${d ? ` (${d})` : ""}: change it where its data is`,
52
+ unparsed: (d) => `the kit cannot trace this page's route to its file${d ? ` (${d})` : ""}: change it by hand, or with Unbase's Operator`,
53
+ home: () => "Home can be duplicated, but not renamed or deleted",
54
+ address: (d) => `${d || "that"} is not an address it can go to: plain segments, not under the page itself, and for --redirect a page of the site`,
55
+ taken: (d) => `${d || "the new address"} is a page already, or the site's own redirects send it on`,
56
+ no_redirects: (_d, framework) =>
57
+ `a live page leaves a redirect, and this site's build does not apply ${core.PAGE_FILE}'s redirects: update ${PACKAGE[String(framework)] ?? "the framework's Unbase package"} to ${core.REDIRECTS_SINCE[PACKAGE[String(framework)]] ?? "a newer version"} or later (unbase init), or pass --not-live when the page was never on the live site`,
58
+ kit_missing: (d, framework) => REASONS.no_redirects(d, framework),
59
+ same: () => "nothing to change: the address and the name are what they are",
60
+ nested: (d) => `pages are under it${d ? ` (${d})` : ""}: delete those first`,
61
+ content_bound: (d) => `its content is a collection of its own${d ? ` (${d})` : ""}, and a copy needs code the kit does not write: Unbase's Operator can make it`,
62
+ content_unregistered: (d) => `it reads content by a name no content file goes by${d ? ` (${d})` : ""}`,
63
+ redirect_conflict: (d) => `the site's own redirects already send ${d || "this address"} somewhere else`,
64
+ runtime: () => "the page comes from a CMS: change it there",
65
+ too_large: () => "the site is too large to work out the change",
66
+ };
67
+
68
+ /** The reason's line, or the reason itself when the CLI does not know it yet (a newer core). */
69
+ export const explain = (reason, detail = "", framework = null) => (REASONS[reason] ? REASONS[reason](detail ?? "", framework) : `${reason}${detail ? ` (${detail})` : ""}`);
70
+
71
+ /** The app's files as the core reads a commit: every path (git's, or a walk without node_modules, dist, .git), and the text of code and content files. */
72
+ function appFilesOf(site) {
73
+ const paths = site.appPaths;
74
+ const cache = new Map();
75
+ const text = (p) => {
76
+ if (!cache.has(p)) cache.set(p, TEXT.test(p) ? site.text(p) : null);
77
+ return cache.get(p);
78
+ };
79
+ return { paths, text };
80
+ }
81
+
82
+ /**
83
+ * Writes a plan's files under `root`: copies first, so a file that moves is read before it goes;
84
+ * then new text; then deletions; then the folders a deletion left empty.
85
+ * @param {string} root
86
+ * @param {{ path: string, content?: string, from?: string, deleted?: true }[]} writes
87
+ */
88
+ export function applyWrites(root, writes) {
89
+ const at = (p) => join(root, p);
90
+ // A source that is itself written over is read before anything changes.
91
+ const written = new Set(writes.filter((w) => !w.deleted).map((w) => w.path));
92
+ const held = new Map(writes.filter((w) => w.from && written.has(w.from)).map((w) => [w.from, readFileSync(at(/** @type {string} */ (w.from)))]));
93
+ for (const w of writes) {
94
+ if (!w.from) continue;
95
+ mkdirSync(dirname(at(w.path)), { recursive: true });
96
+ if (held.has(w.from)) writeFileSync(at(w.path), held.get(w.from));
97
+ else copyFileSync(at(w.from), at(w.path));
98
+ }
99
+ for (const w of writes) {
100
+ if (w.content === undefined) continue;
101
+ mkdirSync(dirname(at(w.path)), { recursive: true });
102
+ writeFileSync(at(w.path), w.content);
103
+ }
104
+ for (const w of writes) if (w.deleted) rmSync(at(w.path), { force: true });
105
+ for (const w of writes) {
106
+ if (!w.deleted) continue;
107
+ for (let d = dirname(w.path); d && d !== "." && d !== "/"; d = dirname(d)) {
108
+ try {
109
+ if (readdirSync(at(d)).length) break;
110
+ rmdirSync(at(d));
111
+ } catch {
112
+ break;
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ /** A plan's writes as the output says them: created, changed, moved (with `from`), copied (with `from`) or deleted. */
119
+ function described(plan, files) {
120
+ const movedFrom = new Map((plan.renamed ?? []).map((r) => [r.to, r.from]));
121
+ const have = new Set(files.paths);
122
+ return plan.files.map((w) => {
123
+ if (w.deleted) return { path: w.path, action: "deleted" };
124
+ if (movedFrom.has(w.path)) return { path: w.path, action: "moved", from: movedFrom.get(w.path) };
125
+ if (w.from) return { path: w.path, action: "copied", from: w.from };
126
+ return { path: w.path, action: have.has(w.path) || files.text(w.path) !== null ? "changed" : "created" };
127
+ });
128
+ }
129
+
130
+ export async function page(flags, io, args = []) {
131
+ const [action, ...addresses] = args;
132
+ const shape = SHAPE[action];
133
+ if (!shape) throw new CouldNotRun("usage", `${action ? `unbase page ${action}: no such action` : "unbase page: say what to do"}. Actions: ${ACTIONS.join(", ")}.`);
134
+ if (addresses.length < shape.args[0] || addresses.length > shape.args[1]) throw new CouldNotRun("usage", `unbase page ${shape.usage}: ${addresses.length < shape.args[0] ? "an address is missing" : `one address too many ("${addresses.at(-1)}")`}.`);
135
+ for (const f of PAGE_FLAGS) if (flags[f] !== undefined && !shape.flags.includes(f)) throw new CouldNotRun("usage", `--${f} is not for unbase page ${action}.`);
136
+
137
+ const site = await openSite(flags.dir ?? process.cwd());
138
+ const framework = site.detection.framework?.id ?? null;
139
+ const files = appFilesOf(site);
140
+ const live = !flags["not-live"];
141
+ const pageFile = core.parsePageFile(files.text(core.PAGE_FILE));
142
+ const base = { command: "page", action, site: site.root, framework, live };
143
+
144
+ if (action === "list") {
145
+ const found = core.discover({ framework, ...files });
146
+ const result = core.pageActions({ framework, ...files, found, live: live ? new Set(found.pages.map((p) => p.path)) : new Set() });
147
+ const pages = Object.entries(result.actions).map(([path, a]) => ({
148
+ path,
149
+ name: pageFile.ok ? (pageFile.pages[path]?.name ?? null) : null,
150
+ draft: pageFile.ok ? pageFile.pages[path]?.draft === true : false,
151
+ under: a.under,
152
+ rename: a.rename,
153
+ duplicate: a.duplicate,
154
+ delete: a.delete,
155
+ }));
156
+ return { ...base, ok: true, exitCode: PASSED, redirects: result.redirects, package: PACKAGE[String(framework)] ?? null, since: core.REDIRECTS_SINCE[PACKAGE[String(framework)]] ?? null, pages };
157
+ }
158
+
159
+ const at = core.normalisePath(addresses[0]);
160
+ /** @type {Record<string, unknown>} */
161
+ let request;
162
+ if (action === "rename") request = { action, path: at, to: addresses[1], live, ...(flags.name !== undefined ? { name: String(flags.name) } : {}) };
163
+ else if (action === "duplicate") {
164
+ // Named after the original, as Unbase's menu names a copy, when the original has a name.
165
+ const name = flags.name !== undefined ? String(flags.name) : pageFile.ok && pageFile.pages[at]?.name ? `${pageFile.pages[at].name} (copy)` : undefined;
166
+ request = { action, path: at, ...(addresses[1] ? { to: addresses[1] } : {}), ...(name ? { name } : {}), drafts: core.kitInstalled({ framework, text: files.text }) };
167
+ } else request = { action, path: at, live, ...(flags["not-found"] ? { redirect: null } : flags.redirect !== undefined ? { redirect: String(flags.redirect) } : {}) };
168
+
169
+ const plan = core.planPage(/** @type {any} */ (request), { framework, ...files });
170
+ if (!plan.ok) {
171
+ return { ...base, ok: false, exitCode: FAILED, path: at, reason: plan.reason, detail: plan.detail ?? null, message: explain(plan.reason, plan.detail, framework) };
172
+ }
173
+ const dryRun = !!flags["dry-run"];
174
+ const changes = described(plan, files);
175
+ if (!dryRun) {
176
+ io.progress?.(`Writing ${plan.files.length} file(s)…`);
177
+ applyWrites(site.root, plan.files);
178
+ }
179
+ return {
180
+ ...base,
181
+ ok: true,
182
+ exitCode: PASSED,
183
+ dryRun,
184
+ path: plan.path,
185
+ to: plan.to,
186
+ message: plan.message,
187
+ files: changes,
188
+ links: plan.links,
189
+ unlinked: plan.unlinked,
190
+ redirects: plan.redirects,
191
+ moves: plan.moves,
192
+ };
193
+ }