@camposcloud/cli 0.0.0-stage → 1.0.1

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.
Files changed (43) hide show
  1. package/README.md +153 -2
  2. package/dist/commands/apps.js +197 -0
  3. package/dist/commands/auth.js +194 -0
  4. package/dist/commands/completion.js +94 -0
  5. package/dist/commands/create.js +220 -0
  6. package/dist/commands/dashboard.js +44 -0
  7. package/dist/commands/db.js +85 -0
  8. package/dist/commands/deploy.js +104 -0
  9. package/dist/commands/env.js +103 -0
  10. package/dist/commands/files.js +101 -0
  11. package/dist/commands/lang.js +34 -0
  12. package/dist/commands/manage.js +121 -0
  13. package/dist/commands/teams.js +127 -0
  14. package/dist/commands/utils.js +102 -0
  15. package/dist/core/api.js +157 -0
  16. package/dist/core/apiErrors.js +38 -0
  17. package/dist/core/apps.js +98 -0
  18. package/dist/core/config.js +34 -0
  19. package/dist/core/context.js +43 -0
  20. package/dist/core/credentials.js +90 -0
  21. package/dist/core/databases.js +53 -0
  22. package/dist/core/detect.js +75 -0
  23. package/dist/core/deviceLogin.js +49 -0
  24. package/dist/core/env.js +71 -0
  25. package/dist/core/files.js +51 -0
  26. package/dist/core/help.js +193 -0
  27. package/dist/core/i18n.js +581 -0
  28. package/dist/core/logs.js +87 -0
  29. package/dist/core/output.js +27 -0
  30. package/dist/core/project.js +119 -0
  31. package/dist/core/prompt.js +29 -0
  32. package/dist/core/session.js +21 -0
  33. package/dist/core/suggest.js +28 -0
  34. package/dist/core/teams.js +39 -0
  35. package/dist/core/update.js +48 -0
  36. package/dist/index.js +223 -0
  37. package/dist/tui/App.js +400 -0
  38. package/dist/tui/App.test.js +189 -0
  39. package/dist/tui/Picker.js +87 -0
  40. package/dist/tui/clickable.js +64 -0
  41. package/dist/tui/mouse.js +65 -0
  42. package/dist/tui/run.js +27 -0
  43. package/package.json +58 -4
@@ -0,0 +1,220 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { appAddress, formatBytes, formatMB } from "../core/apps.js";
4
+ import { detectProject, readCamposConfig, RUNTIME_LABEL, RUNTIMES, toSubdomain } from "../core/detect.js";
5
+ import { parseDotEnv } from "../core/env.js";
6
+ import { t } from "../core/i18n.js";
7
+ import { pc, spinner, ui } from "../core/output.js";
8
+ import { createExcluder, DEFAULT_IGNORE, findProject, MAX_UPLOAD_BYTES, readIgnoreFile, removeProject, writeProject, zipProject } from "../core/project.js";
9
+ import { ask, confirm, isInteractive } from "../core/prompt.js";
10
+ import { signedInContext } from "../core/session.js";
11
+ import { listTeams } from "../core/teams.js";
12
+ import { findApp } from "./apps.js";
13
+ const MEMORY_CHOICES = [256, 512, 1024, 2048, 4096];
14
+ /**
15
+ * `campos create`: makes a new application from this folder. In a terminal it asks, one question at a time,
16
+ * with the folder's own answers already chosen (runtime, main file, memory, name); `--yes` takes them as they
17
+ * are. The folder ends linked to the new application, so `campos deploy` updates it.
18
+ */
19
+ export async function create(apiUrl, options) {
20
+ const { client, team: activeTeam } = await signedInContext(apiUrl);
21
+ const root = process.cwd();
22
+ const askAll = isInteractive() && !options.yes;
23
+ const { pick } = askAll ? await import("../tui/Picker.js") : { pick: null };
24
+ const packing = spinner(t("deploy.packing", { folder: path.basename(root) }));
25
+ const patterns = [...DEFAULT_IGNORE, ...readIgnoreFile(root)];
26
+ let archive;
27
+ try {
28
+ archive = await zipProject(root, createExcluder(patterns));
29
+ }
30
+ finally {
31
+ packing.stop();
32
+ }
33
+ if (archive.files.length === 0) {
34
+ ui.fail(t("deploy.empty"));
35
+ return 1;
36
+ }
37
+ if (archive.zip.length > MAX_UPLOAD_BYTES) {
38
+ ui.fail(t("deploy.tooBig", { size: formatBytes(archive.zip.length), max: formatBytes(MAX_UPLOAD_BYTES) }));
39
+ return 1;
40
+ }
41
+ const config = readCamposConfig(root);
42
+ const packageJson = fs.existsSync(path.join(root, "package.json")) ? fs.readFileSync(path.join(root, "package.json"), "utf8") : undefined;
43
+ const detected = detectProject(archive.files, packageJson);
44
+ const configRuntime = RUNTIMES.find((runtime) => runtime === config.RUNTIME?.toLowerCase());
45
+ // Name.
46
+ let name = options.name ?? config.DISPLAY_NAME ?? path.basename(root);
47
+ if (askAll && !options.name)
48
+ name = await ask(t("create.askName"), name);
49
+ if (name.trim().length < 3) {
50
+ ui.fail(t("create.nameTooShort"));
51
+ return 1;
52
+ }
53
+ // Runtime.
54
+ let runtime = (RUNTIMES.find((item) => item === options.runtime?.toLowerCase()) ?? configRuntime ?? detected.runtime ?? "nodejs");
55
+ if (askAll && !options.runtime && pick) {
56
+ const ordered = [runtime, ...RUNTIMES.filter((item) => item !== runtime)];
57
+ const chosen = await pick(t("create.askRuntime"), ordered.map((item) => ({ label: RUNTIME_LABEL[item], detail: item === (configRuntime ?? detected.runtime) ? t("create.detected") : undefined, value: item })));
58
+ if (!chosen)
59
+ return cancelled();
60
+ runtime = chosen;
61
+ }
62
+ // Main file.
63
+ const defaultMain = config.MAIN || (detected.runtime === runtime ? detected.mainFile : undefined) || (runtime === "python" ? "main.py" : "index.js");
64
+ let mainFile = options.main ?? defaultMain;
65
+ if (askAll && !options.main)
66
+ mainFile = await ask(t("create.askMain"), defaultMain);
67
+ if (!archive.files.includes(mainFile.replace(/^\.?\//, "")))
68
+ ui.dim(t("create.mainMissing", { file: mainFile }));
69
+ // Memory.
70
+ let memoryMB = Number(options.memory ?? config.MEMORY ?? 256);
71
+ if (askAll && !options.memory && pick) {
72
+ const preset = MEMORY_CHOICES.includes(memoryMB) ? memoryMB : 256;
73
+ const chosen = await pick(t("create.askMemory"), [preset, ...MEMORY_CHOICES.filter((item) => item !== preset)].map((mb) => ({ label: formatMB(mb), value: mb })));
74
+ if (chosen === null)
75
+ return cancelled();
76
+ memoryMB = chosen;
77
+ }
78
+ if (!Number.isInteger(memoryMB) || memoryMB < 128) {
79
+ ui.fail(t("create.badMemory"));
80
+ return 1;
81
+ }
82
+ // Public address.
83
+ let web = options.web ?? Boolean(config.SUBDOMAIN);
84
+ if (askAll && options.web === undefined && pick) {
85
+ const chosen = await pick(t("create.askWeb"), [
86
+ { label: t(web ? "create.webYes" : "create.webNo"), value: web },
87
+ { label: t(web ? "create.webNo" : "create.webYes"), value: !web },
88
+ ]);
89
+ if (chosen === null)
90
+ return cancelled();
91
+ web = chosen;
92
+ }
93
+ let port;
94
+ let subdomain;
95
+ if (web) {
96
+ const defaultPort = options.port ?? config.PORT ?? "3000";
97
+ port = Number(askAll && !options.port ? await ask(t("create.askPort"), defaultPort) : defaultPort);
98
+ const defaultSub = (options.subdomain ?? config.SUBDOMAIN ?? toSubdomain(name)).toLowerCase();
99
+ subdomain = askAll && !options.subdomain ? (await ask(t("create.askSubdomain"), defaultSub)).toLowerCase() : defaultSub;
100
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
101
+ ui.fail(t("create.badPort"));
102
+ return 1;
103
+ }
104
+ }
105
+ // Where: the personal account or one of the teams (the active one first).
106
+ let teamId = activeTeam?.id;
107
+ let teamName = activeTeam?.name;
108
+ if (askAll && pick) {
109
+ const teams = await listTeams(client).catch(() => []);
110
+ if (teams.length) {
111
+ const items = [{ label: t("team.personal"), value: "" }, ...teams.map((team) => ({ label: team.name, value: team._id }))];
112
+ items.sort((a, b) => Number(b.value === (teamId ?? "")) - Number(a.value === (teamId ?? "")));
113
+ const chosen = await pick(t("create.askWhere"), items);
114
+ if (chosen === null)
115
+ return cancelled();
116
+ teamId = chosen || undefined;
117
+ teamName = teams.find((team) => team._id === chosen)?.name;
118
+ }
119
+ }
120
+ // Variables from .env.
121
+ const envFile = path.join(root, ".env");
122
+ const envVars = fs.existsSync(envFile) ? parseDotEnv(fs.readFileSync(envFile, "utf8")).filter((item) => item.value !== "") : [];
123
+ let sendEnv = options.env !== false && envVars.length > 0;
124
+ if (askAll && sendEnv && options.env === undefined)
125
+ sendEnv = await confirm(t("create.askEnv", { count: String(envVars.length) }), true);
126
+ const startupCommand = options.start ?? config.START ?? "";
127
+ const autoRestart = options.autoRestart ?? (config.AUTORESTART ? config.AUTORESTART.toLowerCase() === "true" : true);
128
+ // Asked one by one, the answers are already on screen: only what was not asked is added before confirming.
129
+ if (askAll) {
130
+ ui.dim(` ${t("create.field.files")}: ${archive.files.length} (${formatBytes(archive.zip.length)}) · ${t("create.field.env")}: ${sendEnv ? envVars.length : "—"}`);
131
+ }
132
+ else {
133
+ ui.blank();
134
+ ui.info(pc.bold(t("create.summary")));
135
+ const rows = [
136
+ [t("create.field.name"), name],
137
+ [t("create.field.runtime"), RUNTIME_LABEL[runtime]],
138
+ [t("create.field.main"), mainFile],
139
+ [t("apps.info.memory"), formatMB(memoryMB)],
140
+ [t("create.field.web"), web ? `${subdomain}.camposcloud.app → ${port}` : t("create.webNo")],
141
+ [t("create.field.where"), teamName ? t("create.inTeam", { team: teamName }) : t("team.personal")],
142
+ [t("create.field.files"), `${archive.files.length} (${formatBytes(archive.zip.length)})`],
143
+ [t("create.field.env"), sendEnv ? String(envVars.length) : "—"],
144
+ ];
145
+ const width = Math.max(...rows.map(([label]) => label.length));
146
+ for (const [label, value] of rows)
147
+ ui.info(` ${pc.dim(label.padEnd(width))} ${value}`);
148
+ ui.blank();
149
+ }
150
+ if (askAll && !(await confirm(t("create.confirm"), true)))
151
+ return cancelled();
152
+ const fields = {
153
+ appName: name.trim(),
154
+ mainFile,
155
+ memoryMB: String(memoryMB),
156
+ runtimeEnvironment: runtime,
157
+ autoRestartEnabled: String(autoRestart),
158
+ exposedViaWeb: String(web),
159
+ };
160
+ if (startupCommand.trim())
161
+ fields.startupCommand = startupCommand.trim();
162
+ if (teamId)
163
+ fields.team = teamId;
164
+ if (web && port && subdomain) {
165
+ fields.port = String(port);
166
+ fields.assignedSubdomain = subdomain;
167
+ }
168
+ if (sendEnv)
169
+ fields.environmentVariables = JSON.stringify(envVars.map(({ key, value }) => ({ key, value })));
170
+ const sending = spinner(t("create.creating", { name }));
171
+ let created;
172
+ try {
173
+ created = await client.postForm("/v1/apps/create", fields, archive.zip, `${path.basename(root)}.zip`);
174
+ }
175
+ finally {
176
+ sending.stop();
177
+ }
178
+ writeProject(root, { appId: created._id, name: created.name ?? name, apiUrl });
179
+ ui.ok(t("create.done", { name: pc.bold(created.name ?? name) }));
180
+ const address = appAddress(created);
181
+ if (address)
182
+ ui.info(` ${pc.cyan(`https://${address}`)}`);
183
+ ui.dim(t("create.next"));
184
+ return 0;
185
+ }
186
+ function cancelled() {
187
+ ui.info(t("error.cancelled"));
188
+ return 130;
189
+ }
190
+ /**
191
+ * `campos delete [app]`: removes the application for good. Asks to type its name (unless --yes), like the
192
+ * dashboard does; a folder linked to it is unlinked.
193
+ */
194
+ export async function deleteApp(apiUrl, query, options) {
195
+ const { client, app } = await findApp(apiUrl, query);
196
+ if (!options.yes) {
197
+ if (!isInteractive()) {
198
+ ui.fail(t("delete.needsYes"));
199
+ return 1;
200
+ }
201
+ ui.info(pc.red(t("delete.warning", { name: pc.bold(app.name) })));
202
+ const typed = await ask(t("delete.typeName"));
203
+ if (typed.trim() !== app.name) {
204
+ ui.info(t("delete.notMatched"));
205
+ return 1;
206
+ }
207
+ }
208
+ const wait = spinner(t("delete.deleting", { name: app.name }));
209
+ try {
210
+ await client.delete(`/v1/apps/${encodeURIComponent(app._id)}/delete`);
211
+ }
212
+ finally {
213
+ wait.stop();
214
+ }
215
+ const project = findProject();
216
+ if (project?.appId === app._id)
217
+ removeProject(project.root);
218
+ ui.ok(t("delete.done", { name: app.name }));
219
+ return 0;
220
+ }
@@ -0,0 +1,44 @@
1
+ import { ApiClient, ApiError, fetchMe } from "../core/api.js";
2
+ import { readToken } from "../core/credentials.js";
3
+ import { t } from "../core/i18n.js";
4
+ import { pc, ui } from "../core/output.js";
5
+ /**
6
+ * `campos` with nothing after it. In a terminal, signed in: the interactive dashboard. Otherwise (a pipe, CI,
7
+ * or not signed in yet): who is signed in and the list of commands.
8
+ */
9
+ export async function dashboard(apiUrl, help, initialAppId) {
10
+ const stored = await readToken(apiUrl);
11
+ let me = null;
12
+ if (stored) {
13
+ try {
14
+ me = (await fetchMe(new ApiClient(apiUrl, stored.token))).user;
15
+ }
16
+ catch (error) {
17
+ if (!(error instanceof ApiError && error.status === 401))
18
+ throw error;
19
+ }
20
+ }
21
+ if (!me || !stored) {
22
+ ui.info(t("home.signedOut"));
23
+ ui.blank();
24
+ ui.info(help);
25
+ return me ? 0 : 1;
26
+ }
27
+ if (!process.stdout.isTTY || !process.stdin.isTTY) {
28
+ ui.info(t("home.signedIn", { email: pc.bold(me.email) }));
29
+ ui.blank();
30
+ ui.dim(t("home.soon"));
31
+ ui.info(help);
32
+ return 0;
33
+ }
34
+ // Loaded only here: the other commands never pay for React.
35
+ const { runDashboard } = await import("../tui/run.js");
36
+ const via = stored.source === "env" ? "env" : stored.token.startsWith("cc_cli_") ? "cli" : "token";
37
+ const client = new ApiClient(apiUrl, stored.token);
38
+ const { activeTeam } = await import("../core/teams.js");
39
+ const { siteUrl } = await import("./utils.js");
40
+ const team = await activeTeam(client, apiUrl).catch(() => null);
41
+ const openUrl = (url) => { import("open").then(({ default: open }) => open(url)).catch(() => undefined); };
42
+ await runDashboard({ client, me, apiUrl, via, team, openUrl, siteUrl: siteUrl(apiUrl), initialAppId });
43
+ return 0;
44
+ }
@@ -0,0 +1,85 @@
1
+ import { formatBytes, formatMB } from "../core/apps.js";
2
+ import { connectionUrl, dbState, dbTypeLabel, listDbs, powerDb, resolveDb } from "../core/databases.js";
3
+ import { t } from "../core/i18n.js";
4
+ import { pc, spinner, ui } from "../core/output.js";
5
+ import { signedInContext } from "../core/session.js";
6
+ const stateColor = { online: pc.green, offline: pc.dim, suspended: pc.red, creating: pc.yellow };
7
+ // eslint-disable-next-line no-control-regex
8
+ const visible = (text) => text.replace(/\x1b\[[0-9;]*m/g, "");
9
+ const pad = (text, width) => text + " ".repeat(Math.max(0, width - visible(text).length));
10
+ export async function dbList(apiUrl, options) {
11
+ const { client, team } = await signedInContext(apiUrl);
12
+ const dbs = await listDbs(client, team?.id);
13
+ if (team && !options.json)
14
+ ui.dim(t("team.listingIn", { team: team.name }));
15
+ if (options.json) {
16
+ console.log(JSON.stringify(dbs.map((db) => ({ id: db._id, name: db.name, type: db.type, state: dbState(db), memoryMB: db.allocatedMemoryMB, host: db.connection?.host ?? null, port: db.connection?.port ?? null }))));
17
+ return 0;
18
+ }
19
+ if (dbs.length === 0) {
20
+ ui.info(t("db.none"));
21
+ return 0;
22
+ }
23
+ const rows = dbs.map((db) => [pc.bold(db.name), dbTypeLabel(db), stateColor[dbState(db)](`● ${t(`state.${dbState(db)}`)}`), formatMB(db.allocatedMemoryMB), db.connection?.port ? `${db.connection.host}:${db.connection.port}` : "—"]);
24
+ const headers = [t("apps.col.name"), t("db.col.type"), t("apps.col.state"), t("apps.col.memory"), t("db.col.address")];
25
+ const widths = headers.map((header, column) => Math.max(header.length, ...rows.map((row) => visible(row[column]).length)));
26
+ const line = (cells) => cells.map((cell, column) => pad(cell, widths[column])).join(" ").trimEnd();
27
+ ui.info([pc.dim(line(headers)), ...rows.map(line)].join("\n"));
28
+ ui.blank();
29
+ ui.dim(t("db.hint"));
30
+ return 0;
31
+ }
32
+ export async function dbInfo(apiUrl, query, options) {
33
+ const { client, team } = await signedInContext(apiUrl);
34
+ const db = resolveDb(await listDbs(client, team?.id), query);
35
+ const url = connectionUrl(db);
36
+ if (options.json) {
37
+ console.log(JSON.stringify({ id: db._id, name: db.name, type: db.type, state: dbState(db), memoryMB: db.allocatedMemoryMB, vcpu: db.allocatedVCpu, diskUsedBytes: db.diskUsageBytes ?? null, diskLimitBytes: db.diskLimitBytes ?? null, connection: db.connection ?? null, url }));
38
+ return 0;
39
+ }
40
+ const rows = [
41
+ [t("apps.info.state"), stateColor[dbState(db)](`● ${t(`state.${dbState(db)}`)}`)],
42
+ [t("db.type"), dbTypeLabel(db)],
43
+ [t("apps.info.memory"), `${formatMB(db.allocatedMemoryMB)} · ${db.allocatedVCpu ?? "?"} vCPU`],
44
+ [t("db.disk"), db.diskLimitBytes ? `${formatBytes(db.diskUsageBytes ?? 0)} / ${formatBytes(db.diskLimitBytes)}` : "—"],
45
+ [t("db.user"), db.connection?.username ?? "—"],
46
+ [t("db.database"), db.connection?.database ?? "—"],
47
+ [t("db.url"), url ?? "—"],
48
+ [t("apps.info.id"), pc.dim(db._id)],
49
+ ];
50
+ const width = Math.max(...rows.map(([label]) => label.length));
51
+ ui.info(pc.bold(db.name));
52
+ for (const [label, value] of rows)
53
+ ui.info(` ${pc.dim(label.padEnd(width))} ${value}`);
54
+ if (url) {
55
+ ui.blank();
56
+ ui.dim(` ${t("db.passwordNote")}`);
57
+ }
58
+ return 0;
59
+ }
60
+ /** Just the connection string, for `$(campos db url banco)` in scripts. */
61
+ export async function dbUrl(apiUrl, query) {
62
+ const { client, team } = await signedInContext(apiUrl);
63
+ const db = resolveDb(await listDbs(client, team?.id), query);
64
+ const url = connectionUrl(db);
65
+ if (!url) {
66
+ ui.fail(t("db.noConnection"));
67
+ return 1;
68
+ }
69
+ console.log(url);
70
+ return 0;
71
+ }
72
+ export async function dbPower(apiUrl, query, requested) {
73
+ const { client, team } = await signedInContext(apiUrl);
74
+ const db = resolveDb(await listDbs(client, team?.id), query);
75
+ const action = requested === "restart" && dbState(db) !== "online" ? "start" : requested;
76
+ const wait = spinner(t(`apps.power.${action}.doing`, { name: db.name }));
77
+ try {
78
+ await powerDb(client, db._id, action);
79
+ }
80
+ finally {
81
+ wait.stop();
82
+ }
83
+ ui.ok(t(`apps.power.${action}.done`, { name: db.name }));
84
+ return 0;
85
+ }
@@ -0,0 +1,104 @@
1
+ import path from "node:path";
2
+ import { appState, formatBytes, listApps, resolveApp, runtimeLabel } from "../core/apps.js";
3
+ import { t } from "../core/i18n.js";
4
+ import { pc, spinner, ui } from "../core/output.js";
5
+ import { createExcluder, DEFAULT_IGNORE, findProject, MAX_UPLOAD_BYTES, readIgnoreFile, removeProject, writeProject, zipProject } from "../core/project.js";
6
+ import { signedInContext } from "../core/session.js";
7
+ const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
8
+ /** The application `query` names, or — in a terminal, with no name — the one chosen from a list. */
9
+ async function chooseApp(client, teamId, query, title) {
10
+ const { apps } = await listApps(client, teamId);
11
+ if (query)
12
+ return resolveApp(apps, query);
13
+ if (apps.length === 0) {
14
+ ui.info(t("apps.none"));
15
+ return null;
16
+ }
17
+ if (!interactive())
18
+ throw new Error(t("link.needsName"));
19
+ const { pick } = await import("../tui/Picker.js");
20
+ return pick(title, apps.map((app) => ({ label: app.name, detail: [t(`state.${appState(app)}`), runtimeLabel(app)].filter(Boolean).join(" · "), value: app })));
21
+ }
22
+ /** `campos link [app]`: this folder is that application; `campos deploy` sends it there from now on. */
23
+ export async function link(apiUrl, query) {
24
+ const { client, team } = await signedInContext(apiUrl);
25
+ const app = await chooseApp(client, team?.id, query, t("link.choose"));
26
+ if (!app)
27
+ return 1;
28
+ const root = findProject()?.root ?? process.cwd();
29
+ writeProject(root, { appId: app._id, name: app.name, apiUrl });
30
+ ui.ok(t("link.done", { folder: path.basename(root), name: pc.bold(app.name) }));
31
+ ui.dim(t("link.next"));
32
+ return 0;
33
+ }
34
+ export async function unlink() {
35
+ const project = findProject();
36
+ if (!project) {
37
+ ui.info(t("link.none"));
38
+ return 0;
39
+ }
40
+ removeProject(project.root);
41
+ ui.ok(t("unlink.done", { folder: path.basename(project.root), name: project.name }));
42
+ return 0;
43
+ }
44
+ /**
45
+ * `campos deploy`: zips the folder (without node_modules, .git and what `.camposignore` lists), sends it to the
46
+ * linked application and restarts it. Files are added or replaced; files deleted here stay on the server.
47
+ */
48
+ export async function deploy(apiUrl, options) {
49
+ const { client, team } = await signedInContext(apiUrl);
50
+ const project = findProject();
51
+ let app;
52
+ if (options.app) {
53
+ app = resolveApp((await listApps(client, team?.id)).apps, options.app);
54
+ }
55
+ else if (project && (!project.apiUrl || project.apiUrl === apiUrl)) {
56
+ app = { _id: project.appId, name: project.name, status: "active" };
57
+ }
58
+ else {
59
+ app = await chooseApp(client, team?.id, undefined, t("deploy.choose"));
60
+ if (!app)
61
+ return 1;
62
+ // Chosen once: the folder remembers it.
63
+ writeProject(process.cwd(), { appId: app._id, name: app.name, apiUrl });
64
+ ui.dim(t("deploy.linked", { name: app.name }));
65
+ }
66
+ const root = project?.root ?? process.cwd();
67
+ const patterns = [...DEFAULT_IGNORE, ...readIgnoreFile(root)];
68
+ const packing = spinner(t("deploy.packing", { folder: path.basename(root) }));
69
+ let archive;
70
+ try {
71
+ archive = await zipProject(root, createExcluder(patterns));
72
+ }
73
+ finally {
74
+ packing.stop();
75
+ }
76
+ if (archive.files.length === 0) {
77
+ ui.fail(t("deploy.empty"));
78
+ return 1;
79
+ }
80
+ ui.info(t("deploy.summary", { files: String(archive.files.length), size: formatBytes(archive.totalBytes), zip: formatBytes(archive.zip.length), name: pc.bold(app.name) }));
81
+ ui.dim(t("deploy.ignored", { list: patterns.join(", ") }));
82
+ if (archive.zip.length > MAX_UPLOAD_BYTES) {
83
+ ui.fail(t("deploy.tooBig", { size: formatBytes(archive.zip.length), max: formatBytes(MAX_UPLOAD_BYTES) }));
84
+ return 1;
85
+ }
86
+ if (options.dryRun) {
87
+ for (const file of archive.files.slice(0, 40))
88
+ ui.dim(` ${file}`);
89
+ if (archive.files.length > 40)
90
+ ui.dim(` … ${t("deploy.andMore", { count: String(archive.files.length - 40) })}`);
91
+ return 0;
92
+ }
93
+ const restart = options.restart !== false;
94
+ const sending = spinner(t(restart ? "deploy.sendingRestart" : "deploy.sending", { name: app.name }));
95
+ try {
96
+ await client.uploadZip(`/v1/apps/${encodeURIComponent(app._id)}/upload?path=%2F&restart=${restart}`, archive.zip, `${path.basename(root)}.zip`);
97
+ }
98
+ finally {
99
+ sending.stop();
100
+ }
101
+ ui.ok(t(restart ? "deploy.doneRestart" : "deploy.done", { name: pc.bold(app.name) }));
102
+ ui.dim(t("deploy.follow", { name: app.name }));
103
+ return 0;
104
+ }
@@ -0,0 +1,103 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { powerApp } from "../core/apps.js";
4
+ import { maskValue, mergeEnv, parseAssignment, parseDotEnv, readEnv, toDotEnv, writeEnv } from "../core/env.js";
5
+ import { t } from "../core/i18n.js";
6
+ import { pc, spinner, ui } from "../core/output.js";
7
+ import { findApp } from "./apps.js";
8
+ async function load(apiUrl, query) {
9
+ const { client, app } = await findApp(apiUrl, query);
10
+ const vars = await readEnv(client, app._id);
11
+ if (vars === null)
12
+ throw new Error(t("env.noPermission", { name: app.name }));
13
+ return { client, app, vars };
14
+ }
15
+ async function save(client, app, vars, restart) {
16
+ const wait = spinner(t("env.saving", { name: app.name }));
17
+ try {
18
+ await writeEnv(client, app._id, vars);
19
+ if (restart)
20
+ await powerApp(client, app._id, "restart").catch(() => powerApp(client, app._id, "start"));
21
+ }
22
+ finally {
23
+ wait.stop();
24
+ }
25
+ ui.ok(t(restart ? "env.savedRestarted" : "env.saved", { name: pc.bold(app.name), count: String(vars.length) }));
26
+ if (!restart)
27
+ ui.dim(t("env.restartHint", { name: app.name }));
28
+ }
29
+ /** `campos env [app] [--show]`: the keys, with the values hidden unless --show. */
30
+ export async function envList(apiUrl, query, options) {
31
+ const { app, vars } = await load(apiUrl, query);
32
+ if (options.json) {
33
+ console.log(JSON.stringify(options.show ? vars : vars.map(({ key }) => ({ key }))));
34
+ return 0;
35
+ }
36
+ if (vars.length === 0) {
37
+ ui.info(t("env.none", { name: app.name }));
38
+ return 0;
39
+ }
40
+ const width = Math.max(...vars.map(({ key }) => key.length));
41
+ ui.info(pc.bold(app.name));
42
+ for (const { key, value } of vars)
43
+ ui.info(` ${key.padEnd(width)} ${options.show ? value : pc.dim(maskValue(value))}`);
44
+ if (!options.show) {
45
+ ui.blank();
46
+ ui.dim(t("env.showHint"));
47
+ }
48
+ return 0;
49
+ }
50
+ /** `campos env set KEY=value [KEY2=value2...]`. */
51
+ export async function envSet(apiUrl, assignments, options) {
52
+ const changes = [];
53
+ for (const text of assignments) {
54
+ const parsed = parseAssignment(text);
55
+ if (!parsed) {
56
+ ui.fail(t("env.badAssignment", { text }));
57
+ return 1;
58
+ }
59
+ changes.push(parsed);
60
+ }
61
+ const { client, app, vars } = await load(apiUrl, options.app);
62
+ await save(client, app, mergeEnv(vars, changes), options.restart);
63
+ return 0;
64
+ }
65
+ /** `campos env unset KEY [KEY2...]`. */
66
+ export async function envUnset(apiUrl, keys, options) {
67
+ const { client, app, vars } = await load(apiUrl, options.app);
68
+ const missing = keys.filter((key) => !vars.some((item) => item.key === key));
69
+ if (missing.length === keys.length) {
70
+ ui.info(t("env.notFound", { keys: missing.join(", ") }));
71
+ return 1;
72
+ }
73
+ await save(client, app, vars.filter((item) => !keys.includes(item.key)), options.restart);
74
+ return 0;
75
+ }
76
+ /** `campos env pull [file]`: writes the application's variables to `.env` (asks before replacing a different file). */
77
+ export async function envPull(apiUrl, file, options) {
78
+ const { app, vars } = await load(apiUrl, options.app);
79
+ const target = path.resolve(file ?? ".env");
80
+ const text = toDotEnv(vars);
81
+ if (fs.existsSync(target) && fs.readFileSync(target, "utf8") !== text && !options.force) {
82
+ ui.fail(t("env.pullExists", { file: path.basename(target) }));
83
+ return 1;
84
+ }
85
+ fs.writeFileSync(target, text);
86
+ ui.ok(t("env.pulled", { count: String(vars.length), name: app.name, file: path.basename(target) }));
87
+ return 0;
88
+ }
89
+ /**
90
+ * `campos env push [file]`: sends a `.env`. By default it merges (keys in the file are set, the others stay);
91
+ * `--replace` makes the application's variables exactly the file's.
92
+ */
93
+ export async function envPush(apiUrl, file, options) {
94
+ const source = path.resolve(file ?? ".env");
95
+ if (!fs.existsSync(source)) {
96
+ ui.fail(t("env.fileMissing", { file: path.basename(source) }));
97
+ return 1;
98
+ }
99
+ const fromFile = parseDotEnv(fs.readFileSync(source, "utf8"));
100
+ const { client, app, vars } = await load(apiUrl, options.app);
101
+ await save(client, app, options.replace ? fromFile : mergeEnv(vars, fromFile), options.restart);
102
+ return 0;
103
+ }
@@ -0,0 +1,101 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { formatBytes } from "../core/apps.js";
4
+ import { deleteRemote, downloadRemote, extractZip, listRemote, remotePath, zipFile } from "../core/files.js";
5
+ import { t } from "../core/i18n.js";
6
+ import { pc, spinner, ui } from "../core/output.js";
7
+ import { createExcluder, DEFAULT_IGNORE, readIgnoreFile, zipProject } from "../core/project.js";
8
+ import { confirm } from "../core/prompt.js";
9
+ import { findApp } from "./apps.js";
10
+ /** `campos files [path]`: what is in a folder of the application (folders first). */
11
+ export async function filesList(apiUrl, dir, options) {
12
+ const { client, app } = await findApp(apiUrl, options.app);
13
+ const target = remotePath(dir);
14
+ const result = await listRemote(client, app._id, target);
15
+ if ("content" in result) {
16
+ process.stdout.write(result.content.endsWith("\n") ? result.content : `${result.content}\n`);
17
+ return 0;
18
+ }
19
+ const entries = [...result].sort((a, b) => Number(b.isDirectory) - Number(a.isDirectory) || a.name.localeCompare(b.name));
20
+ if (options.json) {
21
+ console.log(JSON.stringify(entries));
22
+ return 0;
23
+ }
24
+ ui.info(`${pc.bold(app.name)}${pc.dim(target)}`);
25
+ if (entries.length === 0)
26
+ ui.dim(` ${t("files.empty")}`);
27
+ for (const entry of entries) {
28
+ const size = entry.isDirectory ? "" : formatBytes(entry.size ?? 0);
29
+ ui.info(` ${entry.isDirectory ? pc.cyan(`${entry.name}/`) : entry.name}${size ? pc.dim(` ${size}`) : ""}`);
30
+ }
31
+ return 0;
32
+ }
33
+ /** `campos files cat <path>`: a text file of the application on screen. */
34
+ export async function filesCat(apiUrl, file, options) {
35
+ const { client, app } = await findApp(apiUrl, options.app);
36
+ const result = await listRemote(client, app._id, remotePath(file));
37
+ if (!("content" in result)) {
38
+ ui.fail(t("files.isFolder", { path: remotePath(file) }));
39
+ return 1;
40
+ }
41
+ process.stdout.write(result.content.endsWith("\n") ? result.content : `${result.content}\n`);
42
+ return 0;
43
+ }
44
+ /** `campos files pull <path> [destination]`: a file or folder of the application, into a local folder. */
45
+ export async function filesPull(apiUrl, source, destination, options) {
46
+ const { client, app } = await findApp(apiUrl, options.app);
47
+ const target = path.resolve(destination ?? ".");
48
+ const wait = spinner(t("files.downloading", { path: remotePath(source), name: app.name }));
49
+ let written;
50
+ try {
51
+ written = extractZip(await downloadRemote(client, app._id, remotePath(source)), target);
52
+ }
53
+ finally {
54
+ wait.stop();
55
+ }
56
+ ui.ok(t("files.pulled", { count: String(written.length), folder: path.relative(process.cwd(), target) || "." }));
57
+ return 0;
58
+ }
59
+ /** `campos files push <local> [folder]`: a local file or folder into a folder of the application (default: the root). */
60
+ export async function filesPush(apiUrl, source, destination, options) {
61
+ const local = path.resolve(source);
62
+ if (!fs.existsSync(local)) {
63
+ ui.fail(t("env.fileMissing", { file: source }));
64
+ return 1;
65
+ }
66
+ const { client, app } = await findApp(apiUrl, options.app);
67
+ const isFolder = fs.statSync(local).isDirectory();
68
+ const zip = isFolder
69
+ ? (await zipProject(local, createExcluder([...DEFAULT_IGNORE, ...readIgnoreFile(local)]))).zip
70
+ : await zipFile(local);
71
+ const target = remotePath(destination);
72
+ const wait = spinner(t("files.uploading", { path: target, name: app.name }));
73
+ try {
74
+ await client.uploadZip(`/v1/apps/${encodeURIComponent(app._id)}/upload?path=${encodeURIComponent(target)}&restart=${options.restart === true}`, zip);
75
+ }
76
+ finally {
77
+ wait.stop();
78
+ }
79
+ ui.ok(t("files.pushed", { source: path.basename(local), path: target, name: app.name }));
80
+ return 0;
81
+ }
82
+ /** `campos files rm <path...>`: asks first, unless --yes. */
83
+ export async function filesRemove(apiUrl, targets, options) {
84
+ const { client, app } = await findApp(apiUrl, options.app);
85
+ const paths = targets.map(remotePath).filter((item) => item !== "/");
86
+ if (paths.length === 0) {
87
+ ui.fail(t("files.noRoot"));
88
+ return 1;
89
+ }
90
+ if (!options.yes && !(await confirm(t("files.confirmRemove", { list: paths.join(", "), name: app.name })))) {
91
+ ui.info(t("error.cancelled"));
92
+ return 1;
93
+ }
94
+ const result = await deleteRemote(client, app._id, paths);
95
+ const failed = result?.failed ?? [];
96
+ if (failed.length)
97
+ ui.fail(t("files.removeFailed", { list: failed.join(", ") }));
98
+ if (failed.length < paths.length)
99
+ ui.ok(t("files.removed", { count: String(paths.length - failed.length), name: app.name }));
100
+ return failed.length ? 1 : 0;
101
+ }