@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,142 @@
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, analytics: wrapped ? analyticsOf(call) : null };
72
+ }
73
+
74
+ /** withUnbase(config, { analytics })'s `analytics`: true (absent, or true), false, or null when not literal. */
75
+ function analyticsOf(call) {
76
+ const opts = unwrap(call.arguments[1]);
77
+ if (!opts) return true;
78
+ if (opts.type !== "ObjectExpression") return null;
79
+ const prop = opts.properties.find((p) => p.type === "ObjectProperty" && !p.computed && (p.key.name ?? p.key.value) === "analytics");
80
+ if (!prop) return opts.properties.some((p) => p.type === "SpreadElement") ? null : true;
81
+ const v = unwrap(prop.value);
82
+ return v.type === "BooleanLiteral" ? v.value : null;
83
+ }
84
+
85
+ /** Where a new import (or require) goes: after the last one at the top, else at the start. */
86
+ function importAt(ast, cjs) {
87
+ let at = 0;
88
+ for (const n of ast.program.body) {
89
+ if (n.type === "ImportDeclaration" || (cjs && n.type === "VariableDeclaration" && n.declarations.some((d) => d.init?.type === "CallExpression" && d.init.callee.name === "require"))) at = n.end;
90
+ else if (n.type === "ExpressionStatement" && n.directive) at = n.end;
91
+ }
92
+ return at;
93
+ }
94
+
95
+ /** next.config with the config wrapped in withUnbase(…), and the changes made; the same when it is already. */
96
+ export function wrapNextConfig(code, file) {
97
+ const found = inspectNextConfig(code, file);
98
+ if (found.wrapped) return { code, changes: [] };
99
+ const changes = [];
100
+ const edits = [];
101
+ let name = [...found.names][0] ?? null;
102
+ if (!name) {
103
+ name = WRAPPER;
104
+ const line = found.cjs ? `const { ${WRAPPER} } = require("${NEXT.name}");` : `import { ${WRAPPER} } from "${NEXT.name}";`;
105
+ const at = importAt(found.ast, found.cjs);
106
+ edits.push({ at, text: at ? `\n${line}` : `${line}\n` });
107
+ changes.push(found.cjs ? `require: ${WRAPPER} from ${NEXT.name}` : `import: ${WRAPPER} from ${NEXT.name}`);
108
+ }
109
+ edits.push({ at: found.value.start, text: `${name}(` }, { at: found.value.end, text: ")" });
110
+ changes.push(`${found.cjs ? "module.exports" : "export default"}: wrapped in ${name}(…)`);
111
+ const out = applySplices(code, edits.map((e) => ({ start: e.at, end: e.at, text: e.text })));
112
+ if (!inspectNextConfig(out, file).wrapped) throw unsafe(file, "the change did not read back as withUnbase(…)");
113
+ return { code: out, changes };
114
+ }
115
+
116
+ /** next.config without withUnbase(…) and the package's import or require; the same when it has neither. */
117
+ export function unwrapNextConfig(code, file) {
118
+ const found = inspectNextConfig(code, file);
119
+ const edits = [];
120
+ const changes = [];
121
+ if (found.wrapped) {
122
+ const args = found.call.arguments;
123
+ if (!args.length) throw unsafe(file, `${found.call.callee.name}() has no config to keep`);
124
+ // withUnbase(config, options) → config: the call's own text around its first argument goes.
125
+ edits.push({ start: found.call.start, end: args[0].start }, { start: args[0].end, end: found.call.end });
126
+ changes.push(`${found.cjs ? "module.exports" : "export default"}: ${found.call.callee.name}(…) taken off`);
127
+ }
128
+ // The import or require: whole when it binds only names this config no longer uses.
129
+ const rest = applySplices(code, edits);
130
+ const used = (n) => new RegExp(`(^|[^\\w$.])${n.replace(/[$]/g, "\\$")}\\b`).test(rest.replace(/^\s*(import\b[^;]*;?|const\s*\{[^}]*\}\s*=\s*require\([^)]*\);?)/gm, ""));
131
+ for (const node of [...found.imports, ...found.required.map((r) => r.node)]) {
132
+ const names = node.type === "ImportDeclaration" ? node.specifiers.map((s) => s.local.name) : requireOf(node).names;
133
+ if (names.some(used)) throw unsafe(file, `it uses ${names.filter(used).join(", ")} from ${NEXT.name} besides the config`);
134
+ edits.push(lineRange(code, node.start, node.end) ?? { start: node.start, end: node.end });
135
+ changes.push(`${node.type === "ImportDeclaration" ? "import" : "require"} of ${NEXT.name} removed`);
136
+ }
137
+ if (!edits.length) return { code, changes: [] };
138
+ const out = applySplices(code, edits);
139
+ const after = inspectNextConfig(out, file);
140
+ if (after.wrapped || after.imports.length || after.required.length) throw unsafe(file, "the change did not read back without withUnbase");
141
+ return { code: out, changes };
142
+ }
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
+ }