@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.
- package/README.md +153 -2
- package/dist/commands/apps.js +197 -0
- package/dist/commands/auth.js +194 -0
- package/dist/commands/completion.js +94 -0
- package/dist/commands/create.js +220 -0
- package/dist/commands/dashboard.js +44 -0
- package/dist/commands/db.js +85 -0
- package/dist/commands/deploy.js +104 -0
- package/dist/commands/env.js +103 -0
- package/dist/commands/files.js +101 -0
- package/dist/commands/lang.js +34 -0
- package/dist/commands/manage.js +121 -0
- package/dist/commands/teams.js +127 -0
- package/dist/commands/utils.js +102 -0
- package/dist/core/api.js +157 -0
- package/dist/core/apiErrors.js +38 -0
- package/dist/core/apps.js +98 -0
- package/dist/core/config.js +34 -0
- package/dist/core/context.js +43 -0
- package/dist/core/credentials.js +90 -0
- package/dist/core/databases.js +53 -0
- package/dist/core/detect.js +75 -0
- package/dist/core/deviceLogin.js +49 -0
- package/dist/core/env.js +71 -0
- package/dist/core/files.js +51 -0
- package/dist/core/help.js +193 -0
- package/dist/core/i18n.js +581 -0
- package/dist/core/logs.js +87 -0
- package/dist/core/output.js +27 -0
- package/dist/core/project.js +119 -0
- package/dist/core/prompt.js +29 -0
- package/dist/core/session.js +21 -0
- package/dist/core/suggest.js +28 -0
- package/dist/core/teams.js +39 -0
- package/dist/core/update.js +48 -0
- package/dist/index.js +223 -0
- package/dist/tui/App.js +400 -0
- package/dist/tui/App.test.js +189 -0
- package/dist/tui/Picker.js +87 -0
- package/dist/tui/clickable.js +64 -0
- package/dist/tui/mouse.js +65 -0
- package/dist/tui/run.js +27 -0
- package/package.json +58 -4
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { storeLanguage } from "../core/context.js";
|
|
2
|
+
import { currentLanguage, t } from "../core/i18n.js";
|
|
3
|
+
import { isInteractive } from "../core/prompt.js";
|
|
4
|
+
import { ui } from "../core/output.js";
|
|
5
|
+
/** `campos lang [pt|en]`: shows the language, or changes it (a list with the arrow keys when none is given). */
|
|
6
|
+
export async function lang(value) {
|
|
7
|
+
let chosen = null;
|
|
8
|
+
if (value) {
|
|
9
|
+
const wanted = value.toLowerCase();
|
|
10
|
+
chosen = wanted.startsWith("pt") || wanted === "portugues" || wanted === "português" ? "pt" : wanted.startsWith("en") || wanted === "ingles" || wanted === "inglês" ? "en" : null;
|
|
11
|
+
if (!chosen) {
|
|
12
|
+
ui.fail(t("lang.unknown"));
|
|
13
|
+
return 1;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
else if (isInteractive()) {
|
|
17
|
+
const { pick } = await import("../tui/Picker.js");
|
|
18
|
+
const current = currentLanguage();
|
|
19
|
+
const options = [{ label: "Português", value: "pt" }, { label: "English", value: "en" }];
|
|
20
|
+
chosen = await pick(t("lang.choose"), current === "pt" ? options : options.reverse(), { filter: false });
|
|
21
|
+
if (!chosen)
|
|
22
|
+
return 130;
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
ui.info(t("lang.current", { lang: t(`lang.${currentLanguage()}`) }));
|
|
26
|
+
return 0;
|
|
27
|
+
}
|
|
28
|
+
storeLanguage(chosen);
|
|
29
|
+
// Said in the new language, as the next commands will be.
|
|
30
|
+
ui.ok(chosen === "pt" ? "Pronto: a CLI agora fala português." : "Done: the CLI now speaks English.");
|
|
31
|
+
if (process.env.CAMPOS_LANG)
|
|
32
|
+
ui.dim(t("lang.envWins"));
|
|
33
|
+
return 0;
|
|
34
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { randomInt } from "node:crypto";
|
|
2
|
+
import { formatMB } from "../core/apps.js";
|
|
3
|
+
import { listDbs, resolveDb } from "../core/databases.js";
|
|
4
|
+
import { t } from "../core/i18n.js";
|
|
5
|
+
import { pc, spinner, ui } from "../core/output.js";
|
|
6
|
+
import { signedInContext } from "../core/session.js";
|
|
7
|
+
import { findApp } from "./apps.js";
|
|
8
|
+
/** Changes settings of an application through `POST /v1/apps/:id/update`; most of them need a restart. */
|
|
9
|
+
async function updateApp(apiUrl, query, changes, done) {
|
|
10
|
+
const { client, app } = await findApp(apiUrl, query);
|
|
11
|
+
const wait = spinner(t("manage.saving", { name: app.name }));
|
|
12
|
+
try {
|
|
13
|
+
await client.post(`/v1/apps/${encodeURIComponent(app._id)}/update`, changes);
|
|
14
|
+
}
|
|
15
|
+
finally {
|
|
16
|
+
wait.stop();
|
|
17
|
+
}
|
|
18
|
+
ui.ok(done(app.name));
|
|
19
|
+
return app;
|
|
20
|
+
}
|
|
21
|
+
const parseMemory = (value) => {
|
|
22
|
+
const match = /^(\d+(?:\.\d+)?)\s*(gb|g|mb|m)?$/i.exec(value.trim());
|
|
23
|
+
if (!match)
|
|
24
|
+
return null;
|
|
25
|
+
const amount = Number(match[1]);
|
|
26
|
+
return Math.round(/^g/i.test(match[2] ?? "") ? amount * 1024 : amount);
|
|
27
|
+
};
|
|
28
|
+
/** `campos scale <memory> [--app]`: "512", "512mb", "1gb". */
|
|
29
|
+
export async function scale(apiUrl, memory, options) {
|
|
30
|
+
const memoryMB = parseMemory(memory);
|
|
31
|
+
if (!memoryMB || memoryMB < 128) {
|
|
32
|
+
ui.fail(t("create.badMemory"));
|
|
33
|
+
return 1;
|
|
34
|
+
}
|
|
35
|
+
const app = await updateApp(apiUrl, options.app, { memoryMB }, (name) => t("manage.scaled", { name: pc.bold(name), memory: formatMB(memoryMB) }));
|
|
36
|
+
ui.dim(t("env.restartHint", { name: app.name }));
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
/** `campos rename <new name> [--app]`. */
|
|
40
|
+
export async function rename(apiUrl, name, options) {
|
|
41
|
+
if (name.trim().length < 3) {
|
|
42
|
+
ui.fail(t("create.nameTooShort"));
|
|
43
|
+
return 1;
|
|
44
|
+
}
|
|
45
|
+
await updateApp(apiUrl, options.app, { appName: name.trim() }, (old) => t("manage.renamed", { old, name: pc.bold(name.trim()) }));
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
/** `campos autorestart on|off [--app]`: restart by itself when it crashes. */
|
|
49
|
+
export async function autorestart(apiUrl, value, options) {
|
|
50
|
+
const on = ["on", "sim", "yes", "true", "ligar", "1"].includes(value.toLowerCase());
|
|
51
|
+
const off = ["off", "nao", "não", "no", "false", "desligar", "0"].includes(value.toLowerCase());
|
|
52
|
+
if (!on && !off) {
|
|
53
|
+
ui.fail(t("manage.onOff"));
|
|
54
|
+
return 1;
|
|
55
|
+
}
|
|
56
|
+
await updateApp(apiUrl, options.app, { autoRestartEnabled: on }, (name) => t(on ? "manage.autorestartOn" : "manage.autorestartOff", { name: pc.bold(name) }));
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
/** A password that passes the control's strength check: 24 characters of letters, digits and a few symbols. */
|
|
60
|
+
export function strongPassword(length = 24) {
|
|
61
|
+
const sets = ["ABCDEFGHJKLMNPQRSTUVWXYZ", "abcdefghijkmnopqrstuvwxyz", "23456789", "-_.~"];
|
|
62
|
+
const all = sets.join("");
|
|
63
|
+
const chars = sets.map((set) => set[randomInt(set.length)]);
|
|
64
|
+
while (chars.length < length)
|
|
65
|
+
chars.push(all[randomInt(all.length)]);
|
|
66
|
+
for (let i = chars.length - 1; i > 0; i--) {
|
|
67
|
+
const j = randomInt(i + 1);
|
|
68
|
+
[chars[i], chars[j]] = [chars[j], chars[i]];
|
|
69
|
+
}
|
|
70
|
+
return chars.join("");
|
|
71
|
+
}
|
|
72
|
+
async function findDb(apiUrl, query) {
|
|
73
|
+
const { client, team } = await signedInContext(apiUrl);
|
|
74
|
+
return { client, db: resolveDb(await listDbs(client, team?.id), query) };
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* `campos db password <db> [--password <p>]`: sets a new password (a strong one is made when none is given)
|
|
78
|
+
* and shows it this once; the API never returns it again.
|
|
79
|
+
*/
|
|
80
|
+
export async function dbPassword(apiUrl, query, options) {
|
|
81
|
+
const { client, db } = await findDb(apiUrl, query);
|
|
82
|
+
const password = options.password ?? strongPassword();
|
|
83
|
+
const wait = spinner(t("manage.saving", { name: db.name }));
|
|
84
|
+
try {
|
|
85
|
+
await client.post(`/v1/databases/${encodeURIComponent(db._id)}/update-credentials`, { password });
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
wait.stop();
|
|
89
|
+
}
|
|
90
|
+
ui.ok(t("manage.passwordChanged", { name: pc.bold(db.name) }));
|
|
91
|
+
if (!options.password) {
|
|
92
|
+
ui.info(` ${pc.bold(password)}`);
|
|
93
|
+
ui.dim(t("manage.passwordOnce"));
|
|
94
|
+
}
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
/** `campos db scale <db> <memory>` and `campos db rename <db> <name>`. */
|
|
98
|
+
export async function dbUpdate(apiUrl, query, changes) {
|
|
99
|
+
const { client, db } = await findDb(apiUrl, query);
|
|
100
|
+
const body = {};
|
|
101
|
+
if (changes.memory !== undefined) {
|
|
102
|
+
const memoryMB = parseMemory(changes.memory);
|
|
103
|
+
if (!memoryMB || memoryMB < 128) {
|
|
104
|
+
ui.fail(t("create.badMemory"));
|
|
105
|
+
return 1;
|
|
106
|
+
}
|
|
107
|
+
body.memoryMB = memoryMB;
|
|
108
|
+
}
|
|
109
|
+
if (changes.name !== undefined)
|
|
110
|
+
body.name = changes.name.trim();
|
|
111
|
+
const wait = spinner(t("manage.saving", { name: db.name }));
|
|
112
|
+
try {
|
|
113
|
+
await client.request("PUT", `/v1/databases/${encodeURIComponent(db._id)}`, body);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
wait.stop();
|
|
117
|
+
}
|
|
118
|
+
ui.ok(body.memoryMB ? t("manage.scaled", { name: pc.bold(db.name), memory: formatMB(body.memoryMB) }) : t("manage.renamed", { old: db.name, name: pc.bold(String(body.name)) }));
|
|
119
|
+
return 0;
|
|
120
|
+
}
|
|
121
|
+
export { parseMemory };
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { fetchMe } from "../core/api.js";
|
|
2
|
+
import { storeTeam } from "../core/context.js";
|
|
3
|
+
import { plural, t } from "../core/i18n.js";
|
|
4
|
+
import { pc, ui } from "../core/output.js";
|
|
5
|
+
import { signedInClient, signedInContext } from "../core/session.js";
|
|
6
|
+
import { activeTeam, createTeam, getTeam, inviteToTeam, isOwner, listTeams, meansPersonal, personOf, resolveTeam } from "../core/teams.js";
|
|
7
|
+
const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
8
|
+
/** "3 pessoas · 1 app · 0 bancos". */
|
|
9
|
+
const teamCounts = (team) => [
|
|
10
|
+
plural((team.members?.length ?? 0) + 1, "team.person", "team.people"),
|
|
11
|
+
plural(team.applicationsCount ?? 0, "team.app", "team.apps"),
|
|
12
|
+
plural(team.databaseInstancesCount ?? 0, "team.db", "team.dbs"),
|
|
13
|
+
].join(" · ");
|
|
14
|
+
/** `campos teams`: every team, the active one marked. */
|
|
15
|
+
export async function teamsList(apiUrl, options) {
|
|
16
|
+
const { client, team: active } = await signedInContext(apiUrl);
|
|
17
|
+
const [teams, { user }] = await Promise.all([listTeams(client), fetchMe(client)]);
|
|
18
|
+
if (options.json) {
|
|
19
|
+
console.log(JSON.stringify({ active: active?.id ?? null, teams: teams.map((team) => ({ id: team._id, name: team.name, owner: isOwner(team, user._id), members: (team.members?.length ?? 0) + 1, applications: team.applicationsCount ?? 0, databases: team.databaseInstancesCount ?? 0 })) }));
|
|
20
|
+
return 0;
|
|
21
|
+
}
|
|
22
|
+
const mark = (isActive) => (isActive ? pc.green("●") : pc.dim("○"));
|
|
23
|
+
ui.info(`${mark(!active)} ${pc.bold(t("team.personal"))} ${pc.dim(user.email)}`);
|
|
24
|
+
for (const team of teams) {
|
|
25
|
+
const role = isOwner(team, user._id) ? t("team.owner") : t("team.member");
|
|
26
|
+
const counts = teamCounts(team);
|
|
27
|
+
ui.info(`${mark(active?.id === team._id)} ${pc.bold(team.name)} ${pc.dim(`${role} · ${counts}`)}`);
|
|
28
|
+
}
|
|
29
|
+
ui.blank();
|
|
30
|
+
ui.dim(t("team.hint"));
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
/** `campos team`: which context the commands are working in. */
|
|
34
|
+
export async function teamCurrent(apiUrl) {
|
|
35
|
+
const { team } = await signedInContext(apiUrl);
|
|
36
|
+
ui.info(team ? t("team.current", { team: pc.bold(team.name) }) : t("team.currentPersonal"));
|
|
37
|
+
ui.dim(t("team.hint"));
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* `campos team use [team]`: from now on, the commands and the dashboard work in that team. With no name, a list
|
|
42
|
+
* to choose from (the personal account first). `pessoal` goes back to the personal account.
|
|
43
|
+
*/
|
|
44
|
+
export async function teamUse(apiUrl, query) {
|
|
45
|
+
const client = await signedInClient(apiUrl);
|
|
46
|
+
const teams = await listTeams(client);
|
|
47
|
+
let chosen;
|
|
48
|
+
if (query) {
|
|
49
|
+
chosen = meansPersonal(query) ? null : resolveTeam(teams, query);
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
if (!interactive())
|
|
53
|
+
throw new Error(t("team.needsName"));
|
|
54
|
+
const current = await activeTeam(client, apiUrl);
|
|
55
|
+
const { pick } = await import("../tui/Picker.js");
|
|
56
|
+
const PERSONAL = "__personal__";
|
|
57
|
+
const value = await pick(t("team.choose"), [
|
|
58
|
+
{ label: t("team.personal"), detail: !current ? t("team.active") : undefined, value: PERSONAL },
|
|
59
|
+
...teams.map((team) => ({ label: team.name, detail: [current?.id === team._id ? t("team.active") : "", teamCounts(team)].filter(Boolean).join(" · "), value: team._id })),
|
|
60
|
+
]);
|
|
61
|
+
if (value === null) {
|
|
62
|
+
ui.info(t("error.cancelled"));
|
|
63
|
+
return 130;
|
|
64
|
+
}
|
|
65
|
+
chosen = value === PERSONAL ? null : teams.find((team) => team._id === value) ?? null;
|
|
66
|
+
}
|
|
67
|
+
storeTeam(apiUrl, chosen ? { id: chosen._id, name: chosen.name } : null);
|
|
68
|
+
ui.ok(chosen ? t("team.switched", { team: pc.bold(chosen.name) }) : t("team.switchedPersonal"));
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
async function teamFor(apiUrl, query) {
|
|
72
|
+
const { client, team } = await signedInContext(apiUrl);
|
|
73
|
+
if (query)
|
|
74
|
+
return { client, team: resolveTeam(await listTeams(client), query) };
|
|
75
|
+
if (!team)
|
|
76
|
+
throw new Error(t("team.noneActive"));
|
|
77
|
+
return { client, team: await getTeam(client, team.id) };
|
|
78
|
+
}
|
|
79
|
+
/** `campos team members [team]`: the owner, the members with their role, and the pending invites. */
|
|
80
|
+
export async function teamMembers(apiUrl, query, options) {
|
|
81
|
+
const { client, team: found } = await teamFor(apiUrl, query);
|
|
82
|
+
const team = await getTeam(client, found._id);
|
|
83
|
+
const roleName = (roleId) => team.roles?.find((role) => role._id === roleId)?.name;
|
|
84
|
+
if (options.json) {
|
|
85
|
+
console.log(JSON.stringify({ id: team._id, name: team.name, owner: personOf(team.owner), members: (team.members ?? []).map((member) => ({ ...personOf(member.user), role: roleName(member.roleId) ?? null })), invites: (team.invites ?? []).map((invite) => invite.email) }));
|
|
86
|
+
return 0;
|
|
87
|
+
}
|
|
88
|
+
const owner = personOf(team.owner);
|
|
89
|
+
ui.info(pc.bold(team.name));
|
|
90
|
+
ui.info(` ${pc.yellow("★")} ${owner?.name ?? "—"} ${pc.dim(owner?.email ?? "")} ${pc.dim(t("team.owner"))}`);
|
|
91
|
+
for (const member of team.members ?? []) {
|
|
92
|
+
const person = personOf(member.user);
|
|
93
|
+
ui.info(` ${pc.dim("•")} ${person?.name ?? "—"} ${pc.dim(person?.email ?? "")} ${pc.dim(roleName(member.roleId) ?? t("team.member"))}`);
|
|
94
|
+
}
|
|
95
|
+
for (const invite of team.invites ?? []) {
|
|
96
|
+
ui.info(` ${pc.dim("◌")} ${pc.dim(invite.email)} ${pc.dim(t("team.invited"))}`);
|
|
97
|
+
}
|
|
98
|
+
return 0;
|
|
99
|
+
}
|
|
100
|
+
/** `campos team invite <email> [--role <name>] [--team <team>]`. */
|
|
101
|
+
export async function teamInvite(apiUrl, email, options) {
|
|
102
|
+
const { client, team: found } = await teamFor(apiUrl, options.team);
|
|
103
|
+
const team = await getTeam(client, found._id);
|
|
104
|
+
let roleId;
|
|
105
|
+
if (options.role) {
|
|
106
|
+
const role = team.roles?.find((item) => item.name.toLowerCase() === options.role.toLowerCase());
|
|
107
|
+
if (!role) {
|
|
108
|
+
ui.fail(t("team.noRole", { role: options.role, list: (team.roles ?? []).map((item) => item.name).join(", ") || "—" }));
|
|
109
|
+
return 1;
|
|
110
|
+
}
|
|
111
|
+
roleId = role._id;
|
|
112
|
+
}
|
|
113
|
+
await inviteToTeam(client, team._id, email.trim(), roleId);
|
|
114
|
+
ui.ok(t("team.invitedDone", { email: pc.bold(email.trim()), team: team.name }));
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
/** `campos team create <name>`: makes the team and switches to it. */
|
|
118
|
+
export async function teamCreate(apiUrl, name, options) {
|
|
119
|
+
const client = await signedInClient(apiUrl);
|
|
120
|
+
const created = await createTeam(client, name.trim());
|
|
121
|
+
ui.ok(t("team.created", { team: pc.bold(created?.name ?? name) }));
|
|
122
|
+
if (options.use !== false && created?._id) {
|
|
123
|
+
storeTeam(apiUrl, { id: created._id, name: created.name ?? name });
|
|
124
|
+
ui.dim(t("team.switched", { team: created.name ?? name }));
|
|
125
|
+
}
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { ApiClient, ApiError, CLI_VERSION, fetchMe, NetworkError } from "../core/api.js";
|
|
2
|
+
import { appAddress } from "../core/apps.js";
|
|
3
|
+
import { configDir } from "../core/config.js";
|
|
4
|
+
import { readToken } from "../core/credentials.js";
|
|
5
|
+
import { t } from "../core/i18n.js";
|
|
6
|
+
import { pc, ui } from "../core/output.js";
|
|
7
|
+
import { findProject } from "../core/project.js";
|
|
8
|
+
import { activeTeam } from "../core/teams.js";
|
|
9
|
+
import { findApp } from "./apps.js";
|
|
10
|
+
/** The site that goes with an API address: CAMPOS_SITE_URL, the local site next to a local control, or production. */
|
|
11
|
+
export function siteUrl(apiUrl, env = process.env) {
|
|
12
|
+
if (env.CAMPOS_SITE_URL)
|
|
13
|
+
return env.CAMPOS_SITE_URL.replace(/\/+$/, "");
|
|
14
|
+
const url = new URL(apiUrl);
|
|
15
|
+
if (["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
|
|
16
|
+
return `${url.protocol}//${url.hostname}:3000`;
|
|
17
|
+
return "https://www.camposcloud.com";
|
|
18
|
+
}
|
|
19
|
+
async function openInBrowser(url) {
|
|
20
|
+
ui.dim(url);
|
|
21
|
+
try {
|
|
22
|
+
const { default: open } = await import("open");
|
|
23
|
+
await open(url);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
// the address is on screen
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** `campos open [app]`: the application's page in the dashboard; with no application anywhere, the dashboard. */
|
|
30
|
+
export async function openDashboard(apiUrl, query) {
|
|
31
|
+
const base = siteUrl(apiUrl);
|
|
32
|
+
const project = findProject();
|
|
33
|
+
if (!query && !(project && (!project.apiUrl || project.apiUrl === apiUrl))) {
|
|
34
|
+
await openInBrowser(`${base}/dashboard/applications`);
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
const { app } = await findApp(apiUrl, query);
|
|
38
|
+
const team = app.teamId ? `?team=${encodeURIComponent(String(app.teamId))}` : "";
|
|
39
|
+
ui.info(t("open.opening", { name: pc.bold(app.name) }));
|
|
40
|
+
await openInBrowser(`${base}/dashboard/applications/${encodeURIComponent(app._id)}${team}`);
|
|
41
|
+
return 0;
|
|
42
|
+
}
|
|
43
|
+
/** `campos url [app] [--open]`: the application's public address. */
|
|
44
|
+
export async function appUrl(apiUrl, query, options) {
|
|
45
|
+
const { app } = await findApp(apiUrl, query);
|
|
46
|
+
const address = appAddress(app);
|
|
47
|
+
if (!address) {
|
|
48
|
+
ui.fail(t("url.none", { name: app.name }));
|
|
49
|
+
return 1;
|
|
50
|
+
}
|
|
51
|
+
if (options.open)
|
|
52
|
+
await openInBrowser(`https://${address}`);
|
|
53
|
+
else
|
|
54
|
+
console.log(`https://${address}`);
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
/** `campos doctor`: checks everything the CLI depends on, one line each. */
|
|
58
|
+
export async function doctor(apiUrl) {
|
|
59
|
+
let problems = 0;
|
|
60
|
+
const line = (ok, label, detail) => {
|
|
61
|
+
if (ok === false)
|
|
62
|
+
problems++;
|
|
63
|
+
const mark = ok === null ? pc.dim("•") : ok ? pc.green("✓") : pc.red("✗");
|
|
64
|
+
ui.info(`${mark} ${label.padEnd(18)} ${pc.dim(detail)}`);
|
|
65
|
+
};
|
|
66
|
+
line(null, t("doctor.version"), `campos ${CLI_VERSION} · Node ${process.versions.node} · ${process.platform}`);
|
|
67
|
+
line(null, t("doctor.config"), configDir());
|
|
68
|
+
let reachable = false;
|
|
69
|
+
try {
|
|
70
|
+
const started = Date.now();
|
|
71
|
+
const response = await fetch(`${apiUrl}/`, { signal: AbortSignal.timeout(8000) });
|
|
72
|
+
reachable = response.status < 500;
|
|
73
|
+
line(reachable, t("doctor.api"), `${apiUrl} · ${Date.now() - started} ms`);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
line(false, t("doctor.api"), t("error.network", { url: apiUrl }));
|
|
77
|
+
}
|
|
78
|
+
const stored = await readToken(apiUrl);
|
|
79
|
+
if (!stored) {
|
|
80
|
+
line(false, t("doctor.login"), t("error.notSignedIn"));
|
|
81
|
+
}
|
|
82
|
+
else if (reachable) {
|
|
83
|
+
try {
|
|
84
|
+
const client = new ApiClient(apiUrl, stored.token);
|
|
85
|
+
const { user } = await fetchMe(client);
|
|
86
|
+
line(true, t("doctor.login"), `${user.email} · ${t(`doctor.via.${stored.source}`)}`);
|
|
87
|
+
const team = await activeTeam(client, apiUrl).catch(() => null);
|
|
88
|
+
line(null, t("doctor.team"), team ? team.name : t("team.personal"));
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
line(false, t("doctor.login"), error instanceof ApiError && error.status === 401 ? t("error.session") : error instanceof NetworkError ? t("error.network", { url: apiUrl }) : String(error.message));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const project = findProject();
|
|
95
|
+
line(null, t("doctor.folder"), project ? t("doctor.linked", { name: project.name }) : t("link.none"));
|
|
96
|
+
ui.blank();
|
|
97
|
+
if (problems === 0)
|
|
98
|
+
ui.ok(t("doctor.allGood"));
|
|
99
|
+
else
|
|
100
|
+
ui.fail(t("doctor.problems", { count: String(problems) }));
|
|
101
|
+
return problems ? 1 : 0;
|
|
102
|
+
}
|
package/dist/core/api.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
const pkg = createRequire(import.meta.url)("../../package.json");
|
|
3
|
+
export const CLI_VERSION = pkg.version;
|
|
4
|
+
/** An answer of the API that was not a success, with the status and the API's own error text. */
|
|
5
|
+
export class ApiError extends Error {
|
|
6
|
+
status;
|
|
7
|
+
code;
|
|
8
|
+
constructor(status, code, message) {
|
|
9
|
+
super(message || code);
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.code = code;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** The API could not be reached at all (offline, wrong address, control down). */
|
|
15
|
+
export class NetworkError extends Error {
|
|
16
|
+
url;
|
|
17
|
+
constructor(url, cause) {
|
|
18
|
+
super(`Could not reach ${url}`, { cause });
|
|
19
|
+
this.url = url;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export class ApiClient {
|
|
23
|
+
baseUrl;
|
|
24
|
+
token;
|
|
25
|
+
fetchImpl;
|
|
26
|
+
constructor(baseUrl, token, fetchImpl = fetch) {
|
|
27
|
+
this.baseUrl = baseUrl;
|
|
28
|
+
this.token = token;
|
|
29
|
+
this.fetchImpl = fetchImpl;
|
|
30
|
+
}
|
|
31
|
+
async request(method, path, body) {
|
|
32
|
+
const url = `${this.baseUrl}${path}`;
|
|
33
|
+
let response;
|
|
34
|
+
try {
|
|
35
|
+
response = await this.fetchImpl(url, {
|
|
36
|
+
method,
|
|
37
|
+
headers: {
|
|
38
|
+
"content-type": "application/json",
|
|
39
|
+
"user-agent": `campos-cli/${CLI_VERSION}`,
|
|
40
|
+
...(this.token ? { authorization: `Bearer ${this.token}` } : {}),
|
|
41
|
+
},
|
|
42
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
43
|
+
signal: AbortSignal.timeout(30_000),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
throw new NetworkError(this.baseUrl, error);
|
|
48
|
+
}
|
|
49
|
+
const text = await response.text();
|
|
50
|
+
let data = undefined;
|
|
51
|
+
try {
|
|
52
|
+
data = text ? JSON.parse(text) : undefined;
|
|
53
|
+
}
|
|
54
|
+
catch { /* not JSON */ }
|
|
55
|
+
if (!response.ok) {
|
|
56
|
+
const code = typeof data?.error === "string" ? data.error : `http_${response.status}`;
|
|
57
|
+
throw new ApiError(response.status, code, typeof data?.error === "string" ? data.error : text.slice(0, 200));
|
|
58
|
+
}
|
|
59
|
+
return data;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A long-lived GET (the live console): no timeout, ended by `signal`. Errors are thrown like `request`'s;
|
|
63
|
+
* on success the caller reads the body.
|
|
64
|
+
*/
|
|
65
|
+
async stream(path, signal) {
|
|
66
|
+
let response;
|
|
67
|
+
try {
|
|
68
|
+
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
69
|
+
headers: {
|
|
70
|
+
accept: "text/event-stream",
|
|
71
|
+
"user-agent": `campos-cli/${CLI_VERSION}`,
|
|
72
|
+
...(this.token ? { authorization: `Bearer ${this.token}` } : {}),
|
|
73
|
+
},
|
|
74
|
+
signal,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (signal.aborted)
|
|
79
|
+
throw error;
|
|
80
|
+
throw new NetworkError(this.baseUrl, error);
|
|
81
|
+
}
|
|
82
|
+
if (!response.ok) {
|
|
83
|
+
const text = await response.text();
|
|
84
|
+
let message;
|
|
85
|
+
try {
|
|
86
|
+
message = JSON.parse(text)?.error;
|
|
87
|
+
}
|
|
88
|
+
catch { /* not JSON */ }
|
|
89
|
+
throw new ApiError(response.status, message || `http_${response.status}`, message || text.slice(0, 200));
|
|
90
|
+
}
|
|
91
|
+
return response;
|
|
92
|
+
}
|
|
93
|
+
/** Sends a .zip as the multipart field `file` (what `POST /v1/apps/:id/upload` expects). */
|
|
94
|
+
uploadZip(path, zip, filename = "project.zip") {
|
|
95
|
+
return this.postForm(path, {}, zip, filename);
|
|
96
|
+
}
|
|
97
|
+
/** A multipart POST: text fields plus a .zip in the field `file` (creating an application, uploading files). */
|
|
98
|
+
async postForm(path, fields, zip, filename = "project.zip") {
|
|
99
|
+
const form = new FormData();
|
|
100
|
+
for (const [key, value] of Object.entries(fields))
|
|
101
|
+
form.append(key, value);
|
|
102
|
+
form.append("file", new Blob([new Uint8Array(zip.buffer, zip.byteOffset, zip.byteLength)], { type: "application/zip" }), filename);
|
|
103
|
+
let response;
|
|
104
|
+
try {
|
|
105
|
+
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
106
|
+
method: "POST",
|
|
107
|
+
// fetch sets the multipart boundary itself: no content-type here.
|
|
108
|
+
headers: { "user-agent": `campos-cli/${CLI_VERSION}`, ...(this.token ? { authorization: `Bearer ${this.token}` } : {}) },
|
|
109
|
+
body: form,
|
|
110
|
+
signal: AbortSignal.timeout(180_000),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
throw new NetworkError(this.baseUrl, error);
|
|
115
|
+
}
|
|
116
|
+
const text = await response.text();
|
|
117
|
+
let data = undefined;
|
|
118
|
+
try {
|
|
119
|
+
data = text ? JSON.parse(text) : undefined;
|
|
120
|
+
}
|
|
121
|
+
catch { /* not JSON */ }
|
|
122
|
+
if (!response.ok) {
|
|
123
|
+
const message = typeof data?.error === "string" ? data.error : text.slice(0, 200);
|
|
124
|
+
throw new ApiError(response.status, typeof data?.error === "string" ? data.error : `http_${response.status}`, message);
|
|
125
|
+
}
|
|
126
|
+
return data;
|
|
127
|
+
}
|
|
128
|
+
/** A binary answer (a .zip download), as a Buffer. */
|
|
129
|
+
async getBuffer(path) {
|
|
130
|
+
let response;
|
|
131
|
+
try {
|
|
132
|
+
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
133
|
+
headers: { "user-agent": `campos-cli/${CLI_VERSION}`, ...(this.token ? { authorization: `Bearer ${this.token}` } : {}) },
|
|
134
|
+
signal: AbortSignal.timeout(300_000),
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
throw new NetworkError(this.baseUrl, error);
|
|
139
|
+
}
|
|
140
|
+
if (!response.ok) {
|
|
141
|
+
const text = await response.text();
|
|
142
|
+
let message;
|
|
143
|
+
try {
|
|
144
|
+
message = JSON.parse(text)?.error;
|
|
145
|
+
}
|
|
146
|
+
catch { /* not JSON */ }
|
|
147
|
+
throw new ApiError(response.status, message || `http_${response.status}`, message || text.slice(0, 200));
|
|
148
|
+
}
|
|
149
|
+
return Buffer.from(await response.arrayBuffer());
|
|
150
|
+
}
|
|
151
|
+
get(path) { return this.request("GET", path); }
|
|
152
|
+
delete(path, body) { return this.request("DELETE", path, body); }
|
|
153
|
+
post(path, body) { return this.request("POST", path, body ?? {}); }
|
|
154
|
+
}
|
|
155
|
+
export async function fetchMe(client) {
|
|
156
|
+
return client.get("/v1/users/@me");
|
|
157
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { currentLanguage } from "./i18n.js";
|
|
2
|
+
/**
|
|
3
|
+
* The control answers in English. The messages it is known to send are shown in Portuguese when the CLI
|
|
4
|
+
* speaks Portuguese; anything else is shown as it came.
|
|
5
|
+
*/
|
|
6
|
+
const PT = [
|
|
7
|
+
[/^The application's container was not found on its server\. Please contact support\.$/, "O contêiner da aplicação não foi encontrado no servidor dela. Fale com o suporte."],
|
|
8
|
+
[/^The application cannot do this in its current state\. Wait a moment and try again\.$/, "A aplicação não pode fazer isso no estado em que está. Espere um pouco e tente de novo."],
|
|
9
|
+
[/^The console of this application is not available right now\. Try again in a few seconds\.$/, "O console desta aplicação não está disponível agora. Tente de novo em alguns segundos."],
|
|
10
|
+
[/^The connection to the server running the application was lost\. Reconnect in a few seconds\.$/, "A conexão com o servidor da aplicação caiu. Reconecte em alguns segundos."],
|
|
11
|
+
[/^Application not found or you do not have permission to access it\.$/, "Aplicação não encontrada, ou sua conta não tem acesso a ela."],
|
|
12
|
+
[/^The owner of this application does not have an active plan\.$/, "O dono desta aplicação não tem um plano ativo."],
|
|
13
|
+
[/^this application has status (\w+), it cannot be (?:restarted|started|stopped) at the moment/i, (m) => `A aplicação está com o status "${m[1]}" e não pode fazer isso agora. Tente de novo mais tarde.`],
|
|
14
|
+
[/^This application does not have a container yet\.$/, "Esta aplicação ainda não tem contêiner."],
|
|
15
|
+
[/^Internal server error\. Please try again later\.$/i, "Erro no servidor. Tente de novo mais tarde."],
|
|
16
|
+
[/^CLI session expired or ended\. Run "campos login" again\.$/, "Sua sessão da CLI acabou. Rode campos login de novo."],
|
|
17
|
+
[/^Invalid, expired or revoked token\.$/, "Token inválido, vencido ou revogado."],
|
|
18
|
+
[/^Too many requests, please try again later$/i, "Muitas requisições. Espere um pouco e tente de novo."],
|
|
19
|
+
[/^You do not have permission to create applications in this team\.$/, "Você não tem permissão para criar aplicações neste time."],
|
|
20
|
+
[/^The minimum memory per project is (\d+) MB/, (m) => `A memória mínima por projeto é ${m[1]} MB.`],
|
|
21
|
+
[/^(?:User|Team owner) does not have an active plan\.$/, "Não há um plano ativo para isso. Veja os planos no painel."],
|
|
22
|
+
[/^Team not found or you are not a member of this team\.$/, "Time não encontrado, ou você não faz parte dele."],
|
|
23
|
+
[/^You already have a team with this name\.$/, "Você já tem um time com esse nome."],
|
|
24
|
+
[/^You need to have an active subscription to create a team\.$/, "Para criar um time, você precisa de uma assinatura ativa."],
|
|
25
|
+
[/^You cannot create more than (\d+) teams\.$/, (m) => `Você não pode criar mais de ${m[1]} times.`],
|
|
26
|
+
[/^Developer token not found or invalid$|^Invalid developer token$|^Invalid developer token format$/, "Token de desenvolvedor inválido."],
|
|
27
|
+
[/^Account not found$/, "Conta não encontrada."],
|
|
28
|
+
];
|
|
29
|
+
export function localizeServerMessage(message) {
|
|
30
|
+
if (currentLanguage() !== "pt")
|
|
31
|
+
return message;
|
|
32
|
+
for (const [pattern, translation] of PT) {
|
|
33
|
+
const match = message.match(pattern);
|
|
34
|
+
if (match)
|
|
35
|
+
return typeof translation === "string" ? translation : translation(match);
|
|
36
|
+
}
|
|
37
|
+
return message;
|
|
38
|
+
}
|