@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
package/README.md CHANGED
@@ -1,3 +1,154 @@
1
- # Temporary Holding Version
1
+ # Campos CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Campos Cloud no terminal: `campos`.
4
+
5
+ ```sh
6
+ campos login # conecta a CLI à sua conta (código no navegador)
7
+ campos # abre o painel: setas, Enter, Esc
8
+ campos --help # todos os comandos
9
+ ```
10
+
11
+ ## Painel
12
+
13
+ Rode `campos` sem nada depois. Abre em tela cheia, com as abas **Aplicações**, **Bancos** e **Conta**, e o
14
+ time ativo no topo. Dá para fazer tudo só com as setas:
15
+
16
+ - **← →** trocam de aba, **↑ ↓** escolhem, **Enter** abre, **Esc** volta (na lista, sai).
17
+ - **t** troca de time (conta pessoal ou um dos seus times).
18
+ - Dentro de uma aplicação, um menu: reiniciar ou ligar, console, variáveis de ambiente, abrir o site, abrir
19
+ no painel, desligar (pergunta antes). Nos bancos: string de conexão e o mesmo menu de ligar e desligar.
20
+ - No console: **↑ ↓ PgUp PgDn** rolam, **End** volta a seguir ao vivo. Nas variáveis: **v** mostra os valores.
21
+ - Atalhos: **r** reinicia (ou liga), **l** abre o console.
22
+ - **Mouse:** clique nas linhas, nas abas, no time e nos itens do menu; a rodinha rola.
23
+
24
+ ## Do zero ao ar
25
+
26
+ ```sh
27
+ cd minha-app
28
+ campos create # pergunta nome, ambiente, arquivo principal, memória, endereço e onde criar
29
+ campos logs -f # console ao vivo
30
+ # … mudanças …
31
+ campos deploy # envia a pasta e reinicia
32
+ ```
33
+
34
+ O `create` já sugere as respostas a partir da pasta (Node.js, Bun ou Python, o arquivo principal, o
35
+ `camposcloud.config`), oferece enviar as variáveis do `.env` e deixa a pasta ligada à aplicação nova. Para
36
+ uma aplicação que já existe, ligue a pasta com `campos link`.
37
+
38
+ ## Comandos
39
+
40
+ `[app]` é o nome (sem diferenciar maiúsculas), um começo único do nome ou o id. Sem nome, vale a aplicação
41
+ ligada à pasta; fora de uma pasta ligada, a CLI mostra a lista para escolher.
42
+
43
+ ### Conta e times
44
+
45
+ | Comando | O que faz |
46
+ |---|---|
47
+ | `campos login [--no-browser] [--token <t>]` | Conecta a CLI à sua conta |
48
+ | `campos logout` | Desconecta este computador |
49
+ | `campos whoami` | A conta conectada |
50
+ | `campos teams` | Seus times, com o ativo marcado |
51
+ | `campos team` | Em qual time você está trabalhando |
52
+ | `campos team use [time]` | Passa a trabalhar num time (lista com setas se não disser qual; `pessoal` volta à conta pessoal) |
53
+ | `campos team members [time]` | Dono, membros com papel, convites pendentes |
54
+ | `campos team invite <email> [--role <papel>]` | Convida para o time ativo |
55
+ | `campos team create <nome>` | Cria um time e passa a trabalhar nele |
56
+
57
+ `--team <time>` em qualquer comando vale só para ele: `campos --team loja apps`.
58
+
59
+ ### Aplicações
60
+
61
+ | Comando | O que faz |
62
+ |---|---|
63
+ | `campos apps` | Lista as aplicações do time ativo |
64
+ | `campos status [app]` | Estado da aplicação da pasta; fora de uma pasta ligada, de todas |
65
+ | `campos info [app]` | Detalhes |
66
+ | `campos start \| stop \| restart [app]` | Liga, desliga, reinicia (reiniciar uma desligada liga) |
67
+ | `campos logs [app] [-f] [-n 100]` | Console (somente leitura) |
68
+ | `campos scale <memória> [--app]` | Muda a memória: `512`, `1gb` |
69
+ | `campos rename <nome> [--app]` | Muda o nome |
70
+ | `campos autorestart on\|off [--app]` | Reinício automático quando cai |
71
+ | `campos url [app] [--open]` | Endereço público |
72
+ | `campos open [app]` | Abre no painel, no navegador |
73
+ | `campos delete [app] [--yes]` | Apaga de vez (pede para digitar o nome) |
74
+
75
+ ### Pasta do projeto
76
+
77
+ | Comando | O que faz |
78
+ |---|---|
79
+ | `campos create` | Cria uma aplicação a partir da pasta (com `--yes` e as opções `--name --runtime --main --memory --web --port --subdomain --start`, sem perguntas) |
80
+ | `campos link [app]` / `campos unlink` | Liga ou desliga a pasta de uma aplicação |
81
+ | `campos deploy [--dry-run] [--no-restart] [--app <app>]` | Envia a pasta e reinicia |
82
+
83
+ Ficam de fora do envio `node_modules`, `.git`, `.campos`, `__pycache__`, `.venv`, `venv` e `.DS_Store`, além
84
+ do que estiver num `.camposignore` (um padrão por linha: `dist`, `*.log`, `src/tmp`). O `.env` vai junto.
85
+ Os arquivos são adicionados ou substituídos; o que foi apagado aqui continua no servidor (`campos files rm`).
86
+
87
+ ### Variáveis de ambiente
88
+
89
+ | Comando | O que faz |
90
+ |---|---|
91
+ | `campos env [app] [--show]` | Lista (valores escondidos sem `--show`) |
92
+ | `campos env set CHAVE=valor [...] [--restart]` | Define |
93
+ | `campos env unset CHAVE [...] [--restart]` | Remove |
94
+ | `campos env pull [arquivo] [--force]` | Baixa para um `.env` |
95
+ | `campos env push [arquivo] [--replace] [--restart]` | Envia um `.env` (mescla; `--replace` substitui tudo) |
96
+
97
+ ### Arquivos da aplicação
98
+
99
+ | Comando | O que faz |
100
+ |---|---|
101
+ | `campos files [pasta]` | Lista |
102
+ | `campos files cat <arquivo>` | Mostra um arquivo de texto |
103
+ | `campos files pull <caminho> [destino]` | Baixa um arquivo ou pasta |
104
+ | `campos files push <local> [pasta] [--restart]` | Envia um arquivo ou pasta |
105
+ | `campos files rm <caminho...> [--yes]` | Apaga (pergunta antes) |
106
+
107
+ ### Bancos de dados
108
+
109
+ | Comando | O que faz |
110
+ |---|---|
111
+ | `campos db` | Lista os bancos do time ativo |
112
+ | `campos db info <banco>` | Detalhes e string de conexão |
113
+ | `campos db url <banco>` | Só a string de conexão (para scripts) |
114
+ | `campos db password <banco> [--password <p>]` | Troca a senha (gera uma forte) e mostra uma vez |
115
+ | `campos db start \| stop \| restart <banco>` | Liga, desliga, reinicia |
116
+ | `campos db scale <banco> <memória>` / `db rename <banco> <nome>` | Memória e nome |
117
+
118
+ A string de conexão vem com `<password>` no lugar da senha: a API nunca devolve a senha.
119
+
120
+ ### Utilitários
121
+
122
+ | Comando | O que faz |
123
+ |---|---|
124
+ | `campos doctor` | Confere API, login, time ativo e a pasta |
125
+ | `campos completion [powershell\|bash\|zsh]` | Completar com Tab (comandos, opções e nomes das aplicações) |
126
+
127
+ Para instalar o Tab no PowerShell: `campos completion powershell >> $PROFILE` e abra um terminal novo.
128
+
129
+ Comandos de leitura aceitam `--json`.
130
+
131
+ ## Variáveis
132
+
133
+ | Variável | Para quê |
134
+ |---|---|
135
+ | `CAMPOS_API_URL` | Endereço da API (padrão `https://api.camposcloud.com`). Em desenvolvimento: `http://localhost:3002` |
136
+ | `CAMPOS_SITE_URL` | Endereço do site para `campos open` (padrão: o site da API) |
137
+ | `CAMPOS_TOKEN` | Token usado no lugar do guardado (CI) |
138
+ | `CAMPOS_TEAM` | Time para os comandos (como `--team`) |
139
+ | `CAMPOS_LANG` | `pt` ou `en` (padrão: idioma do sistema) |
140
+ | `CAMPOS_CONFIG_DIR` | Pasta de configuração (padrão `%APPDATA%\camposcloud` ou `~/.config/camposcloud`) |
141
+ | `CAMPOS_NO_KEYRING` | Não usar o cofre do sistema |
142
+
143
+ ## Login
144
+
145
+ `campos login` pergunta como entrar:
146
+
147
+ - **Pelo navegador** (recomendado): a CLI mostra um código e abre o site; lá você confere o código e clica
148
+ em **Autorizar**.
149
+ - **Colar um token**: crie um em **Perfil → Desenvolvedor → Tokens de acesso** (com nome e validade) e cole;
150
+ ele não aparece na tela. Direto: `campos login --token <token>`, ou `CAMPOS_TOKEN` em CI.
151
+
152
+ Pelo navegador, o acesso vale 90 dias, é renovado com o uso e aparece em **Perfil → Segurança → Sessões
153
+ ativas**, onde pode ser encerrado. Um token vale o que você escolheu ao criá-lo e é revogado na tela de
154
+ tokens. Nos dois casos a credencial fica no cofre do sistema (ou num arquivo legível só pelo seu usuário).
@@ -0,0 +1,197 @@
1
+ import { appAddress, appState, cpuLabel, getApp, listApps, memoryLabel, nodeName, powerApp, resolveApp, runtimeLabel } from "../core/apps.js";
2
+ import { t } from "../core/i18n.js";
3
+ import { localizeServerMessage } from "../core/apiErrors.js";
4
+ import { streamLogs } from "../core/logs.js";
5
+ import { pc, spinner, ui } from "../core/output.js";
6
+ import { signedInContext } from "../core/session.js";
7
+ import { findProject } from "../core/project.js";
8
+ const stateColor = {
9
+ online: pc.green,
10
+ offline: pc.dim,
11
+ suspended: pc.red,
12
+ creating: pc.yellow,
13
+ };
14
+ export const stateText = (state) => t(`state.${state}`);
15
+ const stateCell = (app) => stateColor[appState(app)](`● ${stateText(appState(app))}`);
16
+ // eslint-disable-next-line no-control-regex
17
+ const visible = (text) => text.replace(/\x1b\[[0-9;]*m/g, "");
18
+ const pad = (text, width) => text + " ".repeat(Math.max(0, width - visible(text).length));
19
+ /** A plain table: a dim header row and columns as wide as their widest cell. */
20
+ function table(headers, rows) {
21
+ const widths = headers.map((header, column) => Math.max(header.length, ...rows.map((row) => visible(row[column] ?? "").length)));
22
+ const line = (cells) => cells.map((cell, column) => pad(cell, widths[column])).join(" ").trimEnd();
23
+ return [pc.dim(line(headers)), ...rows.map(line)].join("\n");
24
+ }
25
+ export async function appsList(apiUrl, options) {
26
+ const { client, team } = await signedInContext(apiUrl);
27
+ const { apps } = await listApps(client, team?.id);
28
+ if (options.json) {
29
+ console.log(JSON.stringify(apps.map((app) => ({ id: app._id, name: app.name, state: appState(app), runtime: runtimeLabel(app), memoryMB: app.allocatedMemoryMB, address: appAddress(app) || null }))));
30
+ return 0;
31
+ }
32
+ if (team)
33
+ ui.dim(t("team.listingIn", { team: team.name }));
34
+ if (apps.length === 0) {
35
+ ui.info(team ? t("apps.noneInTeam", { team: team.name }) : t("apps.none"));
36
+ return 0;
37
+ }
38
+ ui.info(table([t("apps.col.name"), t("apps.col.state"), t("apps.col.memory"), t("apps.col.cpu"), t("apps.col.runtime"), t("apps.col.address")], apps.map((app) => [pc.bold(app.name), stateCell(app), memoryLabel(app), cpuLabel(app), runtimeLabel(app), appAddress(app)])));
39
+ ui.blank();
40
+ ui.dim(t("apps.hint"));
41
+ return 0;
42
+ }
43
+ /**
44
+ * The application a command is about: the one named; with no name, the one this folder is linked to
45
+ * (`campos link`); otherwise, in a terminal, one chosen from a list.
46
+ */
47
+ export async function findApp(apiUrl, query) {
48
+ const { client, team } = await signedInContext(apiUrl);
49
+ // A linked folder points at its application by id, whichever team is active.
50
+ const project = findProject();
51
+ if (!query && project && (!project.apiUrl || project.apiUrl === apiUrl)) {
52
+ const linked = await getApp(client, project.appId).catch(() => null);
53
+ if (linked)
54
+ return { client, app: linked };
55
+ }
56
+ const { apps } = await listApps(client, team?.id);
57
+ if (query)
58
+ return { client, app: resolveApp(apps, query) };
59
+ if (!process.stdin.isTTY || !process.stdout.isTTY || apps.length === 0)
60
+ throw new NoAppNamedError();
61
+ const { pick } = await import("../tui/Picker.js");
62
+ const chosen = await pick(t("apps.choose"), apps.map((app) => ({ label: app.name, detail: [t(`state.${appState(app)}`), runtimeLabel(app)].filter(Boolean).join(" · "), value: app })));
63
+ if (!chosen)
64
+ throw new CancelledError();
65
+ return { client, app: chosen };
66
+ }
67
+ /**
68
+ * The application a bare word after `campos` names, if any (exact name, unique start or id), in the active
69
+ * team. Null when signed out, offline, or nothing matches: then the word is treated as a mistyped command.
70
+ */
71
+ export async function findAppByWord(apiUrl, word) {
72
+ try {
73
+ const { client, team } = await signedInContext(apiUrl);
74
+ return resolveApp((await listApps(client, team?.id)).apps, word);
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ /** No application named, no linked folder and no terminal to ask in. */
81
+ export class NoAppNamedError extends Error {
82
+ }
83
+ /** The person pressed Esc in the list. */
84
+ export class CancelledError extends Error {
85
+ }
86
+ export async function appsInfo(apiUrl, query, options) {
87
+ const { client, app: found } = await findApp(apiUrl, query);
88
+ const app = await getApp(client, found._id);
89
+ if (options.json) {
90
+ console.log(JSON.stringify({ id: app._id, name: app.name, state: appState(app), runtime: runtimeLabel(app), memoryMB: app.allocatedMemoryMB, vcpu: app.allocatedVCpu, node: nodeName(app) || null, address: appAddress(app) || null, createdAt: app.createdAt ?? null }));
91
+ return 0;
92
+ }
93
+ const rows = [
94
+ [t("apps.info.state"), stateCell(app)],
95
+ [t("apps.info.runtime"), runtimeLabel(app) || "—"],
96
+ [t("apps.info.memory"), memoryLabel(app)],
97
+ [t("apps.info.cpu"), `${cpuLabel(app)} · ${app.allocatedVCpu ?? "?"} vCPU`],
98
+ [t("apps.info.address"), appAddress(app) || "—"],
99
+ [t("apps.info.node"), nodeName(app) || "—"],
100
+ [t("apps.info.id"), pc.dim(app._id)],
101
+ ];
102
+ const width = Math.max(...rows.map(([label]) => label.length));
103
+ ui.info(pc.bold(app.name));
104
+ for (const [label, value] of rows)
105
+ ui.info(` ${pc.dim(label.padEnd(width))} ${value}`);
106
+ if (app.restartRequired) {
107
+ ui.blank();
108
+ ui.info(pc.yellow(` ${t("apps.info.restartRequired")}`));
109
+ }
110
+ return 0;
111
+ }
112
+ /**
113
+ * `campos status [app]`: the named application, or the one this folder is linked to; anywhere else, the
114
+ * overview of every application.
115
+ */
116
+ export async function status(apiUrl, query, options) {
117
+ const project = findProject();
118
+ const linked = project && (!project.apiUrl || project.apiUrl === apiUrl);
119
+ if (!query && !linked)
120
+ return appsList(apiUrl, options);
121
+ return appsInfo(apiUrl, query, options);
122
+ }
123
+ export async function appsPower(apiUrl, query, requested) {
124
+ const { client, app } = await findApp(apiUrl, query);
125
+ // Restarting a stopped application means starting it: the worker refuses to restart a stopped container.
126
+ const action = requested === "restart" && appState(app) !== "online" ? "start" : requested;
127
+ const wait = spinner(t(`apps.power.${action}.doing`, { name: app.name }));
128
+ try {
129
+ await powerApp(client, app._id, action);
130
+ }
131
+ finally {
132
+ wait.stop();
133
+ }
134
+ ui.ok(t(`apps.power.${action}.done`, { name: app.name }));
135
+ return 0;
136
+ }
137
+ /** `campos logs <app>`: the recent lines; with `--follow`, keeps printing until Ctrl+C. */
138
+ export async function logs(apiUrl, query, options) {
139
+ const { client, app } = await findApp(apiUrl, query);
140
+ const tail = options.tail ? Number(options.tail) : 100;
141
+ const abort = new AbortController();
142
+ const onInterrupt = () => abort.abort();
143
+ process.once("SIGINT", onInterrupt);
144
+ // Without --follow, stop once the recent lines have arrived (the server goes quiet for a moment).
145
+ let quiet;
146
+ const settle = () => {
147
+ if (options.follow)
148
+ return;
149
+ clearTimeout(quiet);
150
+ quiet = setTimeout(() => abort.abort(), 800);
151
+ };
152
+ // Set from the event callback, so it lives in an object TypeScript does not narrow to null.
153
+ const last = { end: null };
154
+ const ended = () => last.end;
155
+ try {
156
+ // The server ends a stream after a while ("timeout") so permissions are checked again: reconnect then,
157
+ // asking only for new lines.
158
+ for (let attempt = 0;; attempt++) {
159
+ last.end = null;
160
+ await streamLogs(client, app._id, {
161
+ tail: attempt === 0 ? tail : 0,
162
+ signal: abort.signal,
163
+ onEvent: (event) => {
164
+ switch (event.type) {
165
+ case "ready":
166
+ if (options.follow && attempt === 0)
167
+ ui.dim(t("logs.following", { name: event.name }));
168
+ settle();
169
+ break;
170
+ case "log":
171
+ process.stdout.write(event.text.endsWith("\n") ? event.text : `${event.text}\n`);
172
+ settle();
173
+ break;
174
+ case "status":
175
+ ui.dim(`— ${t("logs.status", { action: event.action })}`);
176
+ break;
177
+ case "end":
178
+ last.end = event;
179
+ break;
180
+ }
181
+ },
182
+ });
183
+ if (!options.follow || abort.signal.aborted || ended()?.reason !== "timeout")
184
+ break;
185
+ }
186
+ }
187
+ finally {
188
+ clearTimeout(quiet);
189
+ process.off("SIGINT", onInterrupt);
190
+ }
191
+ const end = ended();
192
+ if (end && end.reason !== "timeout") {
193
+ ui.fail(end.message ? localizeServerMessage(end.message) : t("logs.ended"));
194
+ return 1;
195
+ }
196
+ return 0;
197
+ }
@@ -0,0 +1,194 @@
1
+ import { ApiClient, ApiError, CLI_VERSION, fetchMe } from "../core/api.js";
2
+ import { machineInfo } from "../core/config.js";
3
+ import { credentialsFile, deleteToken, readToken, saveToken } from "../core/credentials.js";
4
+ import { pollForToken, startDeviceLogin } from "../core/deviceLogin.js";
5
+ import { t } from "../core/i18n.js";
6
+ import { pc, spinner, ui } from "../core/output.js";
7
+ const isCliToken = (token) => token.startsWith("cc_cli_");
8
+ /** Where a browser can be opened: not over SSH, not in CI, not without a terminal. */
9
+ function canOpenBrowser() {
10
+ return Boolean(process.stdout.isTTY) && !process.env.SSH_CONNECTION && !process.env.SSH_TTY && !process.env.CI;
11
+ }
12
+ async function currentUser(apiUrl) {
13
+ const stored = await readToken(apiUrl);
14
+ if (!stored)
15
+ return null;
16
+ try {
17
+ return (await fetchMe(new ApiClient(apiUrl, stored.token))).user;
18
+ }
19
+ catch (error) {
20
+ if (error instanceof ApiError && error.status === 401)
21
+ return null;
22
+ throw error;
23
+ }
24
+ }
25
+ function reportStored(place) {
26
+ ui.dim(t("login.storedIn", { place: place === "keyring" ? t("login.keyring") : credentialsFile() }));
27
+ }
28
+ export async function login(apiUrl, options) {
29
+ // In a terminal, with nothing chosen yet: ask how to sign in.
30
+ if (!options.token && options.browser !== false && process.stdin.isTTY && process.stdout.isTTY) {
31
+ const already = await currentUser(apiUrl).catch(() => null);
32
+ if (already) {
33
+ ui.info(t("login.alreadyIn", { email: already.email }));
34
+ return 0;
35
+ }
36
+ const { pick, askText } = await import("../tui/Picker.js");
37
+ const how = await pick(t("login.how"), [
38
+ { label: t("login.howBrowser"), detail: t("login.recommended"), value: "browser" },
39
+ { label: t("login.howToken"), detail: t("login.howTokenDetail"), value: "token" },
40
+ ], { filter: false });
41
+ if (how === null) {
42
+ ui.info(t("login.cancelled"));
43
+ return 130;
44
+ }
45
+ if (how === "token") {
46
+ const pasted = await askText(t("login.pasteToken"), "", { mask: true });
47
+ if (!pasted) {
48
+ ui.info(t("login.cancelled"));
49
+ return 130;
50
+ }
51
+ options = { ...options, token: pasted.trim() };
52
+ }
53
+ }
54
+ // A token given directly (a developer token, or one copied for CI): check it, then keep it.
55
+ if (options.token) {
56
+ try {
57
+ const { user } = await fetchMe(new ApiClient(apiUrl, options.token));
58
+ reportStored(await saveToken(apiUrl, options.token));
59
+ ui.ok(t("login.tokenSaved", { email: user.email }));
60
+ return 0;
61
+ }
62
+ catch (error) {
63
+ if (error instanceof ApiError && error.status === 401) {
64
+ ui.fail(t("login.tokenInvalid"));
65
+ return 1;
66
+ }
67
+ throw error;
68
+ }
69
+ }
70
+ const signedIn = await currentUser(apiUrl);
71
+ if (signedIn) {
72
+ ui.info(t("login.alreadyIn", { email: signedIn.email }));
73
+ return 0;
74
+ }
75
+ const client = new ApiClient(apiUrl);
76
+ const authorization = await startDeviceLogin(client, { client: "Campos CLI", ...machineInfo(), cliVersion: CLI_VERSION });
77
+ ui.blank();
78
+ ui.info(` ${t("login.code")} ${pc.bold(pc.cyan(authorization.userCode))}`);
79
+ ui.blank();
80
+ const openBrowser = options.browser !== false && canOpenBrowser();
81
+ if (openBrowser) {
82
+ ui.dim(` ${t("login.opening")}`);
83
+ ui.dim(` ${t("login.link")} ${authorization.verificationUrlComplete}`);
84
+ try {
85
+ const { default: open } = await import("open");
86
+ await open(authorization.verificationUrlComplete);
87
+ }
88
+ catch {
89
+ // The link is on screen anyway.
90
+ }
91
+ }
92
+ else {
93
+ ui.info(` ${t("login.openManually")}`);
94
+ ui.info(` ${pc.underline(authorization.verificationUrl)}`);
95
+ }
96
+ ui.blank();
97
+ const abort = new AbortController();
98
+ const onInterrupt = () => abort.abort();
99
+ process.once("SIGINT", onInterrupt);
100
+ const wait = spinner(t("login.waiting"));
101
+ try {
102
+ const outcome = await pollForToken(client, authorization, { signal: abort.signal });
103
+ wait.stop();
104
+ switch (outcome.status) {
105
+ case "approved": {
106
+ const { user } = await fetchMe(new ApiClient(apiUrl, outcome.token));
107
+ const place = await saveToken(apiUrl, outcome.token);
108
+ ui.ok(t("login.success", { email: pc.bold(user.email) }));
109
+ reportStored(place);
110
+ return 0;
111
+ }
112
+ case "denied":
113
+ ui.fail(t("login.denied"));
114
+ return 1;
115
+ case "expired":
116
+ ui.fail(t("login.expired"));
117
+ return 1;
118
+ case "cancelled":
119
+ ui.info(t("login.cancelled"));
120
+ return 130;
121
+ }
122
+ }
123
+ finally {
124
+ wait.stop();
125
+ process.off("SIGINT", onInterrupt);
126
+ }
127
+ }
128
+ export async function logout(apiUrl) {
129
+ const stored = await readToken(apiUrl);
130
+ if (!stored) {
131
+ ui.info(t("logout.notLoggedIn"));
132
+ return 0;
133
+ }
134
+ if (stored.source === "env") {
135
+ ui.info(t("logout.envToken"));
136
+ return 1;
137
+ }
138
+ let endedOnServer = false;
139
+ if (isCliToken(stored.token)) {
140
+ try {
141
+ await new ApiClient(apiUrl, stored.token).post("/v1/cli/auth/logout");
142
+ endedOnServer = true;
143
+ }
144
+ catch (error) {
145
+ // Already ended (401) or the API is unreachable: the local copy goes anyway.
146
+ if (!(error instanceof ApiError))
147
+ ui.dim(String(error.message));
148
+ }
149
+ }
150
+ await deleteToken(apiUrl);
151
+ ui.ok(endedOnServer ? t("logout.done") : t("logout.localOnly"));
152
+ return 0;
153
+ }
154
+ export async function whoami(apiUrl, options) {
155
+ const stored = await readToken(apiUrl);
156
+ if (!stored) {
157
+ if (options.json)
158
+ console.log(JSON.stringify({ signedIn: false }));
159
+ else
160
+ ui.info(t("whoami.notLoggedIn"));
161
+ return 1;
162
+ }
163
+ let user;
164
+ try {
165
+ user = (await fetchMe(new ApiClient(apiUrl, stored.token))).user;
166
+ }
167
+ catch (error) {
168
+ if (error instanceof ApiError && error.status === 401) {
169
+ if (options.json)
170
+ console.log(JSON.stringify({ signedIn: false }));
171
+ else
172
+ ui.fail(t("error.session"));
173
+ return 1;
174
+ }
175
+ throw error;
176
+ }
177
+ const plan = user.currentSubscription?.planReference?.name ?? null;
178
+ const via = stored.source === "env" ? "env" : isCliToken(stored.token) ? "cli" : "token";
179
+ if (options.json) {
180
+ console.log(JSON.stringify({ signedIn: true, id: user._id, name: user.name ?? null, email: user.email, plan, apiUrl, via }));
181
+ return 0;
182
+ }
183
+ const rows = [
184
+ [t("whoami.name"), user.name ?? "—"],
185
+ [t("whoami.email"), user.email],
186
+ [t("whoami.plan"), plan ?? t("whoami.noPlan")],
187
+ [t("whoami.via"), t(`whoami.via.${via}`)],
188
+ [t("whoami.api"), apiUrl],
189
+ ];
190
+ const width = Math.max(...rows.map(([label]) => label.length));
191
+ for (const [label, value] of rows)
192
+ ui.info(`${pc.dim(label.padEnd(width))} ${value}`);
193
+ return 0;
194
+ }
@@ -0,0 +1,94 @@
1
+ import { listApps } from "../core/apps.js";
2
+ import { listDbs } from "../core/databases.js";
3
+ import { t } from "../core/i18n.js";
4
+ import { ui } from "../core/output.js";
5
+ import { signedInContext } from "../core/session.js";
6
+ /**
7
+ * Tab completion. The shell scripts call `campos __complete <words so far> <word being typed>`, which answers
8
+ * one candidate per line: subcommands and options of the command reached so far, and the names of the
9
+ * applications or databases when the command expects one.
10
+ */
11
+ const SCRIPTS = {
12
+ powershell: `Register-ArgumentCompleter -Native -CommandName campos -ScriptBlock {
13
+ param($wordToComplete, $commandAst, $cursorPosition)
14
+ $words = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.ToString() })
15
+ if ($wordToComplete -and $words.Count -gt 0) { $words = @($words | Select-Object -SkipLast 1) }
16
+ campos __complete @words "::" "$wordToComplete" 2>$null | ForEach-Object {
17
+ [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
18
+ }
19
+ }`,
20
+ bash: `_campos_complete() {
21
+ local cur="\${COMP_WORDS[COMP_CWORD]}"
22
+ local IFS=$'\\n'
23
+ COMPREPLY=($(campos __complete "\${COMP_WORDS[@]:1:COMP_CWORD-1}" "::" "$cur" 2>/dev/null))
24
+ }
25
+ complete -F _campos_complete campos`,
26
+ zsh: `_campos() {
27
+ local -a candidates
28
+ candidates=("\${(@f)$(campos __complete \${words[2,CURRENT-1]} "::" "\${words[CURRENT]}" 2>/dev/null)}")
29
+ compadd -a candidates
30
+ }
31
+ compdef _campos campos`,
32
+ };
33
+ const INSTALL = {
34
+ powershell: "campos completion powershell >> $PROFILE",
35
+ bash: "campos completion bash >> ~/.bashrc",
36
+ zsh: "campos completion zsh >> ~/.zshrc",
37
+ };
38
+ export function completionScript(shell) {
39
+ const wanted = (shell ?? (process.platform === "win32" ? "powershell" : "bash")).toLowerCase().replace(/^pwsh$/, "powershell");
40
+ const script = SCRIPTS[wanted];
41
+ if (!script) {
42
+ ui.fail(t("completion.unknown", { shells: Object.keys(SCRIPTS).join(", ") }));
43
+ return 1;
44
+ }
45
+ if (process.stdout.isTTY)
46
+ ui.dim(`# ${t("completion.install", { command: INSTALL[wanted] })}`);
47
+ console.log(script);
48
+ return 0;
49
+ }
50
+ /** Arguments of these commands are application or database names. */
51
+ const APP_ARGUMENT = new Set(["start", "stop", "restart", "info", "status", "logs", "delete", "open", "url", "link", "env"]);
52
+ const DB_ARGUMENT = new Set(["info", "url", "start", "stop", "restart", "password", "scale", "rename"]);
53
+ export async function complete(program, apiUrl, parsedWords) {
54
+ // The raw words: commander drops a bare "--", which is exactly what someone completing an option types.
55
+ const marker = process.argv.indexOf("__complete");
56
+ const words = marker === -1 ? parsedWords : process.argv.slice(marker + 1);
57
+ // "::" separates the words already typed from the one being typed ("--" would be eaten as end of options).
58
+ const separator = words.indexOf("::");
59
+ const typed = separator === -1 ? words : words.slice(0, separator);
60
+ const current = (separator === -1 ? "" : words[separator + 1] ?? "").toLowerCase();
61
+ // Walk down the commands named so far.
62
+ let command = program;
63
+ const path = [];
64
+ for (const word of typed) {
65
+ const next = command.commands.find((sub) => sub.name() === word || sub.aliases().includes(word));
66
+ if (!next)
67
+ break;
68
+ command = next;
69
+ path.push(next.name());
70
+ }
71
+ const candidates = [];
72
+ if (current.startsWith("-")) {
73
+ candidates.push(...command.options.flatMap((option) => [option.long, option.short]).filter((flag) => Boolean(flag)));
74
+ }
75
+ else {
76
+ candidates.push(...command.commands.filter((sub) => !sub.name().startsWith("__")).map((sub) => sub.name()));
77
+ const leaf = path[path.length - 1];
78
+ const isDb = path[0] === "db" && DB_ARGUMENT.has(leaf ?? "");
79
+ const isApp = !isDb && path.length > 0 && APP_ARGUMENT.has(leaf ?? "") && path[0] !== "db";
80
+ if (isApp || isDb) {
81
+ try {
82
+ const { client, team } = await signedInContext(apiUrl());
83
+ const names = isDb ? (await listDbs(client, team?.id)).map((db) => db.name) : (await listApps(client, team?.id)).apps.map((app) => app.name);
84
+ candidates.push(...names.map((name) => (/\s/.test(name) ? `"${name}"` : name)));
85
+ }
86
+ catch {
87
+ // offline or signed out: no names, the commands still complete
88
+ }
89
+ }
90
+ }
91
+ for (const candidate of [...new Set(candidates)].filter((item) => item.toLowerCase().replace(/^"/, "").startsWith(current)))
92
+ console.log(candidate);
93
+ return 0;
94
+ }