@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/AGENTS.md +37 -0
- package/LICENSE +21 -0
- package/README.md +211 -2
- package/agents/astro.md +162 -0
- package/agents/next.md +109 -0
- package/agents/vite-react.md +108 -0
- package/bin/unbase.mjs +147 -0
- package/lib/args.mjs +49 -0
- package/lib/build.mjs +71 -0
- package/lib/compare.mjs +96 -0
- package/lib/config-edit.mjs +629 -0
- package/lib/doctor.mjs +37 -0
- package/lib/errors.mjs +15 -0
- package/lib/feature.mjs +23 -0
- package/lib/frameworks/astro.mjs +485 -0
- package/lib/frameworks/index.mjs +50 -0
- package/lib/frameworks/next.mjs +321 -0
- package/lib/frameworks/vite-react.mjs +299 -0
- package/lib/init.mjs +165 -0
- package/lib/next-config.mjs +131 -0
- package/lib/pm.mjs +109 -0
- package/lib/readers.mjs +1918 -0
- package/lib/site.mjs +153 -0
- package/lib/uninstall.mjs +136 -0
- package/lib/versions.mjs +71 -0
- package/lib/vite-config.mjs +294 -0
- package/package.json +43 -4
package/lib/init.mjs
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
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
|
+
|
|
16
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
import { CouldNotRun, PASSED } from "./errors.mjs";
|
|
19
|
+
import { addPackages, dropDependencies, installAsListed, lockfileOf, packageManagerOf, tarballFor, writeDependencies } from "./pm.mjs";
|
|
20
|
+
import { installedVersion, openSite } from "./site.mjs";
|
|
21
|
+
import { BEFORE, compareVersions, SELF, versionIn } from "./versions.mjs";
|
|
22
|
+
|
|
23
|
+
export const POINTER_FILES = ["AGENTS.md", "CLAUDE.md"];
|
|
24
|
+
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.`;
|
|
25
|
+
export const POINTER_LINE = pointerLine(SELF.name);
|
|
26
|
+
/** The line under the CLI's name before K5: init replaces it, uninstall takes it out. */
|
|
27
|
+
export const POINTER_BEFORE = pointerLine(BEFORE.cli);
|
|
28
|
+
/** What Unbase reads a project key as (detect.ts, the Astro adapter): a uuid or a slug. */
|
|
29
|
+
const PROJECT = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
30
|
+
|
|
31
|
+
/** A choice from its flags, a question in a terminal, or an error without one (never a silent default). */
|
|
32
|
+
async function choose(io, flags, { yes, no, question, fallback }) {
|
|
33
|
+
if (flags[yes]) return true;
|
|
34
|
+
if (flags[no]) return false;
|
|
35
|
+
if (flags.yes) return fallback;
|
|
36
|
+
if (io.interactive) return io.ask(question, fallback);
|
|
37
|
+
throw new CouldNotRun("choice_missing", `Pass --${yes} or --${no} (or --yes for the defaults): there is no terminal to ask in.`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* What init does with one package: add it, move it up to the pinned version when the one there is
|
|
42
|
+
* older, or keep it (the pinned version already, a newer one, or one whose version cannot be read).
|
|
43
|
+
* Never down. The version there is node_modules', else the one package.json names.
|
|
44
|
+
*/
|
|
45
|
+
export function planPackage(site, p) {
|
|
46
|
+
const pkg = site.pkg;
|
|
47
|
+
const inDev = pkg.devDependencies?.[p.name] !== undefined;
|
|
48
|
+
const spec = pkg.dependencies?.[p.name] ?? pkg.devDependencies?.[p.name];
|
|
49
|
+
if (spec === undefined) return { ...p, action: "added" };
|
|
50
|
+
const dev = inDev && pkg.dependencies?.[p.name] === undefined;
|
|
51
|
+
// 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.
|
|
52
|
+
const exact = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(String(spec).trim()) ? String(spec).trim() : null;
|
|
53
|
+
const have = exact ?? installedVersion(site, p.name) ?? versionIn(spec);
|
|
54
|
+
if (!have) return { ...p, dev, action: "kept", have: spec, note: "its version cannot be read" };
|
|
55
|
+
const order = compareVersions(have, p.version);
|
|
56
|
+
if (order < 0) return { ...p, dev, action: "updated", from: have, to: p.version, have: spec };
|
|
57
|
+
if (order > 0) return { ...p, dev, action: "kept", have: spec, note: `newer than the ${p.version} this CLI pins` };
|
|
58
|
+
return { ...p, dev, action: "kept", have: spec };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function init(flags, io) {
|
|
62
|
+
const site = await openSite(flags.dir ?? process.cwd());
|
|
63
|
+
const fw = site.framework;
|
|
64
|
+
|
|
65
|
+
const project = typeof flags.project === "string" ? flags.project : null;
|
|
66
|
+
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}".`);
|
|
67
|
+
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.`);
|
|
68
|
+
// --yes: a site that has Unbase keeps what it chose; a new one gets comments.
|
|
69
|
+
const now = fw.current?.(site) ?? null;
|
|
70
|
+
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 }));
|
|
71
|
+
if (!comments && project) throw new CouldNotRun("usage", "--project links comments; it cannot go with --no-comments.");
|
|
72
|
+
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 });
|
|
73
|
+
let pointerFile = null;
|
|
74
|
+
if (pointerWanted) {
|
|
75
|
+
pointerFile = typeof flags.pointer === "string" ? flags.pointer : (POINTER_FILES.find((f) => site.exists(f)) ?? "AGENTS.md");
|
|
76
|
+
if (!POINTER_FILES.includes(pointerFile)) throw new CouldNotRun("usage", `--pointer is AGENTS.md or CLAUDE.md, not "${pointerFile}".`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ── Plan ──────────────────────────────────────────────────────────────────
|
|
80
|
+
// The framework's own files (on Astro: astro.config, comment-modus.json), planned: nothing is written yet.
|
|
81
|
+
const own = fw.init(site, { comments, project });
|
|
82
|
+
// What the framework's package replaced (K5): out once it is in; what the site keeps, moved to the version it brings.
|
|
83
|
+
const replaced = fw.replaced?.(site, own) ?? { remove: [], keep: [], by: null };
|
|
84
|
+
const packages = [...fw.packages({ comments }), ...replaced.keep].map((p) => planPackage(site, p));
|
|
85
|
+
const toAdd = packages.filter((p) => p.action !== "kept").map((p) => ({ ...p, tarball: tarballFor(flags.tarballs, p) ?? undefined }));
|
|
86
|
+
if (flags.tarballs && !existsSync(flags.tarballs)) throw new CouldNotRun("usage", `--tarballs: no folder ${flags.tarballs}.`);
|
|
87
|
+
|
|
88
|
+
const pointers = [];
|
|
89
|
+
// The old line moves to the new name wherever it is, asked or not: it points at a package that goes.
|
|
90
|
+
for (const file of POINTER_FILES) {
|
|
91
|
+
const text = site.text(file);
|
|
92
|
+
if (text?.split("\n").some((l) => l.trim() === POINTER_BEFORE))
|
|
93
|
+
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}`] });
|
|
94
|
+
}
|
|
95
|
+
if (pointerFile && !pointers.some((p) => p.file === pointerFile)) {
|
|
96
|
+
const text = site.text(pointerFile);
|
|
97
|
+
if (text === null) pointers.push({ file: pointerFile, action: "created", text: `${POINTER_LINE}\n`, changes: [POINTER_LINE] });
|
|
98
|
+
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] });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ── Apply ─────────────────────────────────────────────────────────────────
|
|
102
|
+
const pm = packageManagerOf(site);
|
|
103
|
+
const files = [];
|
|
104
|
+
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}`;
|
|
105
|
+
const removed = (n) => `removed ${n}${replaced.by ? ` (replaced by ${replaced.by})` : ""}`;
|
|
106
|
+
if (toAdd.length || replaced.remove.length) {
|
|
107
|
+
if (flags["no-install"]) {
|
|
108
|
+
if (toAdd.length) writeDependencies(site, toAdd);
|
|
109
|
+
if (replaced.remove.length) dropDependencies(site, replaced.remove);
|
|
110
|
+
files.push({ file: "package.json", action: "changed", changes: [...toAdd.map(line), ...replaced.remove.map(removed)] });
|
|
111
|
+
} else if (replaced.remove.length) {
|
|
112
|
+
// The move: package.json with the new packages in and the old ones out, then one install, so
|
|
113
|
+
// a bin the old and the new CLI both name is the new one's. A failed install puts it back.
|
|
114
|
+
const before = readFileSync(join(site.root, "package.json"), "utf8");
|
|
115
|
+
writeDependencies(site, toAdd.map((p) => (p.tarball ? { ...p, version: `file:${p.tarball}` } : p)));
|
|
116
|
+
dropDependencies(site, replaced.remove);
|
|
117
|
+
io.progress(`Moving to ${toAdd.map((p) => `${p.name}@${p.version}`).join(", ") || replaced.by}, without ${replaced.remove.join(", ")}, with ${pm}…`);
|
|
118
|
+
installAsListed(site, pm, before, { quiet: io.json });
|
|
119
|
+
files.push({ file: "package.json", action: "changed", changes: [...toAdd.map(line), ...replaced.remove.map(removed)] });
|
|
120
|
+
files.push({ file: lockfileOf(site, pm), action: "changed", changes: [`${pm} installed ${toAdd.length} and removed ${replaced.remove.length} package(s)`] });
|
|
121
|
+
} else {
|
|
122
|
+
if (toAdd.length) {
|
|
123
|
+
io.progress(`Installing ${toAdd.map((p) => `${p.name}@${p.version}${p.tarball ? " (from a local tarball)" : ""}`).join(", ")} with ${pm}…`);
|
|
124
|
+
addPackages(site, pm, toAdd, { quiet: io.json });
|
|
125
|
+
}
|
|
126
|
+
files.push({ file: "package.json", action: "changed", changes: toAdd.map(line) });
|
|
127
|
+
files.push({ file: lockfileOf(site, pm), action: "changed", changes: [`${pm} installed ${toAdd.length} package(s)`] });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
for (const f of own) {
|
|
131
|
+
writeFileSync(join(site.root, f.file), f.text);
|
|
132
|
+
files.push({ file: f.file, action: f.action, changes: f.changes });
|
|
133
|
+
}
|
|
134
|
+
for (const p of pointers) {
|
|
135
|
+
writeFileSync(join(site.root, p.file), p.text);
|
|
136
|
+
files.push({ file: p.file, action: p.action, changes: p.changes });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const linked = comments ? fw.linked(site) : null;
|
|
140
|
+
const agents = `node_modules/${SELF.name}/${fw.agents}`;
|
|
141
|
+
return {
|
|
142
|
+
command: "init",
|
|
143
|
+
ok: true,
|
|
144
|
+
exitCode: PASSED,
|
|
145
|
+
site: site.root,
|
|
146
|
+
framework: { id: fw.id, name: fw.name },
|
|
147
|
+
/** The steps init leaves, for this framework. */
|
|
148
|
+
agents,
|
|
149
|
+
packageManager: pm,
|
|
150
|
+
installed: !flags["no-install"],
|
|
151
|
+
comments,
|
|
152
|
+
project: linked,
|
|
153
|
+
changed: files.length > 0,
|
|
154
|
+
packages: [
|
|
155
|
+
...packages.map(({ name, version, dev, action, have, from, to, note }) => ({ name, version, dev, action, ...(from ? { from, to } : {}), ...(have ? { have } : {}), ...(note ? { note } : {}) })),
|
|
156
|
+
...replaced.remove.map((name) => ({ name, action: "removed", ...(replaced.by ? { replacedBy: replaced.by } : {}) })),
|
|
157
|
+
],
|
|
158
|
+
files,
|
|
159
|
+
next: [
|
|
160
|
+
...(flags["no-install"] && toAdd.length ? [`Install the packages: ${pm} install`] : []),
|
|
161
|
+
`Do the steps in ${agents} that this site still needs.`,
|
|
162
|
+
"Run npx @unbase-app/cli doctor until it passes; then commit on a new branch.",
|
|
163
|
+
],
|
|
164
|
+
};
|
|
165
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// Editing next.config safely: the config wrapped in withUnbase(…) and the
|
|
3
|
+
// import (or require) of @unbase-app/next added, or both taken out again.
|
|
4
|
+
// As config-edit.mjs does for astro.config, with its helpers: the config is
|
|
5
|
+
// parsed (Babel, with TypeScript for .ts), the places are found in the syntax
|
|
6
|
+
// tree, the change is a splice at those offsets so the rest keeps its
|
|
7
|
+
// formatting and comments, and the result is parsed again and checked. What the tree does not make
|
|
8
|
+
// certain (no `export default` or `module.exports =`, a class, withUnbase used
|
|
9
|
+
// elsewhere) stops with an error naming the file: never a guess.
|
|
10
|
+
// ============================================================================
|
|
11
|
+
|
|
12
|
+
import { parse } from "@babel/parser";
|
|
13
|
+
import { applySplices, lineRange, unwrap } from "./config-edit.mjs";
|
|
14
|
+
import { CouldNotRun } from "./errors.mjs";
|
|
15
|
+
import { NEXT } from "./versions.mjs";
|
|
16
|
+
|
|
17
|
+
export const WRAPPER = "withUnbase";
|
|
18
|
+
|
|
19
|
+
const unsafe = (file, why) =>
|
|
20
|
+
new CouldNotRun("config_unsafe", `${file} cannot be edited safely: ${why}. Make the change by hand (step 1 of agents/next.md in @unbase-app/cli), then run the command again.`, { file });
|
|
21
|
+
|
|
22
|
+
function parseConfig(code, file) {
|
|
23
|
+
try {
|
|
24
|
+
return parse(code, { sourceType: /\.cjs$/.test(file) ? "script" : "unambiguous", plugins: /\.(m|c)?ts$/.test(file) ? ["typescript"] : [], errorRecovery: false });
|
|
25
|
+
} catch (e) {
|
|
26
|
+
throw unsafe(file, `it does not parse (${e.message})`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** `module.exports = …` at the top. */
|
|
31
|
+
const isModuleExports = (n) =>
|
|
32
|
+
n.type === "ExpressionStatement" &&
|
|
33
|
+
n.expression.type === "AssignmentExpression" &&
|
|
34
|
+
n.expression.left.type === "MemberExpression" &&
|
|
35
|
+
n.expression.left.object.name === "module" &&
|
|
36
|
+
(n.expression.left.property.name === "exports" || n.expression.left.property.value === "exports");
|
|
37
|
+
|
|
38
|
+
/** `require("@unbase-app/next")` as a declaration's value: its statement and local names. */
|
|
39
|
+
function requireOf(n) {
|
|
40
|
+
if (n.type !== "VariableDeclaration") return null;
|
|
41
|
+
for (const d of n.declarations) {
|
|
42
|
+
const init = d.init;
|
|
43
|
+
if (init?.type !== "CallExpression" || init.callee.name !== "require" || init.arguments[0]?.value !== NEXT.name) continue;
|
|
44
|
+
if (d.id.type === "Identifier") return { node: n, names: [d.id.name], default: true };
|
|
45
|
+
if (d.id.type === "ObjectPattern") return { node: n, names: d.id.properties.map((p) => p.value?.name).filter(Boolean), default: false };
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* What a next.config holds of Unbase: whether it is CommonJS, where its config is handed to Next.js
|
|
52
|
+
* (the node `export default` or `module.exports =` gives), the import (or require) of the package
|
|
53
|
+
* and the names it binds, and whether that config is withUnbase(…).
|
|
54
|
+
*/
|
|
55
|
+
export function inspectNextConfig(code, file) {
|
|
56
|
+
const ast = parseConfig(code, file);
|
|
57
|
+
const body = ast.program.body;
|
|
58
|
+
const exp = body.find((n) => n.type === "ExportDefaultDeclaration");
|
|
59
|
+
const cjs = body.find(isModuleExports);
|
|
60
|
+
if (!exp && !cjs) throw unsafe(file, "it has no `export default` or `module.exports =`");
|
|
61
|
+
const imports = body.filter((n) => n.type === "ImportDeclaration" && n.source.value === NEXT.name);
|
|
62
|
+
const required = body.map(requireOf).filter(Boolean);
|
|
63
|
+
const names = new Set([
|
|
64
|
+
...imports.flatMap((n) => n.specifiers.map((s) => (s.type === "ImportSpecifier" && (s.imported.name ?? s.imported.value) === WRAPPER) || s.type === "ImportDefaultSpecifier" ? s.local.name : null).filter(Boolean)),
|
|
65
|
+
...required.flatMap((r) => r.names),
|
|
66
|
+
]);
|
|
67
|
+
let value = exp ? exp.declaration : cjs.expression.right;
|
|
68
|
+
if (value.type === "ClassDeclaration") throw unsafe(file, "its `export default` is a class");
|
|
69
|
+
const call = unwrap(value);
|
|
70
|
+
const wrapped = call?.type === "CallExpression" && call.callee.type === "Identifier" && names.has(call.callee.name);
|
|
71
|
+
return { ast, cjs: !exp, value, wrapped, call: wrapped ? call : null, imports, required, names };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Where a new import (or require) goes: after the last one at the top, else at the start. */
|
|
75
|
+
function importAt(ast, cjs) {
|
|
76
|
+
let at = 0;
|
|
77
|
+
for (const n of ast.program.body) {
|
|
78
|
+
if (n.type === "ImportDeclaration" || (cjs && n.type === "VariableDeclaration" && n.declarations.some((d) => d.init?.type === "CallExpression" && d.init.callee.name === "require"))) at = n.end;
|
|
79
|
+
else if (n.type === "ExpressionStatement" && n.directive) at = n.end;
|
|
80
|
+
}
|
|
81
|
+
return at;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** next.config with the config wrapped in withUnbase(…), and the changes made; the same when it is already. */
|
|
85
|
+
export function wrapNextConfig(code, file) {
|
|
86
|
+
const found = inspectNextConfig(code, file);
|
|
87
|
+
if (found.wrapped) return { code, changes: [] };
|
|
88
|
+
const changes = [];
|
|
89
|
+
const edits = [];
|
|
90
|
+
let name = [...found.names][0] ?? null;
|
|
91
|
+
if (!name) {
|
|
92
|
+
name = WRAPPER;
|
|
93
|
+
const line = found.cjs ? `const { ${WRAPPER} } = require("${NEXT.name}");` : `import { ${WRAPPER} } from "${NEXT.name}";`;
|
|
94
|
+
const at = importAt(found.ast, found.cjs);
|
|
95
|
+
edits.push({ at, text: at ? `\n${line}` : `${line}\n` });
|
|
96
|
+
changes.push(found.cjs ? `require: ${WRAPPER} from ${NEXT.name}` : `import: ${WRAPPER} from ${NEXT.name}`);
|
|
97
|
+
}
|
|
98
|
+
edits.push({ at: found.value.start, text: `${name}(` }, { at: found.value.end, text: ")" });
|
|
99
|
+
changes.push(`${found.cjs ? "module.exports" : "export default"}: wrapped in ${name}(…)`);
|
|
100
|
+
const out = applySplices(code, edits.map((e) => ({ start: e.at, end: e.at, text: e.text })));
|
|
101
|
+
if (!inspectNextConfig(out, file).wrapped) throw unsafe(file, "the change did not read back as withUnbase(…)");
|
|
102
|
+
return { code: out, changes };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** next.config without withUnbase(…) and the package's import or require; the same when it has neither. */
|
|
106
|
+
export function unwrapNextConfig(code, file) {
|
|
107
|
+
const found = inspectNextConfig(code, file);
|
|
108
|
+
const edits = [];
|
|
109
|
+
const changes = [];
|
|
110
|
+
if (found.wrapped) {
|
|
111
|
+
const args = found.call.arguments;
|
|
112
|
+
if (!args.length) throw unsafe(file, `${found.call.callee.name}() has no config to keep`);
|
|
113
|
+
// withUnbase(config, options) → config: the call's own text around its first argument goes.
|
|
114
|
+
edits.push({ start: found.call.start, end: args[0].start }, { start: args[0].end, end: found.call.end });
|
|
115
|
+
changes.push(`${found.cjs ? "module.exports" : "export default"}: ${found.call.callee.name}(…) taken off`);
|
|
116
|
+
}
|
|
117
|
+
// The import or require: whole when it binds only names this config no longer uses.
|
|
118
|
+
const rest = applySplices(code, edits);
|
|
119
|
+
const used = (n) => new RegExp(`(^|[^\\w$.])${n.replace(/[$]/g, "\\$")}\\b`).test(rest.replace(/^\s*(import\b[^;]*;?|const\s*\{[^}]*\}\s*=\s*require\([^)]*\);?)/gm, ""));
|
|
120
|
+
for (const node of [...found.imports, ...found.required.map((r) => r.node)]) {
|
|
121
|
+
const names = node.type === "ImportDeclaration" ? node.specifiers.map((s) => s.local.name) : requireOf(node).names;
|
|
122
|
+
if (names.some(used)) throw unsafe(file, `it uses ${names.filter(used).join(", ")} from ${NEXT.name} besides the config`);
|
|
123
|
+
edits.push(lineRange(code, node.start, node.end) ?? { start: node.start, end: node.end });
|
|
124
|
+
changes.push(`${node.type === "ImportDeclaration" ? "import" : "require"} of ${NEXT.name} removed`);
|
|
125
|
+
}
|
|
126
|
+
if (!edits.length) return { code, changes: [] };
|
|
127
|
+
const out = applySplices(code, edits);
|
|
128
|
+
const after = inspectNextConfig(out, file);
|
|
129
|
+
if (after.wrapped || after.imports.length || after.required.length) throw unsafe(file, "the change did not read back without withUnbase");
|
|
130
|
+
return { code: out, changes };
|
|
131
|
+
}
|
package/lib/pm.mjs
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// The site's own package manager, as Unbase detects it (detect.ts: the
|
|
3
|
+
// lockfile in the site's folder or the repository's root, else the root's
|
|
4
|
+
// packageManager field), with npm when there is none.
|
|
5
|
+
// ============================================================================
|
|
6
|
+
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { join, relative, resolve, sep } from "node:path";
|
|
10
|
+
import { CouldNotRun } from "./errors.mjs";
|
|
11
|
+
|
|
12
|
+
const SUPPORTED = ["npm", "pnpm", "yarn"];
|
|
13
|
+
|
|
14
|
+
export function packageManagerOf(site) {
|
|
15
|
+
const pm = site.detection.package_manager ?? "npm";
|
|
16
|
+
if (!SUPPORTED.includes(pm)) throw new CouldNotRun("package_manager", `This site uses ${pm}; the CLI installs with npm, pnpm or yarn. Use --no-install and install the packages yourself.`);
|
|
17
|
+
return pm;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The lockfile the package manager writes, relative to the site: in its folder, or the repository's root in a workspace. */
|
|
21
|
+
export function lockfileOf(site, pm) {
|
|
22
|
+
const name = { npm: "package-lock.json", pnpm: "pnpm-lock.yaml", yarn: "yarn.lock" }[pm];
|
|
23
|
+
if (site.exists(name) || site.repoRoot === site.root || !existsSync(join(site.repoRoot, name))) return name;
|
|
24
|
+
return relative(site.root, join(site.repoRoot, name)).split(sep).join("/");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A tarball for name@version in `dir` (as `npm pack` names it), or null. */
|
|
28
|
+
export function tarballFor(dir, { name, version }) {
|
|
29
|
+
if (!dir) return null;
|
|
30
|
+
const file = join(resolve(dir), `${name.replace(/^@/, "").replace("/", "-")}-${version}.tgz`);
|
|
31
|
+
return existsSync(file) ? file : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function run(cmd, args, cwd, quiet) {
|
|
35
|
+
const r = spawnSync(cmd, args, { cwd, stdio: quiet ? ["ignore", "pipe", "pipe"] : "inherit", encoding: "utf8", shell: process.platform === "win32" });
|
|
36
|
+
if (r.status !== 0) {
|
|
37
|
+
const tail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n").slice(-12).join("\n");
|
|
38
|
+
throw new CouldNotRun("install_failed", `${cmd} ${args.join(" ")} failed${tail ? `:\n${tail}` : ""}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Adds (or moves) packages to exact versions: `specs` are { name, version, dev, tarball? }. */
|
|
43
|
+
export function addPackages(site, pm, specs, { quiet }) {
|
|
44
|
+
for (const dev of [false, true]) {
|
|
45
|
+
const list = specs.filter((s) => s.dev === dev).map((s) => s.tarball ?? `${s.name}@${s.version}`);
|
|
46
|
+
if (!list.length) continue;
|
|
47
|
+
const args = {
|
|
48
|
+
npm: ["install", "--save-exact", ...(dev ? ["--save-dev"] : []), "--no-audit", "--no-fund", ...list],
|
|
49
|
+
pnpm: ["add", "--save-exact", ...(dev ? ["--save-dev"] : []), ...list],
|
|
50
|
+
yarn: ["add", "--exact", ...(dev ? ["--dev"] : []), ...list],
|
|
51
|
+
}[pm];
|
|
52
|
+
run(pm, args, site.root, quiet);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Installs what package.json now says, in one run of the package manager: how a move (K5) puts the
|
|
58
|
+
* new packages in and the old ones out together, so a bin both name (`unbase`) ends up linked to
|
|
59
|
+
* the new one. package.json is put back as it was when the run fails.
|
|
60
|
+
*/
|
|
61
|
+
export function installAsListed(site, pm, before, { quiet }) {
|
|
62
|
+
const args = { npm: ["install", "--no-audit", "--no-fund"], pnpm: ["install"], yarn: ["install"] }[pm];
|
|
63
|
+
try {
|
|
64
|
+
run(pm, args, site.root, quiet);
|
|
65
|
+
} catch (e) {
|
|
66
|
+
writeFileSync(join(site.root, "package.json"), before);
|
|
67
|
+
throw e;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function removePackages(site, pm, names, { quiet }) {
|
|
72
|
+
if (!names.length) return;
|
|
73
|
+
const args = { npm: ["uninstall", "--no-audit", "--no-fund", ...names], pnpm: ["remove", ...names], yarn: ["remove", ...names] }[pm];
|
|
74
|
+
run(pm, args, site.root, quiet);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ── Without the package manager (--no-install): package.json only ───────────
|
|
78
|
+
|
|
79
|
+
function rewritePackageJson(site, change) {
|
|
80
|
+
const file = join(site.root, "package.json");
|
|
81
|
+
const text = readFileSync(file, "utf8");
|
|
82
|
+
const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
|
|
83
|
+
const pkg = JSON.parse(text);
|
|
84
|
+
change(pkg);
|
|
85
|
+
writeFileSync(file, `${JSON.stringify(pkg, null, indent)}${text.endsWith("\n") ? "\n" : ""}`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const sorted = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)));
|
|
89
|
+
|
|
90
|
+
export function writeDependencies(site, specs) {
|
|
91
|
+
rewritePackageJson(site, (pkg) => {
|
|
92
|
+
for (const s of specs) {
|
|
93
|
+
const key = s.dev ? "devDependencies" : "dependencies";
|
|
94
|
+
pkg[key] = sorted({ ...(pkg[key] ?? {}), [s.name]: s.version });
|
|
95
|
+
const other = s.dev ? "dependencies" : "devDependencies";
|
|
96
|
+
if (pkg[other]?.[s.name] !== undefined) delete pkg[other][s.name];
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function dropDependencies(site, names) {
|
|
102
|
+
rewritePackageJson(site, (pkg) => {
|
|
103
|
+
for (const key of ["dependencies", "devDependencies"]) {
|
|
104
|
+
if (!pkg[key]) continue;
|
|
105
|
+
for (const n of names) delete pkg[key][n];
|
|
106
|
+
if (!Object.keys(pkg[key]).length) delete pkg[key];
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|